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
sequence
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
sequence
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
sequence
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
924574d1896020badcf30bdec95c18a84cd52b5e
5,235
java
Java
archunit/src/main/java/com/tngtech/archunit/core/domain/Formatters.java
pstanoev/ArchUnit
28b33493000c33b1831f8c638cf3f61eb2a18ebd
[ "Apache-2.0", "BSD-3-Clause" ]
4
2021-04-15T18:50:54.000Z
2021-06-02T05:42:19.000Z
archunit/src/main/java/com/tngtech/archunit/core/domain/Formatters.java
OLibutzki/ArchUnit
c5226097ec35be15706cdfea38149d97b4698888
[ "Apache-2.0", "BSD-3-Clause" ]
25
2021-02-10T06:51:00.000Z
2021-05-12T21:23:46.000Z
archunit/src/main/java/com/tngtech/archunit/core/domain/Formatters.java
OLibutzki/ArchUnit
c5226097ec35be15706cdfea38149d97b4698888
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
41.547619
117
0.686724
1,003,380
/* * Copyright 2014-2021 TNG Technology Consulting GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tngtech.archunit.core.domain; import java.util.ArrayList; import java.util.List; import com.google.common.base.Joiner; import com.tngtech.archunit.PublicAPI; import com.tngtech.archunit.core.domain.properties.HasName; import static com.tngtech.archunit.PublicAPI.Usage.ACCESS; public final class Formatters { private Formatters() { } /** * @param ownerName Class name where the method is declared * @param methodName Name of the method * @param parameters Parameters of the method * @return Arguments formatted as "ownerName.methodName(fqn.param1, fqn.param2, ...)" */ @PublicAPI(usage = ACCESS) public static String formatMethod(String ownerName, String methodName, JavaClassList parameters) { return format(ownerName, methodName, formatMethodParameters(parameters)); } private static String format(String ownerName, String methodName, String parameters) { return ownerName + "." + methodName + "(" + parameters + ")"; } /** * @param ownerName Class name where the method is declared (may be simple or fqn) * @param methodName Name of the method * @param parameters Names of parameter types (may be simple or fqn) * @return Arguments formatted as "simple(ownerName).methodName(simple(param1), simple(param2), ...)", * where simple(..) ensures the simple type name (compare {@link #ensureSimpleName(String)}) */ @PublicAPI(usage = ACCESS) public static String formatMethodSimple(String ownerName, String methodName, List<String> parameters) { List<String> simpleParams = new ArrayList<>(); for (String parameter : parameters) { simpleParams.add(ensureSimpleName(parameter)); } return formatMethod(ensureSimpleName(ownerName), methodName, simpleParams); } /** * @param ownerName Class name where the method is declared * @param methodName Name of the method * @param parameters Names of parameter types * @return Arguments formatted (as passed) as "ownerName.methodName(param1, param2, ...)" */ @PublicAPI(usage = ACCESS) public static String formatMethod(String ownerName, String methodName, List<String> parameters) { return format(ownerName, methodName, formatMethodParameterTypeNames(parameters)); } private static String formatMethodParameters(List<? extends HasName> parameters) { List<String> names = new ArrayList<>(); for (HasName type : parameters) { names.add(type.getName()); } return formatMethodParameterTypeNames(names); } /** * @param typeNames List of method parameter type names * @return Arguments formatted as "param1, param2, ..." */ @PublicAPI(usage = ACCESS) public static String formatMethodParameterTypeNames(List<String> typeNames) { return Joiner.on(", ").join(typeNames); } /** * @param typeNames List of throws declaration type names * @return Arguments formatted as "param1, param2, ..." */ @PublicAPI(usage = ACCESS) public static String formatThrowsDeclarationTypeNames(List<String> typeNames) { return Joiner.on(", ").join(typeNames); } // Excluding the '$' character might be incorrect, but since '$' is a valid character of a class name // and also the delimiter within the fully qualified name between an inner class and its enclosing class, // there is no clean way to derive the simple name from just a fully qualified class name without // further information // Luckily for imported classes we can read this information from the bytecode /** * @param name A possibly fully qualified class name * @return A best guess of the simple name, i.e. prefixes like 'a.b.c.' cut off, 'Some$' of 'Some$Inner' as well. * Returns an empty String, if the name belongs to an anonymous class (e.g. some.Type$1). */ @PublicAPI(usage = ACCESS) public static String ensureSimpleName(String name) { int lastIndexOfDot = name.lastIndexOf('.'); String partAfterDot = lastIndexOfDot >= 0 ? name.substring(lastIndexOfDot + 1) : name; int lastIndexOf$ = partAfterDot.lastIndexOf('$'); String simpleNameCandidate = lastIndexOf$ >= 0 ? partAfterDot.substring(lastIndexOf$ + 1) : partAfterDot; for (int i = 0; i < simpleNameCandidate.length(); i++) { if (Character.isJavaIdentifierStart(simpleNameCandidate.charAt(i))) { return simpleNameCandidate.substring(i); } } return ""; } }
9245755f9cbc334097f8ff5f686b02b366b4e72b
6,024
java
Java
app/src/main/java/org/andengine/extension/multiplayer/protocol/server/Server.java
the3deers/AndEngine
2a7c0004c6dde4223e1f356d05460f6e90c0de01
[ "Apache-2.0" ]
1
2020-10-10T07:54:23.000Z
2020-10-10T07:54:23.000Z
app/src/main/java/org/andengine/extension/multiplayer/protocol/server/Server.java
the3deers/AndEngine
2a7c0004c6dde4223e1f356d05460f6e90c0de01
[ "Apache-2.0" ]
null
null
null
app/src/main/java/org/andengine/extension/multiplayer/protocol/server/Server.java
the3deers/AndEngine
2a7c0004c6dde4223e1f356d05460f6e90c0de01
[ "Apache-2.0" ]
1
2020-11-06T08:07:15.000Z
2020-11-06T08:07:15.000Z
31.705263
140
0.633134
1,003,381
package org.andengine.extension.multiplayer.protocol.server; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import org.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage; import org.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.andengine.extension.multiplayer.protocol.server.connector.ClientConnector.IClientConnectorListener; import org.andengine.extension.multiplayer.protocol.shared.Connection; import org.andengine.util.adt.list.SmartList; import org.andengine.util.debug.Debug; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:36:54 - 18.09.2009 */ public abstract class Server<C extends Connection, CC extends ClientConnector<C>> extends Thread { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected IServerListener<? extends Server<C, CC>> mServerListener; private final AtomicBoolean mRunning = new AtomicBoolean(false); private final AtomicBoolean mTerminated = new AtomicBoolean(false); protected final SmartList<CC> mClientConnectors = new SmartList<CC>(); protected IClientConnectorListener<C> mClientConnectorListener; // =========================================================== // Constructors // =========================================================== public Server(final IClientConnectorListener<C> pClientConnectorListener, final IServerListener<? extends Server<C, CC>> pServerListener) { this.mServerListener = pServerListener; this.mClientConnectorListener = pClientConnectorListener; this.initName(); } private void initName() { this.setName(this.getClass().getName()); } // =========================================================== // Getter & Setter // =========================================================== public boolean isRunning() { return this.mRunning.get(); } public boolean isTerminated() { return this.mTerminated.get(); } public IClientConnectorListener<C> getClientConnectorListener() { return this.mClientConnectorListener; } public void setClientConnectorListener(final IClientConnectorListener<C> pClientConnectorListener) { this.mClientConnectorListener = pClientConnectorListener; } public IServerListener<? extends Server<C, ? extends ClientConnector<C>>> getServerListener() { return this.mServerListener; } protected void setServerListener(final IServerListener<? extends Server<C, CC>> pServerListener) { this.mServerListener = pServerListener; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract void onStart() throws IOException; protected abstract CC acceptClientConnector() throws IOException; protected abstract void onTerminate(); protected abstract void onException(Throwable pThrowable); @Override public void run() { try { this.onStart(); this.mRunning.set(true); // android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_DEFAULT); // TODO What ThreadPriority makes sense here? /* Endless waiting for incoming clients. */ while (!Thread.interrupted() && this.mRunning.get() && !this.mTerminated.get()) { try { final CC clientConnector = this.acceptClientConnector(); clientConnector.addClientConnectorListener(new IClientConnectorListener<C>() { @Override public void onStarted(final ClientConnector<C> pClientConnector) { onAddClientConnector(clientConnector); } @Override public void onTerminated(final ClientConnector<C> pClientConnector) { onRemoveClientConnector(clientConnector); } }); clientConnector.addClientConnectorListener(this.mClientConnectorListener); /* Start the ClientConnector(-Thread) so it starts receiving messages. */ clientConnector.start(); } catch (final Throwable pThrowable) { this.onException(pThrowable); } } } catch (final Throwable pThrowable) { this.onException(pThrowable); } finally { this.terminate(); } } @Override protected void finalize() throws Throwable { this.terminate(); super.finalize(); } // =========================================================== // Methods // =========================================================== private synchronized void onAddClientConnector(final CC pClientConnector) { Server.this.mClientConnectors.add(pClientConnector); } private synchronized void onRemoveClientConnector(final CC pClientConnector) { Server.this.mClientConnectors.remove(pClientConnector); } public void terminate() { if (!this.mTerminated.getAndSet(true)) { this.mRunning.set(false); try { /* First interrupt all Clients. */ final SmartList<CC> clientConnectors = this.mClientConnectors; for (int i = 0; i < clientConnectors.size(); i++) { clientConnectors.get(i).terminate(); } clientConnectors.clear(); } catch (final Exception e) { this.onException(e); } try { Thread.sleep(1000); } catch (final InterruptedException e) { Debug.e(e); } this.interrupt(); this.onTerminate(); } } public synchronized void sendBroadcastServerMessage(final IServerMessage pServerMessage) throws IOException { if (this.mRunning.get()) { final SmartList<CC> clientConnectors = this.mClientConnectors; for (int i = 0; i < clientConnectors.size(); i++) { try { clientConnectors.get(i).sendServerMessage(pServerMessage); } catch (final IOException e) { this.onException(e); } } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
924575b8aa420d8721417c3d2f5375e5cb79edab
451
java
Java
task7/src/cn/hyn123/service/CaptchaService.java
sweetalin/abbey
578e04926df74f113fa668d69288aeeb772e078d
[ "Apache-2.0" ]
1
2017-08-30T06:27:45.000Z
2017-08-30T06:27:45.000Z
task7/src/cn/hyn123/service/CaptchaService.java
sweetalin/abbey
578e04926df74f113fa668d69288aeeb772e078d
[ "Apache-2.0" ]
null
null
null
task7/src/cn/hyn123/service/CaptchaService.java
sweetalin/abbey
578e04926df74f113fa668d69288aeeb772e078d
[ "Apache-2.0" ]
3
2017-08-15T08:35:58.000Z
2019-01-01T14:38:20.000Z
20.5
94
0.764967
1,003,382
package cn.hyn123.service; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; public interface CaptchaService { /** * 生成验证码 * @param request * @param response * @throws IOException */ public void genernateCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws IOException; }
92457618d55e58034bccd4d53e612f07f4a8389c
770
java
Java
app/src/main/java/ru/monkeys/monkeyapp/engine/thread/BaseGameThread.java
metalink94/MonkeyApp
a77f648ac675d96ac447c1b36f083fef4a3fbf6a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ru/monkeys/monkeyapp/engine/thread/BaseGameThread.java
metalink94/MonkeyApp
a77f648ac675d96ac447c1b36f083fef4a3fbf6a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ru/monkeys/monkeyapp/engine/thread/BaseGameThread.java
metalink94/MonkeyApp
a77f648ac675d96ac447c1b36f083fef4a3fbf6a
[ "Apache-2.0" ]
null
null
null
25.666667
85
0.715584
1,003,383
package ru.monkeys.monkeyapp.engine.thread; import android.view.SurfaceHolder; import ru.monkeys.monkeyapp.engine.AbstractGamePanel; public abstract class BaseGameThread extends Thread { // Store references to the game panel and holder protected SurfaceHolder surfaceHolder; protected AbstractGamePanel gamePanel; // flag to hold game state protected boolean running; public void setRunning(boolean running) { this.running = running; } public boolean isRunning() { return this.running; } public BaseGameThread(SurfaceHolder surfaceHolder, AbstractGamePanel gamePanel) { super(); this.surfaceHolder = surfaceHolder; this.gamePanel = gamePanel; } public abstract void run(); }
9245766f48b4dcb32928a55c9a6b3fbcece6b879
2,668
java
Java
WearScript/src/main/java/com/dappervision/wearscript/managers/ManagerManager.java
wearscript/wearscript-android
92267dd04c99cc97bc175f911d8e552679b88684
[ "Apache-2.0" ]
27
2015-01-01T01:55:53.000Z
2021-12-14T18:00:39.000Z
WearScript/src/main/java/com/dappervision/wearscript/managers/ManagerManager.java
wearscript/wearscript-android
92267dd04c99cc97bc175f911d8e552679b88684
[ "Apache-2.0" ]
2
2015-03-10T17:27:47.000Z
2019-03-15T07:39:54.000Z
WearScript/src/main/java/com/dappervision/wearscript/managers/ManagerManager.java
wearscript/wearscript-android
92267dd04c99cc97bc175f911d8e552679b88684
[ "Apache-2.0" ]
9
2015-03-10T18:00:44.000Z
2021-05-30T08:46:57.000Z
29.318681
162
0.621814
1,003,384
package com.dappervision.wearscript.managers; import android.content.pm.PackageManager; import com.dappervision.wearscript.BackgroundService; import com.dappervision.wearscript.HardwareDetector; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ManagerManager { private static ManagerManager singleton; Map<String, Manager> managers; private ManagerManager() { managers = new ConcurrentHashMap<String, Manager>(); } public static ManagerManager get() { if (singleton != null) { return singleton; } singleton = new ManagerManager(); return singleton; } public static boolean hasManager(Class<? extends Manager> c) { return get().get(c) != null; } public void newManagers(BackgroundService bs) { add(new OpenCVManager(bs)); add(new DataManager(bs)); add(new CameraManager(bs)); add(new BarcodeManager(bs)); add(new WifiManager(bs)); add(new AudioManager(bs)); add(new BluetoothManager(bs)); add(new SpeechManager(bs)); add(new ConnectionManager(bs)); add(new WarpManager(bs)); add(new LiveCardManager(bs)); add(new PicarusManager(bs)); //Really just FEATURE_CAMERA_ANY should work, but someone is a dumb head and broke Android. if(bs.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY) || bs.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) { add(new CameraManager(bs)); add(new BarcodeManager(bs)); } if(bs.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) { add(new BluetoothManager(bs)); } if (HardwareDetector.hasGDK) { add(new CardTreeManager(bs)); add(new EyeManager(bs)); } } public void add(Manager manager) { String name = manager.getClass().getName(); Manager old = managers.remove(name); if (old != null) old.shutdown(); managers.put(name, manager); } public Manager remove(Class<? extends Manager> manager) { String name = manager.getName(); return managers.remove(name); } public Manager get(Class<? extends Manager> c) { return managers.get(c.getName()); } public void resetAll() { for (Manager m : managers.values()) { m.reset(); } } public void shutdownAll() { for (String name : managers.keySet()) { Manager m = managers.remove(name); m.shutdown(); } } }
9245769246cf5091b27a8dd29a5ba532a5307862
551
java
Java
mobile_app1/module949/src/main/java/module949packageJava0/Foo494.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
70
2021-01-22T16:48:06.000Z
2022-02-16T10:37:33.000Z
mobile_app1/module949/src/main/java/module949packageJava0/Foo494.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
16
2021-01-22T20:52:52.000Z
2021-08-09T17:51:24.000Z
mobile_app1/module949/src/main/java/module949packageJava0/Foo494.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
5
2021-01-26T13:53:49.000Z
2021-08-11T20:10:57.000Z
11.02
46
0.540835
1,003,385
package module949packageJava0; import java.lang.Integer; public class Foo494 { Integer int0; Integer int1; public void foo0() { new module949packageJava0.Foo493().foo9(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } public void foo5() { foo4(); } public void foo6() { foo5(); } public void foo7() { foo6(); } public void foo8() { foo7(); } public void foo9() { foo8(); } }
9245772dea3f0bc93126d26eb2359dc457f5ccd1
162
java
Java
src/test/java/com/github/onotoliy/fuzzycontroller/cm/package-info.java
onotoliy/fuzzy-controller
8b2bb4699638ec29ef9d6dcdd519a17481a61658
[ "Apache-2.0" ]
null
null
null
src/test/java/com/github/onotoliy/fuzzycontroller/cm/package-info.java
onotoliy/fuzzy-controller
8b2bb4699638ec29ef9d6dcdd519a17481a61658
[ "Apache-2.0" ]
1
2019-08-23T06:21:13.000Z
2019-08-23T06:21:13.000Z
src/test/java/com/github/onotoliy/fuzzycontroller/cm/package-info.java
onotoliy/fuzzy-controller
8b2bb4699638ec29ef9d6dcdd519a17481a61658
[ "Apache-2.0" ]
null
null
null
23.142857
71
0.777778
1,003,386
/** * Пакет содержит классы тестирующие стандартные методы дефаззификации. * * @author Anatoliy Pokhresnyi */ package com.github.onotoliy.fuzzycontroller.cm;
92457769ce952b6690f414319eb7d212678154ed
2,841
java
Java
src/test/java/com/mtlevine0/handler/RequestRouterStaticServerDisabledTest.java
mtlevine0/httpj
7ccba80475d06b3c4068ebbee172dc55730c58c2
[ "MIT" ]
2
2021-09-07T01:31:20.000Z
2022-02-06T18:06:32.000Z
src/test/java/com/mtlevine0/handler/RequestRouterStaticServerDisabledTest.java
mtlevine0/httpj
7ccba80475d06b3c4068ebbee172dc55730c58c2
[ "MIT" ]
null
null
null
src/test/java/com/mtlevine0/handler/RequestRouterStaticServerDisabledTest.java
mtlevine0/httpj
7ccba80475d06b3c4068ebbee172dc55730c58c2
[ "MIT" ]
null
null
null
43.707692
136
0.773671
1,003,387
package com.mtlevine0.handler; import com.mtlevine0.FeatureFlag; import com.mtlevine0.FeatureFlagContext; import com.mtlevine0.exception.MethodNotAllowedException; import com.mtlevine0.request.HttpMethod; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import java.io.IOException; public class RequestRouterStaticServerDisabledTest extends RequestRouterTest { @Before public void setup() { basePath = "../httpj"; FeatureFlagContext.getInstance().disableFeature(FeatureFlag.STATIC_FILE_SERVER); requestRouter = new RequestRouter(basePath); requestRouter.registerRoute("/test", HttpMethod.GET, new CustomHandler()); } @Test public void ShouldExecuteRequestHandler_WhenHttpRequestMatchesRegisteredRoute() throws IOException { assertEquals(getBasicHttpResponse("Custom Body!"), requestRouter.route(getBasicGetRequest("/test"))); } @Test(expected = IllegalArgumentException.class) public void ShouldThrowIllegalArgumentException_WhenRegisteringCustomRequestHandlerToWildCardPathRoute() { requestRouter.registerRoute("*", HttpMethod.GET, new CustomHandler()); } @Test public void ShouldReturn200_WhenCustomRouteRegisteredAndRequestIsHead() throws IOException { assertEquals(getBasicHttpResponse(null), requestRouter.route(getBasicRequest(HttpMethod.HEAD,"/test"))); } @Test(expected = IllegalArgumentException.class) public void ShouldThrowIllegalArgumentException_WhenRegisteringRequestHandlerWithDuplicateRoute() { requestRouter.registerRoute("/test", HttpMethod.GET, new CustomHandler()); requestRouter.registerRoute("/test", HttpMethod.GET, new CustomHandler()); } @Test public void ShouldExecuteRequestHandler_WhenRequestHandlerRegisteredToWildCardRouteAndHttpRequestMatchesRoute() throws IOException { requestRouter.registerRoute("*", HttpMethod.GET, new DefaultRequestHandler()); assertEquals(getBasicHttpResponse("Default Body!"), requestRouter.route(getBasicGetRequest("/"))); } @Test public void ShouldExecuteWildCardPathCustomRequestHandler_WhenRequestPathDoesNotMatchStaticPathRoutes() throws IOException { FeatureFlagContext.getInstance().disableFeature(FeatureFlag.STATIC_FILE_SERVER); requestRouter.registerRoute("*", HttpMethod.GET, new DefaultRequestHandler()); assertEquals(getBasicHttpResponse("Default Body!"), requestRouter.route(getBasicGetRequest("/"))); } @Test(expected = MethodNotAllowedException.class) public void ShouldThrowMethodNotAllowedException_WhenRequestDoesNotMatchRoute() throws IOException { FeatureFlagContext.getInstance().disableFeature(FeatureFlag.STATIC_FILE_SERVER); requestRouter.route(getBasicGetRequest("/does-not-exist")); } }
924578da9b400a9b5703d9c3df8509bffeea0326
9,970
java
Java
src/main/java/jds/bibliocraft/models/BiblioModelSimple.java
RPMYT/BiblioCraft-Source
9a4f963dcb897aed3d58a911383749c69d7e1b28
[ "MIT" ]
15
2021-12-26T02:36:47.000Z
2022-03-21T18:31:31.000Z
src/main/java/jds/bibliocraft/models/BiblioModelSimple.java
RPMYT/BiblioCraft-Source
9a4f963dcb897aed3d58a911383749c69d7e1b28
[ "MIT" ]
13
2022-01-04T15:33:53.000Z
2022-03-19T09:48:45.000Z
src/main/java/jds/bibliocraft/models/BiblioModelSimple.java
RPMYT/BiblioCraft-Source
9a4f963dcb897aed3d58a911383749c69d7e1b28
[ "MIT" ]
14
2021-12-26T19:03:03.000Z
2022-03-22T00:43:24.000Z
29.58457
146
0.680943
1,003,388
package jds.bibliocraft.models; import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import javax.vecmath.Matrix4f; import javax.vecmath.Quat4f; import javax.vecmath.Vector3f; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.commons.lang3.tuple.Pair; import jds.bibliocraft.helpers.ModelCache; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType; import net.minecraft.client.renderer.block.model.ItemOverride; import net.minecraft.client.renderer.block.model.ItemOverrideList; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; //import net.minecraftforge.client.model.IBakedModel; import net.minecraftforge.client.model.IModel; //import net.minecraftforge.client.model.ISmartBlockModel; //import net.minecraftforge.client.model.ISmartItemModel; import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.client.model.obj.OBJModel; import net.minecraftforge.common.model.TRSRTransformation; import net.minecraftforge.common.property.IExtendedBlockState; public abstract class BiblioModelSimple implements IBakedModel //, ISmartBlockModel, ISmartItemModel { private IModel model = null; private IBakedModel baseModel; private String modelLocation = " "; private CustomItemOverrideList overrides = new CustomItemOverrideList(); public IBakedModel wrapper; private ModelCache cache; private boolean gotOBJ = false; public BiblioModelSimple(String modelLoc) { this.modelLocation = modelLoc; this.wrapper = this; this.cache = new ModelCache(); } private void getModel(IBlockState state, int attempt) { if (this.model == null || (this.model != null && !this.model.toString().contains("obj.OBJModel"))) { try { this.model = ModelLoaderRegistry.getModel(new ResourceLocation(this.modelLocation)); model = model.process(ImmutableMap.of("flip-v", "true")); gotOBJ = true; } catch (Exception e) { this.model = ModelLoaderRegistry.getMissingModel(); gotOBJ = false; if (attempt < 6) { getModel(state, attempt + 1); return; } } } OBJModel.OBJState modelState = new OBJModel.OBJState(getDefaultVisiableModelParts(), true); if (state != null && state instanceof IExtendedBlockState) { IExtendedBlockState exState = (IExtendedBlockState)state; if (exState.getUnlistedNames().contains(OBJModel.OBJProperty.INSTANCE)) { modelState = exState.getValue(OBJModel.OBJProperty.INSTANCE); } if (modelState == null) { return; } getAdditionalModelStateStuff(exState); } Function<ResourceLocation, TextureAtlasSprite> texture = textureGetter; if (state != null && state instanceof IExtendedBlockState) { IBakedModel bakedModel = model.bake(modelState, DefaultVertexFormats.ITEM, texture); this.baseModel = bakedModel; } else { if (cache.hasModel(texture.toString())) { this.baseModel = cache.getCurrentMatch(); } else { IBakedModel bakedModel = model.bake(modelState, DefaultVertexFormats.ITEM, texture); if (gotOBJ) cache.addToCache(bakedModel, texture.toString()); this.baseModel = bakedModel; } } //System.out.println(test.toString()); } public void getAdditionalModelStateStuff(IExtendedBlockState state) { } public List<String> getDefaultVisiableModelParts() { List<String> modelParts = Lists.newArrayList(OBJModel.Group.ALL); return modelParts; } protected Function<ResourceLocation, TextureAtlasSprite> textureGetter = new Function<ResourceLocation, TextureAtlasSprite>() { @Override public TextureAtlasSprite apply(ResourceLocation location) { // the color thing doesnt work right return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(getTextureLocation(location.toString())); } }; public String getTextureLocation(String resourceLocation) { return resourceLocation; } @Override public boolean isAmbientOcclusion() { return false; } @Override public boolean isGui3d() { return false; } @Override public boolean isBuiltInRenderer() { return false; } @Override public TextureAtlasSprite getParticleTexture() { try { return this.baseModel.getParticleTexture(); } catch (NullPointerException e) { return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:blocks/planks_oak"); } } @Override public ItemCameraTransforms getItemCameraTransforms() { return ItemCameraTransforms.DEFAULT; } @Override public Pair<? extends IBakedModel, Matrix4f> handlePerspective(TransformType cameraTransformType) { TRSRTransformation transform = new TRSRTransformation(new Vector3f(0.0f, 0.0f, 0.0f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f), new Vector3f(1.0f, 1.0f, 1.0f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f)); switch (cameraTransformType) { case FIRST_PERSON_RIGHT_HAND: { transform = new TRSRTransformation(new Vector3f(1.4f, 0.2f, -1.5f), new Quat4f(0.0f, 1.0f, 0.0f, 1.0f), new Vector3f(1.0f, 1.0f, 1.0f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f)); transform = getTweakedRIGHTHANDTransform(transform); break; } case FIRST_PERSON_LEFT_HAND: { transform = new TRSRTransformation(new Vector3f(1.4f, 0.2f, 0.5f), new Quat4f(0.0f, 1.0f, 0.0f, 1.0f), new Vector3f(1.0f, 1.0f, 1.0f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f)); transform = getTweakedLEFTHANDTransform(transform); break; } case THIRD_PERSON_RIGHT_HAND: { transform = new TRSRTransformation(new Vector3f(0.6f, 0.8f, 0.25f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f), new Vector3f(0.65f, 0.65f, 0.65f), new Quat4f(1.0f, 0.0f, 0.0f, 1.0f)); transform = transform.compose(new TRSRTransformation(new Vector3f(0.0f, 0.0f, 0.0f), new Quat4f(0.0f, 1.0f, 0.0f, 1.0f), new Vector3f(1.0f, 1.0f, 1.0f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f))); transform = getTweakedRIGHTHANDTransform(transform); break; } case THIRD_PERSON_LEFT_HAND: { transform = new TRSRTransformation(new Vector3f(0.65f, -0.5f, 0.25f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f), new Vector3f(0.65f, 0.65f, 0.65f), new Quat4f(1.0f, 0.0f, 0.0f, 1.0f)); transform = transform.compose(new TRSRTransformation(new Vector3f(0.0f, 0.0f, 0.0f), new Quat4f(0.0f, 1.0f, 0.0f, 1.0f), new Vector3f(1.0f, 1.0f, 1.0f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f))); transform = getTweakedLEFTHANDTransform(transform); break; } case GUI: { transform = new TRSRTransformation(new Vector3f(0.0f, 0.26f, 0.0f), new Quat4f(0.25f, 1.0f, 0.25f, 1.0f), new Vector3f(0.75f, 0.75f, 0.75f), new Quat4f(0.0f, 0.4f, 0.0f, 1.0f)); transform = getTweakedGUITransform(transform); break; } case GROUND: { transform = new TRSRTransformation(new Vector3f(0.5f, 0.05f, 0.5f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f), new Vector3f(0.5f, 0.5f, 0.5f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f)); break; } case FIXED: { transform = new TRSRTransformation(new Vector3f(-0.75f, 0.12f, 0.75f), new Quat4f(0.0f, -1.0f, 0.0f, 1.0f), new Vector3f(0.75f, 0.75f, 0.75f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f)); break; } case NONE: { transform = new TRSRTransformation(new Vector3f(0.0f, 0.0f, 0.0f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f), new Vector3f(1.0f, 1.0f, 1.0f), new Quat4f(0.0f, 0.0f, 0.0f, 1.0f)); } default: break; } transform = getTweakedMasterTransfer(transform); return Pair.of(this, transform.getMatrix()); } public TRSRTransformation getTweakedMasterTransfer(TRSRTransformation transform) { return transform; } public TRSRTransformation getTweakedGUITransform(TRSRTransformation transform) { return transform; } public TRSRTransformation getTweakedLEFTHANDTransform(TRSRTransformation transform) { return transform; } public TRSRTransformation getTweakedRIGHTHANDTransform(TRSRTransformation transform) { return transform; } @Override public List<BakedQuad> getQuads(IBlockState state, EnumFacing side, long rand) { getModel(state, 0); try { List<BakedQuad> q = this.baseModel.getQuads(state, side, rand); return q; } catch (NullPointerException e) { return new ArrayList<BakedQuad>(); } } @Override public ItemOverrideList getOverrides() { return overrides; } private class CustomItemOverrideList extends ItemOverrideList { private CustomItemOverrideList() { super(ImmutableList.<ItemOverride>of()); } @Nonnull @Override public IBakedModel handleItemState(@Nonnull IBakedModel originalModel, ItemStack stack, @Nonnull World world, @Nonnull EntityLivingBase entity) { getModel(null, 0); return wrapper; } } }
924579149e1179c58fc87a8baeda312f276e4923
970
java
Java
POO/overloadConstructors/src/broTutorials/Pizza.java
hugoresende27/Java
1edc5f625cc76b184e32938847ebf1be3d137f63
[ "MIT" ]
null
null
null
POO/overloadConstructors/src/broTutorials/Pizza.java
hugoresende27/Java
1edc5f625cc76b184e32938847ebf1be3d137f63
[ "MIT" ]
null
null
null
POO/overloadConstructors/src/broTutorials/Pizza.java
hugoresende27/Java
1edc5f625cc76b184e32938847ebf1be3d137f63
[ "MIT" ]
null
null
null
19.019608
69
0.568041
1,003,389
package overloadConstructors; public class Pizza { /////////ATRIBUTOS GLOBAIS String massa; String molho; String queijo; String topping; //////////METODO CONSTRUTOR ////////METODO OVERLOADED SEM PARAMETROS Pizza(){ } ////////METODO OVERLOADED SÓ COM MASSA Pizza(String massa){ this.massa = massa; } ////////METODO OVERLOADED SEM TOPPING e SEM QUEIJO Pizza(String massa, String molho){ this.massa = massa; this.molho = molho; } ////////METODO OVERLOADED SEM TOPPING Pizza(String massa, String molho, String queijo){ this.massa = massa; this.molho = molho; this.queijo = queijo; } /////////METODO COMPLETO, 4 PARAMETROS Pizza(String massa, String molho, String queijo, String topping){ this.massa = massa; this.molho = molho; this.queijo = queijo; this.topping = topping; } }
924579991ffda20df354ece03adf735cfc700455
4,052
java
Java
jykits-core/src/main/java/com/junya/core/lang/Range.java
smiletou99/JYKits
388494d831f34eb0453ad1b8eb9cd3cf78021990
[ "Apache-2.0" ]
null
null
null
jykits-core/src/main/java/com/junya/core/lang/Range.java
smiletou99/JYKits
388494d831f34eb0453ad1b8eb9cd3cf78021990
[ "Apache-2.0" ]
null
null
null
jykits-core/src/main/java/com/junya/core/lang/Range.java
smiletou99/JYKits
388494d831f34eb0453ad1b8eb9cd3cf78021990
[ "Apache-2.0" ]
null
null
null
18.934579
95
0.635982
1,003,390
package com.junya.core.lang; import java.io.Serializable; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.junya.core.thread.lock.NoLock; /** * 范围生成器。根据给定的初始值、结束值和步进生成一个步进列表生成器<br> * 由于用户自行实现{@link Steper}来定义步进,因此Range本身无法判定边界(是否达到end),需在step实现边界判定逻辑。 * * <p> * 此类使用{@link ReentrantReadWriteLock}保证线程安全 * </p> * * @author zhangchao * * @param <T> 生成范围对象的类型 */ public class Range<T> implements Iterable<T>, Iterator<T>, Serializable { private static final long serialVersionUID = 1L; /** 锁保证线程安全 */ private Lock lock = new ReentrantLock(); /** 起始对象 */ private T start; /** 结束对象 */ private T end; /** 当前对象 */ private T current; /** 下一个对象 */ private T next; /** 步进 */ private Steper<T> steper; /** 索引 */ private int index = 0; /** 是否包含第一个元素 */ private boolean includeStart; /** 是否包含最后一个元素 */ private boolean includeEnd; /** * 构造 * * @param start 起始对象 * @param steper 步进 */ public Range(T start, Steper<T> steper) { this(start, null, steper); } /** * 构造 * * @param start 起始对象(包含) * @param end 结束对象(包含) * @param steper 步进 */ public Range(T start, T end, Steper<T> steper) { this(start, end, steper, true, true); } /** * 构造 * * @param start 起始对象 * @param end 结束对象 * @param steper 步进 * @param isIncludeStart 是否包含第一个元素 * @param isIncludeEnd 是否包含最后一个元素 */ public Range(T start, T end, Steper<T> steper, boolean isIncludeStart, boolean isIncludeEnd) { this.start = start; this.current = start; this.end = end; this.steper = steper; this.next = safeStep(this.current); this.includeStart = isIncludeStart; includeEnd = true; this.includeEnd = isIncludeEnd; } /** * 禁用锁,调用此方法后不在 使用锁保护 * * @return this * @since 2.0.3 */ public Range<T> disableLock() { this.lock = new NoLock(); return this; } @Override public boolean hasNext() { lock.lock(); try { if(0 == this.index && this.includeStart) { return true; } if (null == this.next) { return false; } else if (false == includeEnd && this.next.equals(this.end)) { return false; } } finally { lock.unlock(); } return true; } @Override public T next() { lock.lock(); try { if (false == this.hasNext()) { throw new NoSuchElementException("Has no next range!"); } return nextUncheck(); } finally { lock.unlock(); } } /** * 获取下一个元素,并将下下个元素准备好 */ private T nextUncheck() { if (0 != this.index || false == this.includeStart) { // 非第一个元素或不包含第一个元素增加步进 this.current = this.next; if (null != this.current) { this.next = safeStep(this.next); } } index++; return this.current; } /** * 不抛异常的获取下一步进的元素,如果获取失败返回{@code null} * * @param base 上一个元素 * @return 下一步进 */ private T safeStep(T base) { T next = null; try { next = steper.step(base, this.end, this.index); } catch (Exception e) { // ignore } return next; } @Override public void remove() { throw new UnsupportedOperationException("Can not remove ranged element!"); } @Override public Iterator<T> iterator() { return this; } /** * 重置{@link Range} * * @return this */ public Range<T> reset() { lock.lock(); try { this.current = this.start; this.index = 0; } finally { lock.unlock(); } return this; } /** * 步进接口,此接口用于实现如何对一个对象按照指定步进增加步进<br> * 步进接口可以定义以下逻辑: * * <pre> * 1、步进规则,即对象如何做步进 * 2、步进大小,通过实现此接口,在实现类中定义一个对象属性,可灵活定义步进大小 * 3、限制range个数,通过实现此接口,在实现类中定义一个对象属性,可灵活定义limit,限制range个数 * </pre> * * @author zhangchao * * @param <T> 需要增加步进的对象 */ public interface Steper<T> { /** * 增加步进<br> * 增加步进后的返回值如果为{@code null}则表示步进结束<br> * 用户需根据end参数自行定义边界,当达到边界时返回null表示结束,否则Range中边界对象无效,会导致无限循环 * * @param current 上一次增加步进后的基础对象 * @param end 结束对象 * @param index 当前索引(步进到第几个元素),从0开始计数 * @return 增加步进后的对象 */ T step(T current, T end, int index); } }
924579fda6368c2d5dc538b71f3b464df802e5aa
1,332
java
Java
src/org/waveprotocol/wave/model/document/util/EmptyDocument.java
gburd/wave
9dc306f82817d027f28a50b39e6a6c898f63de38
[ "Apache-2.0" ]
7
2015-01-25T02:10:50.000Z
2021-02-02T14:49:49.000Z
src/org/waveprotocol/wave/model/document/util/EmptyDocument.java
JaredMiller/Wave
adcdbe82a124f5e84961569f505d7483cf6aa562
[ "Apache-2.0" ]
null
null
null
src/org/waveprotocol/wave/model/document/util/EmptyDocument.java
JaredMiller/Wave
adcdbe82a124f5e84961569f505d7483cf6aa562
[ "Apache-2.0" ]
4
2015-04-16T04:13:42.000Z
2016-05-18T13:08:05.000Z
29.6
84
0.746997
1,003,391
/** * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.waveprotocol.wave.model.document.util; import org.waveprotocol.wave.model.document.operation.DocInitialization; import org.waveprotocol.wave.model.document.operation.DocOp; import org.waveprotocol.wave.model.document.operation.impl.DocInitializationBuilder; import org.waveprotocol.wave.model.document.operation.impl.DocOpBuilder; /** * A utility class containing an empty document. * */ public final class EmptyDocument { /** * An empty document. */ public static final DocInitialization EMPTY_DOCUMENT = new DocInitializationBuilder().build(); /** * An empty document operation. */ public static final DocOp EMPTY_DOC_OP = new DocOpBuilder().build(); private EmptyDocument() {} }
92457a253dcadb29cd4e67a1c5f5f8697bf7d35b
3,240
java
Java
src/main/java/org/ssunion/cloudschedule/telegram/pushbot/controller/PushMessages.java
Kasad0r/CloudSchedule
dd55dc0d8cd3bf397427b40b3ccac85cc7898a09
[ "MIT" ]
null
null
null
src/main/java/org/ssunion/cloudschedule/telegram/pushbot/controller/PushMessages.java
Kasad0r/CloudSchedule
dd55dc0d8cd3bf397427b40b3ccac85cc7898a09
[ "MIT" ]
null
null
null
src/main/java/org/ssunion/cloudschedule/telegram/pushbot/controller/PushMessages.java
Kasad0r/CloudSchedule
dd55dc0d8cd3bf397427b40b3ccac85cc7898a09
[ "MIT" ]
null
null
null
28.928571
89
0.642901
1,003,392
package org.ssunion.cloudschedule.telegram.pushbot.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.ssunion.cloudschedule.domain.telegram.pushbot.User; import org.ssunion.cloudschedule.service.impl.UserServiceImpl; import org.ssunion.cloudschedule.telegram.pushbot.PushBot; import org.ssunion.cloudschedule.telegram.pushbot.messages.MessageFactory; import java.util.List; /** * @author kasad0r */ @Component public class PushMessages { private final PushBot pushBot; private final UserServiceImpl userService; @Autowired public PushMessages(PushBot pushBot, UserServiceImpl userService) { this.pushBot = pushBot; this.userService = userService; } //TODO /** * @param groupName * @param message */ public boolean forGroupImportant(String groupName, String message) { List<User> users = userService.getUsersBySelectedGroup(groupName); if (users != null && !users.isEmpty()) { pushBot.executeMessage(MessageFactory.createBold(users, message)); return true; } else { return false; } } //TODO /** * @param groupName * @param message */ public boolean forGroupInconsiderable(String groupName, String message) { List<User> users = userService.getUsersBySelectedGroupAndNotice(groupName, true); if (users != null && !users.isEmpty()) { pushBot.executeMessage(MessageFactory.createBold(users, message)); return true; } else { return false; } } //TODO /** * @param courseName * @param message */ public boolean forCourseImportant(String courseName, String message) { List<User> users = userService.getUsersByCourse(courseName); if (users != null && !users.isEmpty()) { pushBot.executeMessage(MessageFactory.createBold(users, message)); return true; } else { return false; } } //TODO /** * @param courseName * @param message */ public void forCourseInconsiderable(String courseName, String message) { List<User> users = userService.getUsersByCourseAndNotice(courseName, true); if (users != null && !users.isEmpty()) { pushBot.executeMessage(MessageFactory.createBold(users, message)); } } //TODO /** * @param groupName * @param message */ public void forAllImportant(String groupName, String message) { List<User> users = userService.findAll(); if (users != null && !users.isEmpty()) { pushBot.executeMessage(MessageFactory.createBold(users, message)); } } //TODO /*public static void main(String[] args) { System.out.println("Кирилл пидор"); }*/ /** * @param groupName * @param message */ public void forAllInconsiderable(String groupName, String message) { List<User> users = userService.getUsersByAdminNotice(true); if (users != null && !users.isEmpty()) { pushBot.executeMessage(MessageFactory.createBold(users, message)); } } }
92457cf7cd6ea67c57f2f340954093c84c7318a9
13,756
java
Java
src/java/org/apache/cassandra/cql3/Sets.java
Rushi11111/Cassandra
88d870710c89e0554fcd70f554f21c8a34af128e
[ "Apache-2.0" ]
12
2017-02-28T14:11:51.000Z
2019-09-18T02:41:38.000Z
src/java/org/apache/cassandra/cql3/Sets.java
Rushi11111/Cassandra
88d870710c89e0554fcd70f554f21c8a34af128e
[ "Apache-2.0" ]
null
null
null
src/java/org/apache/cassandra/cql3/Sets.java
Rushi11111/Cassandra
88d870710c89e0554fcd70f554f21c8a34af128e
[ "Apache-2.0" ]
5
2017-04-05T10:25:29.000Z
2020-10-27T07:14:54.000Z
36.978495
175
0.608898
1,003,393
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.cql3; import static org.apache.cassandra.cql3.Constants.UNSET_VALUE; import java.nio.ByteBuffer; import java.util.*; import java.util.stream.Collectors; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.cql3.functions.Function; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.rows.*; import org.apache.cassandra.db.marshal.*; import org.apache.cassandra.exceptions.InvalidRequestException; import org.apache.cassandra.serializers.CollectionSerializer; import org.apache.cassandra.serializers.MarshalException; import org.apache.cassandra.transport.ProtocolVersion; import org.apache.cassandra.utils.ByteBufferUtil; /** * Static helper methods and classes for sets. */ public abstract class Sets { private Sets() {} public static ColumnSpecification valueSpecOf(ColumnSpecification column) { return new ColumnSpecification(column.ksName, column.cfName, new ColumnIdentifier("value(" + column.name + ")", true), elementsType(column.type)); } private static AbstractType<?> unwrap(AbstractType<?> type) { return type.isReversed() ? unwrap(((ReversedType<?>) type).baseType) : type; } private static AbstractType<?> elementsType(AbstractType<?> type) { return ((SetType) unwrap(type)).getElementsType(); } public static class Literal extends Term.Raw { private final List<Term.Raw> elements; public Literal(List<Term.Raw> elements) { this.elements = elements; } public Term prepare(String keyspace, ColumnSpecification receiver) throws InvalidRequestException { validateAssignableTo(keyspace, receiver); // We've parsed empty maps as a set literal to break the ambiguity so // handle that case now if (receiver.type instanceof MapType && elements.isEmpty()) return new Maps.Value(Collections.<ByteBuffer, ByteBuffer>emptyMap()); ColumnSpecification valueSpec = Sets.valueSpecOf(receiver); Set<Term> values = new HashSet<>(elements.size()); boolean allTerminal = true; for (Term.Raw rt : elements) { Term t = rt.prepare(keyspace, valueSpec); if (t.containsBindMarker()) throw new InvalidRequestException(String.format("Invalid set literal for %s: bind variables are not supported inside collection literals", receiver.name)); if (t instanceof Term.NonTerminal) allTerminal = false; values.add(t); } DelayedValue value = new DelayedValue(elementsType(receiver.type), values); return allTerminal ? value.bind(QueryOptions.DEFAULT) : value; } private void validateAssignableTo(String keyspace, ColumnSpecification receiver) throws InvalidRequestException { AbstractType<?> type = unwrap(receiver.type); if (!(type instanceof SetType)) { // We've parsed empty maps as a set literal to break the ambiguity so // handle that case now if ((type instanceof MapType) && elements.isEmpty()) return; throw new InvalidRequestException(String.format("Invalid set literal for %s of type %s", receiver.name, receiver.type.asCQL3Type())); } ColumnSpecification valueSpec = Sets.valueSpecOf(receiver); for (Term.Raw rt : elements) { if (!rt.testAssignment(keyspace, valueSpec).isAssignable()) throw new InvalidRequestException(String.format("Invalid set literal for %s: value %s is not of type %s", receiver.name, rt, valueSpec.type.asCQL3Type())); } } public AssignmentTestable.TestResult testAssignment(String keyspace, ColumnSpecification receiver) { if (!(receiver.type instanceof SetType)) { // We've parsed empty maps as a set literal to break the ambiguity so handle that case now if (receiver.type instanceof MapType && elements.isEmpty()) return AssignmentTestable.TestResult.WEAKLY_ASSIGNABLE; return AssignmentTestable.TestResult.NOT_ASSIGNABLE; } // If there is no elements, we can't say it's an exact match (an empty set if fundamentally polymorphic). if (elements.isEmpty()) return AssignmentTestable.TestResult.WEAKLY_ASSIGNABLE; ColumnSpecification valueSpec = Sets.valueSpecOf(receiver); return AssignmentTestable.TestResult.testAll(keyspace, valueSpec, elements); } @Override public AbstractType<?> getExactTypeIfKnown(String keyspace) { for (Term.Raw term : elements) { AbstractType<?> type = term.getExactTypeIfKnown(keyspace); if (type != null) return SetType.getInstance(type, false); } return null; } public String getText() { return elements.stream().map(Term.Raw::getText).collect(Collectors.joining(", ", "{", "}")); } } public static class Value extends Term.Terminal { public final SortedSet<ByteBuffer> elements; public Value(SortedSet<ByteBuffer> elements) { this.elements = elements; } public static Value fromSerialized(ByteBuffer value, SetType type, ProtocolVersion version) throws InvalidRequestException { try { // Collections have this small hack that validate cannot be called on a serialized object, // but compose does the validation (so we're fine). Set<?> s = type.getSerializer().deserializeForNativeProtocol(value, version); SortedSet<ByteBuffer> elements = new TreeSet<>(type.getElementsType()); for (Object element : s) elements.add(type.getElementsType().decompose(element)); return new Value(elements); } catch (MarshalException e) { throw new InvalidRequestException(e.getMessage()); } } public ByteBuffer get(ProtocolVersion protocolVersion) { return CollectionSerializer.pack(elements, elements.size(), protocolVersion); } public boolean equals(SetType st, Value v) { if (elements.size() != v.elements.size()) return false; Iterator<ByteBuffer> thisIter = elements.iterator(); Iterator<ByteBuffer> thatIter = v.elements.iterator(); AbstractType elementsType = st.getElementsType(); while (thisIter.hasNext()) if (elementsType.compare(thisIter.next(), thatIter.next()) != 0) return false; return true; } } // See Lists.DelayedValue public static class DelayedValue extends Term.NonTerminal { private final Comparator<ByteBuffer> comparator; private final Set<Term> elements; public DelayedValue(Comparator<ByteBuffer> comparator, Set<Term> elements) { this.comparator = comparator; this.elements = elements; } public boolean containsBindMarker() { // False since we don't support them in collection return false; } public void collectMarkerSpecification(VariableSpecifications boundNames) { } public Terminal bind(QueryOptions options) throws InvalidRequestException { SortedSet<ByteBuffer> buffers = new TreeSet<>(comparator); for (Term t : elements) { ByteBuffer bytes = t.bindAndGet(options); if (bytes == null) throw new InvalidRequestException("null is not supported inside collections"); if (bytes == ByteBufferUtil.UNSET_BYTE_BUFFER) return UNSET_VALUE; buffers.add(bytes); } return new Value(buffers); } public void addFunctionsTo(List<Function> functions) { Terms.addFunctions(elements, functions); } } public static class Marker extends AbstractMarker { protected Marker(int bindIndex, ColumnSpecification receiver) { super(bindIndex, receiver); assert receiver.type instanceof SetType; } public Terminal bind(QueryOptions options) throws InvalidRequestException { ByteBuffer value = options.getValues().get(bindIndex); if (value == null) return null; if (value == ByteBufferUtil.UNSET_BYTE_BUFFER) return UNSET_VALUE; return Value.fromSerialized(value, (SetType)receiver.type, options.getProtocolVersion()); } } public static class Setter extends Operation { public Setter(ColumnDefinition column, Term t) { super(column, t); } public void execute(DecoratedKey partitionKey, UpdateParameters params) throws InvalidRequestException { Term.Terminal value = t.bind(params.options); if (value == UNSET_VALUE) return; // delete + add if (column.type.isMultiCell()) params.setComplexDeletionTimeForOverwrite(column); Adder.doAdd(value, column, params); } } public static class Adder extends Operation { public Adder(ColumnDefinition column, Term t) { super(column, t); } public void execute(DecoratedKey partitionKey, UpdateParameters params) throws InvalidRequestException { assert column.type.isMultiCell() : "Attempted to add items to a frozen set"; Term.Terminal value = t.bind(params.options); if (value != UNSET_VALUE) doAdd(value, column, params); } static void doAdd(Term.Terminal value, ColumnDefinition column, UpdateParameters params) throws InvalidRequestException { if (column.type.isMultiCell()) { if (value == null) return; for (ByteBuffer bb : ((Value) value).elements) { if (bb == ByteBufferUtil.UNSET_BYTE_BUFFER) continue; params.addCell(column, CellPath.create(bb), ByteBufferUtil.EMPTY_BYTE_BUFFER); } } else { // for frozen sets, we're overwriting the whole cell if (value == null) params.addTombstone(column); else params.addCell(column, value.get(ProtocolVersion.CURRENT)); } } } // Note that this is reused for Map subtraction too (we subtract a set from a map) public static class Discarder extends Operation { public Discarder(ColumnDefinition column, Term t) { super(column, t); } public void execute(DecoratedKey partitionKey, UpdateParameters params) throws InvalidRequestException { assert column.type.isMultiCell() : "Attempted to remove items from a frozen set"; Term.Terminal value = t.bind(params.options); if (value == null || value == UNSET_VALUE) return; // This can be either a set or a single element Set<ByteBuffer> toDiscard = value instanceof Sets.Value ? ((Sets.Value)value).elements : Collections.singleton(value.get(params.options.getProtocolVersion())); for (ByteBuffer bb : toDiscard) params.addTombstone(column, CellPath.create(bb)); } } public static class ElementDiscarder extends Operation { public ElementDiscarder(ColumnDefinition column, Term k) { super(column, k); } public void execute(DecoratedKey partitionKey, UpdateParameters params) throws InvalidRequestException { assert column.type.isMultiCell() : "Attempted to delete a single element in a frozen set"; Term.Terminal elt = t.bind(params.options); if (elt == null) throw new InvalidRequestException("Invalid null set element"); params.addTombstone(column, CellPath.create(elt.get(params.options.getProtocolVersion()))); } } }
92457d34528f137ff01c9378fdc7a81c6b523155
326
java
Java
processor/src/test/fixtures/subsystem/bad_input/com/example/name_ref/BadType3NameRefSubSystem.java
realityforge/galdr
6ac8a49baa52c6ade4e1a9ebd13212682a5ecec1
[ "Apache-2.0" ]
1
2020-10-05T09:07:27.000Z
2020-10-05T09:07:27.000Z
processor/src/test/fixtures/subsystem/bad_input/com/example/name_ref/BadType3NameRefSubSystem.java
realityforge/galdr
6ac8a49baa52c6ade4e1a9ebd13212682a5ecec1
[ "Apache-2.0" ]
null
null
null
processor/src/test/fixtures/subsystem/bad_input/com/example/name_ref/BadType3NameRefSubSystem.java
realityforge/galdr
6ac8a49baa52c6ade4e1a9ebd13212682a5ecec1
[ "Apache-2.0" ]
null
null
null
17.157895
46
0.788344
1,003,394
package com.example.name_ref; import galdr.annotations.GaldrSubSystem; import galdr.annotations.NameRef; import galdr.annotations.Processor; import java.io.IOException; @GaldrSubSystem public abstract class BadType3NameRefSubSystem { @NameRef abstract IOException name(); @Processor final void runFrame() { } }
92457d5c9daf8acafe27b202c457a59138175e31
1,019
java
Java
petra-core/src/main/java/io/cognitionbox/petra/guarantees/impl/StepsMustHavePublicClasses.java
cognitionbox/petra
f9c6029e9136138bfc10e7b50c23aff045473b50
[ "Apache-2.0" ]
12
2020-02-20T21:04:31.000Z
2022-03-30T23:38:09.000Z
petra-core/src/main/java/io/cognitionbox/petra/guarantees/impl/StepsMustHavePublicClasses.java
cognitionbox/petra
f9c6029e9136138bfc10e7b50c23aff045473b50
[ "Apache-2.0" ]
9
2021-02-10T11:25:04.000Z
2022-01-16T01:20:19.000Z
petra-core/src/main/java/io/cognitionbox/petra/guarantees/impl/StepsMustHavePublicClasses.java
cognitionbox/petra
f9c6029e9136138bfc10e7b50c23aff045473b50
[ "Apache-2.0" ]
2
2021-02-10T10:56:19.000Z
2022-02-09T15:41:29.000Z
35.137931
107
0.745829
1,003,395
/** * Copyright 2016-2020 Aran Hakki * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.cognitionbox.petra.guarantees.impl; import io.cognitionbox.petra.core.IStep; import io.cognitionbox.petra.guarantees.StepCheck; import java.lang.reflect.Modifier; public class StepsMustHavePublicClasses implements StepCheck { @Override public boolean test(IStep<?> step) { return step.getStepClazz().isLocalClass() || Modifier.isPublic(step.getStepClazz().getModifiers()); } }
92457dbdfff0f212dbd2f9a427c1acc2d36f0c9c
1,008
java
Java
src/main/java/team/serenity/commons/core/sorter/StudentInfoSorter.java
Nijnxw/tp
c8c8c61e6046d820419938c2a84df1a4fca3ed80
[ "MIT" ]
3
2020-09-16T09:26:57.000Z
2020-09-16T09:27:07.000Z
src/main/java/team/serenity/commons/core/sorter/StudentInfoSorter.java
Nijnxw/tp
c8c8c61e6046d820419938c2a84df1a4fca3ed80
[ "MIT" ]
247
2020-09-16T09:37:09.000Z
2020-11-09T15:53:28.000Z
src/main/java/team/serenity/commons/core/sorter/StudentInfoSorter.java
Nijnxw/tp
c8c8c61e6046d820419938c2a84df1a4fca3ed80
[ "MIT" ]
4
2020-09-16T09:24:58.000Z
2020-09-16T09:32:57.000Z
31.5
80
0.632937
1,003,396
package team.serenity.commons.core.sorter; import java.util.Comparator; import team.serenity.model.group.studentinfo.StudentInfo; public class StudentInfoSorter implements Comparator<StudentInfo> { @Override public int compare(StudentInfo studentInfoOne, StudentInfo studentInfoTwo) { String infoOne = studentInfoOne.getStudent().getStudentName().fullName; int infoOneLen = infoOne.length(); String infoTwo = studentInfoTwo.getStudent().getStudentName().fullName; int infoTwoLen = infoTwo.length(); int minLength = Math.min(infoOneLen, infoTwoLen); for (int i = 0; i < minLength; i++) { int infoOneChar = infoOne.charAt(i); int infoTwoChar = infoTwo.charAt(i); if (infoOneChar != infoTwoChar) { return infoOneChar - infoTwoChar; } } if (infoOneLen != infoTwoLen) { return infoOneLen - infoTwoLen; } else { return 0; } } }
92457ef6a733ebd8a739339905cb7d7b3aa9a407
4,720
java
Java
YadaWebSecurity/src/main/java/net/yadaframework/security/persistence/repository/YadaUserMessageDao.java
xtianus/yadaframework
30865611fb85fe932289328d8968734b404585d3
[ "MIT" ]
1
2017-02-27T12:15:01.000Z
2017-02-27T12:15:01.000Z
YadaWebSecurity/src/main/java/net/yadaframework/security/persistence/repository/YadaUserMessageDao.java
xtianus/yadaframework
30865611fb85fe932289328d8968734b404585d3
[ "MIT" ]
null
null
null
YadaWebSecurity/src/main/java/net/yadaframework/security/persistence/repository/YadaUserMessageDao.java
xtianus/yadaframework
30865611fb85fe932289328d8968734b404585d3
[ "MIT" ]
3
2019-07-18T19:23:00.000Z
2020-09-24T23:52:16.000Z
42.909091
127
0.694703
1,003,397
package net.yadaframework.security.persistence.repository; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import net.yadaframework.components.YadaUtil; import net.yadaframework.exceptions.YadaInvalidUsageException; import net.yadaframework.persistence.YadaSql; import net.yadaframework.security.persistence.entity.YadaUserMessage; import net.yadaframework.security.persistence.entity.YadaUserProfile; @Repository @Transactional(readOnly = true) public class YadaUserMessageDao { private final transient Logger log = LoggerFactory.getLogger(getClass()); @Autowired private YadaUtil yadaUtil; @PersistenceContext EntityManager em; /** * Delete all messages that do not involve users other than the one specified (no other users as sender o recipient) * @param userProfile the receiver/sender of the message */ @Transactional(readOnly = false) public void deleteBelongingTo(YadaUserProfile userProfile) { // Messages that have the user as sender or recipient, and nobody else involved, or // where the user is both sender and recipient List <YadaUserMessage> toDelete = YadaSql.instance().selectFrom("select yum from YadaUserMessage yum") .where("(sender=:userProfile and recipient=null)").or() .where("(sender=null and recipient=:userProfile)").or() .where("(sender=:userProfile and recipient=:userProfile)") .setParameter("userProfile", userProfile) .query(em, YadaUserMessage.class).getResultList(); // Need to fetch them all then delete them, in order to cascade deletes to "created" and "attachment" for (YadaUserMessage yadaUserMessage : toDelete) { em.remove(yadaUserMessage); } } /** * Save a message. If the message is stackable, only increment the counter of an existing message with identical * content and same recipient and same sender and same data, if not older than one day * @param m the message * @return true if the message has been created, false if the counter incremented */ @Transactional(readOnly = false) public boolean createOrIncrement(YadaUserMessage<?> m) { log.debug("YadaUserMessage to {} from {}: [{}] '{}' - {} (data={})", m.getReceiverName()!=null?m.getReceiverName():"-", m.getSender()!=null?m.getSenderName():"-", m.getPriority(), m.getTitle(), m.getMessage(), m.getData()); if (m.getId()!=null) { throw new YadaInvalidUsageException("Message already exists with id=" + m.getId()); } /* Recipient can be null. For example in a ticket. if (m.getRecipient()==null) { throw new YadaInvalidUsageException("Message with no recipient - title=" + m.getTitle()); }*/ if (!m.isStackable()) { em.persist(m); return true; // Created new } // Need to update an existing row counter if it exists, or insert a new one. // Not using "insert ... on duplicate key update" because of the time window // TODO the time window could be a (configured) parameter Date oldestStackTime = yadaUtil.daysAgo(1); // Time window: one day ago m.computeHash(); // Needed List<YadaUserMessage> existingList = YadaSql.instance().selectFrom("select m from YadaUserMessage m") //YadaTicketMessage? .where("m.contentHash=:contentHash").and() .where("m.modified > :oldestStackTime").and() .where("m.recipient = :recipient").and() .where(m.getSender()!=null, "m.sender = :sender").and() .where(m.getData()!=null, "m.data = :data").and() .orderBy("m.modified desc") .setParameter("contentHash", m.getContentHash()) .setParameter("oldestStackTime", oldestStackTime) .setParameter("recipient", m.getRecipient()) .setParameter("sender", m.getSender()) .setParameter("data", m.getData()) .query(em, YadaUserMessage.class).setMaxResults(1).getResultList(); if (existingList.isEmpty()) { em.persist(m); return true; // Created new } else { m = existingList.get(0); m.incrementStack(); m.setReadByRecipient(false); m.setModified(new Date()); return false; } } List<YadaUserMessage> findOldYadaUserMessages() { String sql = "select * from YadaUserMessage where modified <= (NOW() - INTERVAL 30 DAY)"; return em.createNativeQuery(sql, YadaUserMessage.class) .getResultList(); } }
92457f3cb70e1ecaa4267309ad466003c81a19a0
373
java
Java
eclipse/home/AndroidGame/src/com/scottwes/framework/Music.java
swestoverblog/NBGardensAEM
d2b2ece388d4b977834822e3aa6a1d06200e7761
[ "MIT" ]
null
null
null
eclipse/home/AndroidGame/src/com/scottwes/framework/Music.java
swestoverblog/NBGardensAEM
d2b2ece388d4b977834822e3aa6a1d06200e7761
[ "MIT" ]
null
null
null
eclipse/home/AndroidGame/src/com/scottwes/framework/Music.java
swestoverblog/NBGardensAEM
d2b2ece388d4b977834822e3aa6a1d06200e7761
[ "MIT" ]
1
2015-01-20T05:39:54.000Z
2015-01-20T05:39:54.000Z
15.541667
44
0.670241
1,003,398
package com.scottwes.framework; public interface Music { public void play(); public void stop(); public void pause(); public void setLooping(boolean looping); public void setVolume(float volume); public boolean isPlaying(); public boolean isStopped(); public boolean isLooping(); public void dispose(); void seekBegin(); }
92458086361c605a01e9cf427914bedaa9ea6e02
2,857
java
Java
echoes-gui/echoes-gui-database/src/main/java/org/csuc/dao/loader/LoaderDAO.java
CSUC/ECHOES-Tools
c20376b1222a51fef23d152ec8ba5de43b8de58c
[ "MIT" ]
6
2017-10-20T17:05:25.000Z
2020-01-23T14:30:32.000Z
echoes-gui/echoes-gui-database/src/main/java/org/csuc/dao/loader/LoaderDAO.java
CSUC/ECHOES-Tools
c20376b1222a51fef23d152ec8ba5de43b8de58c
[ "MIT" ]
360
2018-09-13T11:05:14.000Z
2021-12-10T01:02:12.000Z
echoes-gui/echoes-gui-database/src/main/java/org/csuc/dao/loader/LoaderDAO.java
CSUC/ECHOES-Tools
c20376b1222a51fef23d152ec8ba5de43b8de58c
[ "MIT" ]
2
2017-11-28T12:26:10.000Z
2019-03-06T09:50:51.000Z
46.080645
118
0.627581
1,003,399
package org.csuc.dao.loader; import com.mongodb.WriteResult; import org.bson.types.ObjectId; import org.csuc.entities.loader.Loader; import org.csuc.utils.Aggregation; import org.csuc.utils.Status; import org.mongodb.morphia.Key; import org.mongodb.morphia.dao.DAO; import java.util.Iterator; import java.util.List; /** * @author amartinez */ public interface LoaderDAO extends DAO<Loader, ObjectId> { /*****************************************************id*****************************************************/ Loader getById(String objectId) throws Exception; /*****************************************************user*****************************************************/ List<Loader> getByUser(String user, String orderby) throws Exception; List<Loader> getByUser(String user, int offset, int limit, String orderby) throws Exception; long countByUser(String user) throws Exception; /*****************************************************status*****************************************************/ List<Loader> getByStatus(Status status) throws Exception; List<Loader> getByStatus(Status status, String user) throws Exception; List<Loader> getByStatus(Status status, int offset, int limit) throws Exception; List<Loader> getByStatus(Status status, String user, int offset, int limit) throws Exception; long countByStatus(Status status) throws Exception; long countByStatus(Status status, String user) throws Exception; long getStatusLastMonth(Status status) throws Exception; long getStatusLastMonth(Status status, String user) throws Exception; long getStatusMonth(Status status) throws Exception; long getStatusMonth(Status status, String user) throws Exception; long getStatusLastYear(Status status) throws Exception; long getStatusLastYear(Status status, String user) throws Exception; long getStatusYear(Status status) throws Exception; long getStatusYear(Status status, String user) throws Exception; long getStatusLastDay(Status status) throws Exception; long getStatusLastDay(Status status, String user) throws Exception; long getStatusDay(Status status) throws Exception; long getStatusDay(Status status, String user) throws Exception; Iterator<Aggregation> getStatusAggregation(); Iterator<Aggregation> getStatusAggregation(String user); /*****************************************************insert*****************************************************/ Key<Loader> insert(Loader loader) throws Exception; /*****************************************************delete*****************************************************/ WriteResult deleteById(String objectId) throws Exception; WriteResult deleteByUser(String user) throws Exception; WriteResult deleteByStatus(Status status) throws Exception; }
924580a3d4761d5d99b5f580d5104c9df1c1a442
2,668
java
Java
src/main/java/client/AbstractClient.java
IBM/simple-remoting-library
c7f5465a83fabffe8792caeaf50627eb5ff2e299
[ "Apache-2.0" ]
null
null
null
src/main/java/client/AbstractClient.java
IBM/simple-remoting-library
c7f5465a83fabffe8792caeaf50627eb5ff2e299
[ "Apache-2.0" ]
1
2021-04-03T15:53:52.000Z
2021-04-03T15:53:52.000Z
src/main/java/client/AbstractClient.java
IBM/simple-remoting-library
c7f5465a83fabffe8792caeaf50627eb5ff2e299
[ "Apache-2.0" ]
1
2021-04-12T14:20:09.000Z
2021-04-12T14:20:09.000Z
29
99
0.75075
1,003,400
package client; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.Map; import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.logging.Logger; import common.Payload; import common.PayloadHandler; import common.ProtocolHandler; /** * * @author psuryan * */ public abstract class AbstractClient extends ProtocolHandler { public AbstractClient(PayloadHandler payloadHandler) { super(payloadHandler); } protected final Logger logger = Logger.getLogger(getClass().getName()); private static final ExecutorService threadPool = Executors.newCachedThreadPool(); private Map<String, ResponseHandler> handlers = new ConcurrentHashMap<String, ResponseHandler>(); @SuppressWarnings("unchecked") public <T extends Object> T get(Class<T> interfaceClass) throws ClassNotFoundException { logger.info("interfacClass " + interfaceClass.getCanonicalName()); InvocationHandler handler = new Invoker(this); return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass }, handler); } public Object call(String interfaceName, Payload req) throws InterruptedException, ExecutionException { ResponseHandler handler = new ResponseHandler(); handlers.put(req.getUuid().toString(), handler); Future<Object> future = threadPool.submit(handler); doCall(interfaceName, req); return future.get(); } public void done() throws Exception { threadPool.shutdown(); shutDown(); } protected abstract void doCall(String interfaceName, Payload req); public void onReturn(Payload payload) { String key = payload.getUuid().toString(); logger.fine("Removing " + key); handlers.get(key).handle(payload.getResponse()); handlers.remove(key); } public abstract void init(Properties props) throws Exception; protected abstract void shutDown() throws Exception; } class ResponseHandler implements Callable<Object> { private final Logger logger = Logger.getLogger(getClass().getName()); private final CountDownLatch replyLatch = new CountDownLatch(1); private Object callbackResults; public Object call() throws Exception { replyLatch.await(); return callbackResults; } void handle(Object obj) { callbackResults = obj; replyLatch.countDown(); logger.fine("Handling return."); } }
924580cc58ac750bd056af9c801a40ad210b7b8f
2,668
java
Java
hedwig-api/src/main/java/com/hs/mail/imap/dao/AnsiUserDao.java
gluckzhang/hedwig-pankti
142ec001662f20eb8a5772af6a2dbac8be9b175f
[ "Apache-2.0" ]
null
null
null
hedwig-api/src/main/java/com/hs/mail/imap/dao/AnsiUserDao.java
gluckzhang/hedwig-pankti
142ec001662f20eb8a5772af6a2dbac8be9b175f
[ "Apache-2.0" ]
2
2019-01-14T06:10:01.000Z
2019-02-03T09:21:04.000Z
hedwig-api/src/main/java/com/hs/mail/imap/dao/AnsiUserDao.java
gluckzhang/hedwig-pankti
142ec001662f20eb8a5772af6a2dbac8be9b175f
[ "Apache-2.0" ]
null
null
null
30.318182
74
0.673163
1,003,401
package com.hs.mail.imap.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.mail.Quota; import org.springframework.jdbc.core.RowMapper; import com.hs.mail.imap.user.Alias; import com.hs.mail.imap.user.User; /** * * @author Won Chul Doh * @since July 26, 2015 * */ abstract class AnsiUserDao extends AbstractDao implements UserDao { public long getUserID(String address) { String sql = "SELECT userid FROM hw_user WHERE loginid = ?"; return queryForLong(sql, new Object[] { address }); } public User getUserByAddress(String address) { String sql = "SELECT * FROM hw_user WHERE loginid = ?"; return queryForObject(sql, new Object[] { address }, userMapper); } public List<Alias> expandAlias(String alias) { String sql = "SELECT * FROM hw_alias WHERE alias = ?"; return getJdbcTemplate() .query(sql, new Object[] { alias }, aliasMapper); } public long getQuotaLimit(long ownerID) { String sql = "SELECT maxmail_size FROM hw_user WHERE userid = ?"; long limit = queryForLong(sql, new Object[] { new Long(ownerID) }); return limit * 1024 * 1024; } public Quota getQuota(long ownerID, long mailboxID, String quotaRoot) { Quota quota = new Quota(quotaRoot); quota.setResourceLimit("STORAGE", getQuotaLimit(ownerID)); quota.resources[0].usage = getQuotaUsage(ownerID, mailboxID); return quota; } public void setQuota(long ownerID, Quota quota) { String sql = "UPDATE hw_user SET maxmail_size = ? WHERE userid = ?"; for (int i = 0; i < quota.resources.length; i++) { if ("STORAGE".equals(quota.resources[i].name)) { getJdbcTemplate().update( sql, new Object[] { new Long(quota.resources[i].limit), new Long(ownerID) }); quota.resources[i].usage = getQuotaUsage(ownerID, 0); return; } } } protected static RowMapper<User> userMapper = new RowMapper<User>() { public User mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setID(rs.getLong("userid")); user.setUserID(rs.getString("loginid")); user.setPassword(rs.getString("passwd")); user.setQuota(rs.getLong("maxmail_size")); user.setForwardTo(rs.getString("forward")); return user; } }; protected static RowMapper<Alias> aliasMapper = new RowMapper<Alias>() { public Alias mapRow(ResultSet rs, int rowNum) throws SQLException { Alias alias = new Alias(); alias.setID(rs.getLong("aliasid")); alias.setAlias(rs.getString("alias")); alias.setDeliverTo(rs.getString("deliver_to")); return alias; } }; }
92458127d98a2a37d23f12460c1d60e614ceed58
789
java
Java
ScenarioGen/src/com/laurel/BackstagecraftOne/State1.java
emilyhunt/ScenarioGen
e102900bb0fa026d99a09a0892ef868aa24bf165
[ "MIT" ]
null
null
null
ScenarioGen/src/com/laurel/BackstagecraftOne/State1.java
emilyhunt/ScenarioGen
e102900bb0fa026d99a09a0892ef868aa24bf165
[ "MIT" ]
null
null
null
ScenarioGen/src/com/laurel/BackstagecraftOne/State1.java
emilyhunt/ScenarioGen
e102900bb0fa026d99a09a0892ef868aa24bf165
[ "MIT" ]
null
null
null
23.205882
62
0.765526
1,003,402
package com.laurel.BackstagecraftOne; import org.bukkit.GameMode; import org.bukkit.entity.Player; import com.laurel.Actions.set; import com.laurel.Listeners.OnJoinGameMode; import com.laurel.ScenarioGen.ScenarioState; public class State1 extends ScenarioState { // Join state for players in the lobby room. @Override public void enable(Player player, Listeners listeners) { player.sendMessage("Enabling state 1."); // Current gamemodes set.allOnlineGameModes(GameMode.ADVENTURE); // Join gamemode rules OnJoinGameMode joinListener = listeners.getOnJoinGameMode(); joinListener.setMode(GameMode.ADVENTURE); joinListener.enable(); } @Override public void disable(Player player, Listeners listeners) { player.sendMessage("Disabling state 1."); } }
9245813a542b2100f1405c4c952ff64a8cee39c7
9,355
java
Java
aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/UpdateAliasRequest.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
1
2019-10-17T14:03:43.000Z
2019-10-17T14:03:43.000Z
aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/UpdateAliasRequest.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/UpdateAliasRequest.java
DamonTung/aws-sdk-java
e33012aea76a1cc18866120d0c53fd593b2cf550
[ "Apache-2.0" ]
2
2017-10-05T10:52:18.000Z
2018-10-19T09:13:12.000Z
32.258621
120
0.618707
1,003,403
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lambda.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lambda-2015-03-31/UpdateAlias" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateAliasRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The function name for which the alias is created. Note that the length constraint applies only to the ARN. If you * specify only the function name, it is limited to 64 characters in length. * </p> */ private String functionName; /** * <p> * The alias name. * </p> */ private String name; /** * <p> * Using this parameter you can change the Lambda function version to which the alias points. * </p> */ private String functionVersion; /** * <p> * You can change the description of the alias using this parameter. * </p> */ private String description; /** * <p> * The function name for which the alias is created. Note that the length constraint applies only to the ARN. If you * specify only the function name, it is limited to 64 characters in length. * </p> * * @param functionName * The function name for which the alias is created. Note that the length constraint applies only to the ARN. * If you specify only the function name, it is limited to 64 characters in length. */ public void setFunctionName(String functionName) { this.functionName = functionName; } /** * <p> * The function name for which the alias is created. Note that the length constraint applies only to the ARN. If you * specify only the function name, it is limited to 64 characters in length. * </p> * * @return The function name for which the alias is created. Note that the length constraint applies only to the * ARN. If you specify only the function name, it is limited to 64 characters in length. */ public String getFunctionName() { return this.functionName; } /** * <p> * The function name for which the alias is created. Note that the length constraint applies only to the ARN. If you * specify only the function name, it is limited to 64 characters in length. * </p> * * @param functionName * The function name for which the alias is created. Note that the length constraint applies only to the ARN. * If you specify only the function name, it is limited to 64 characters in length. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAliasRequest withFunctionName(String functionName) { setFunctionName(functionName); return this; } /** * <p> * The alias name. * </p> * * @param name * The alias name. */ public void setName(String name) { this.name = name; } /** * <p> * The alias name. * </p> * * @return The alias name. */ public String getName() { return this.name; } /** * <p> * The alias name. * </p> * * @param name * The alias name. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAliasRequest withName(String name) { setName(name); return this; } /** * <p> * Using this parameter you can change the Lambda function version to which the alias points. * </p> * * @param functionVersion * Using this parameter you can change the Lambda function version to which the alias points. */ public void setFunctionVersion(String functionVersion) { this.functionVersion = functionVersion; } /** * <p> * Using this parameter you can change the Lambda function version to which the alias points. * </p> * * @return Using this parameter you can change the Lambda function version to which the alias points. */ public String getFunctionVersion() { return this.functionVersion; } /** * <p> * Using this parameter you can change the Lambda function version to which the alias points. * </p> * * @param functionVersion * Using this parameter you can change the Lambda function version to which the alias points. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAliasRequest withFunctionVersion(String functionVersion) { setFunctionVersion(functionVersion); return this; } /** * <p> * You can change the description of the alias using this parameter. * </p> * * @param description * You can change the description of the alias using this parameter. */ public void setDescription(String description) { this.description = description; } /** * <p> * You can change the description of the alias using this parameter. * </p> * * @return You can change the description of the alias using this parameter. */ public String getDescription() { return this.description; } /** * <p> * You can change the description of the alias using this parameter. * </p> * * @param description * You can change the description of the alias using this parameter. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAliasRequest withDescription(String description) { setDescription(description); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFunctionName() != null) sb.append("FunctionName: ").append(getFunctionName()).append(","); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getFunctionVersion() != null) sb.append("FunctionVersion: ").append(getFunctionVersion()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateAliasRequest == false) return false; UpdateAliasRequest other = (UpdateAliasRequest) obj; if (other.getFunctionName() == null ^ this.getFunctionName() == null) return false; if (other.getFunctionName() != null && other.getFunctionName().equals(this.getFunctionName()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getFunctionVersion() == null ^ this.getFunctionVersion() == null) return false; if (other.getFunctionVersion() != null && other.getFunctionVersion().equals(this.getFunctionVersion()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFunctionName() == null) ? 0 : getFunctionName().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getFunctionVersion() == null) ? 0 : getFunctionVersion().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); return hashCode; } @Override public UpdateAliasRequest clone() { return (UpdateAliasRequest) super.clone(); } }
9245823cbcedec9762357c6b17ceae31382e905e
14,572
java
Java
rr/snowhack/snow/module/ModuleManager.java
christallinqq/snowhack
7db8a9d299a5e8a2ff43bd54f05e8dd2c828656a
[ "Unlicense" ]
10
2021-09-13T01:14:37.000Z
2021-11-09T11:10:04.000Z
rr/snowhack/snow/module/ModuleManager.java
christallinqq/snowhack
7db8a9d299a5e8a2ff43bd54f05e8dd2c828656a
[ "Unlicense" ]
2
2021-09-13T21:54:56.000Z
2021-09-18T17:20:40.000Z
rr/snowhack/snow/module/ModuleManager.java
christallinqq/snowhack
7db8a9d299a5e8a2ff43bd54f05e8dd2c828656a
[ "Unlicense" ]
1
2021-09-13T01:27:38.000Z
2021-09-13T01:27:38.000Z
49.117845
310
0.674664
1,003,404
package rr.snowhack.snow.module; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.math.Vec3d; import net.minecraftforge.client.event.RenderWorldLastEvent; import rr.snowhack.snow.SnowMod; import rr.snowhack.snow.event.events.RenderEvent; import rr.snowhack.snow.module.modules.ClickGUI; import rr.snowhack.snow.util.ClassFinder; import rr.snowhack.snow.util.EntityUtil; import rr.snowhack.snow.util.SnowTessellator; import rr.snowhack.snow.util.Wrapper; public class ModuleManager { // $FF: synthetic field public static ArrayList<Module> modules; // $FF: synthetic field private static final String[] llllIllIlllI; // $FF: synthetic field static HashMap<String, Module> lookup; // $FF: synthetic field private static final int[] llllIlllIIIl; public static Module getModuleByName(String lllllllllllllllIlIlIIlIIIlIIIIll) { return (Module)lookup.get(lllllllllllllllIlIlIIlIIIlIIIIll.toLowerCase()); } public static void onBind(int lllllllllllllllIlIlIIlIIIlIIIllI) { if (!lIlIIIIlIlIlII(lllllllllllllllIlIlIIlIIIlIIIllI)) { modules.forEach((lllllllllllllllIlIlIIlIIIIlllIII) -> { if (lIlIIIIlIlIIll(lllllllllllllllIlIlIIlIIIIlllIII.getBind().isDown(lllllllllllllllIlIlIIlIIIlIIIllI))) { lllllllllllllllIlIlIIlIIIIlllIII.toggle(); } }); } } private static void lIlIIIIlIIlllI() { llllIllIlllI = new String[llllIlllIIIl[14]]; llllIllIlllI[llllIlllIIIl[0]] = lIlIIIIlIIlIlI("74t3tndxag9o7h0890bnpfzh4olk2h9x", "ADegB"); llllIllIlllI[llllIlllIIIl[1]] = lIlIIIIlIIlIll("LCsODA==", "GJcek"); llllIllIlllI[llllIlllIIIl[2]] = lIlIIIIlIIllII("2mvIb3urW50=", "cnJlB"); llllIllIlllI[llllIlllIIIl[6]] = lIlIIIIlIIllII("HR7znVTTkEU=", "DlgDA"); llllIllIlllI[llllIlllIIIl[8]] = lIlIIIIlIIllII("9q3vfhm7l33rus21toc8fndupq76itje", "HlKMG"); llllIllIlllI[llllIlllIIIl[9]] = lIlIIIIlIIllII("pQouDzEMkGw=", "TWAly"); llllIllIlllI[llllIlllIIIl[10]] = lIlIIIIlIIlIlI("dl9PbBoT9n+5YaoubI0iZg==", "bXlhI"); llllIllIlllI[llllIlllIIIl[11]] = lIlIIIIlIIlIll("vqbpgud2ghvjgm1n5hdgjnn5818fzsf2", "PhBwN"); llllIllIlllI[llllIlllIIIl[12]] = lIlIIIIlIIlIll("VGMvIiJPYw==", "uCjPP"); llllIllIlllI[llllIlllIIIl[13]] = lIlIIIIlIIlIll("T0g+JhIQCTQmW0M=", "chSCa"); } public static boolean isModuleEnabled(String lllllllllllllllIlIlIIlIIIIllllll) { byte lllllllllllllllIlIlIIlIIIIllllII = getModuleByName(lllllllllllllllIlIlIIlIIIIllllll); return (boolean)(lIlIIIIlIlIlIl(lllllllllllllllIlIlIIlIIIIllllII) ? llllIlllIIIl[0] : lllllllllllllllIlIlIIlIIIIllllII.isEnabled()); } private static void lIlIIIIlIlIIlI() { llllIlllIIIl = new int[15]; llllIlllIIIl[0] = (27 ^ 18) << (" ".length() << " ".length()) & ~((203 ^ 194) << (" ".length() << " ".length())); llllIlllIIIl[1] = " ".length(); llllIlllIIIl[2] = " ".length() << " ".length(); llllIlllIIIl[3] = ((42 ^ 11) << (" ".length() << " ".length())) + (" ".length() << (" ".length() << " ".length())) - ((97 ^ 112) << " ".length()) + 170 + 268 - 393 + 238 << " ".length(); llllIlllIIIl[4] = 120 + 24 - -92 + 61 + 38 + 171 - 105 + 69 - (106 + 123 - 108 + 30 << " ".length()) + 267 + 230 - 419 + 525; llllIlllIIIl[5] = 5520 + 6493 - 7653 + 3065; llllIlllIIIl[6] = " ".length(); llllIlllIIIl[7] = (195 ^ 138 ^ (175 ^ 186) << (" ".length() << " ".length())) << (" ".length() << " ".length()); llllIlllIIIl[8] = " ".length() << (" ".length() << " ".length()); llllIlllIIIl[9] = 186 ^ 191; llllIlllIIIl[10] = " ".length() << " ".length(); llllIlllIIIl[11] = 66 ^ 69; llllIlllIIIl[12] = " ".length() << " ".length(); llllIlllIIIl[13] = 206 ^ 199; llllIlllIIIl[14] = (136 ^ 147 ^ (58 ^ 53) << " ".length()) << " ".length(); } private static boolean lIlIIIIlIlIIll(int var0) { return var0 != 0; } private static String lIlIIIIlIIlIll(String lllllllllllllllIlIlIIIllllllIlII, String lllllllllllllllIlIlIIIlllllIlllI) { lllllllllllllllIlIlIIIllllllIlII = new String(Base64.getDecoder().decode(lllllllllllllllIlIlIIIllllllIlII.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); StringBuilder lllllllllllllllIlIlIIIllllllIIlI = new StringBuilder(); char[] lllllllllllllllIlIlIIIllllllIIIl = lllllllllllllllIlIlIIIlllllIlllI.toCharArray(); int lllllllllllllllIlIlIIIllllllIIII = llllIlllIIIl[0]; boolean lllllllllllllllIlIlIIIlllllIlIlI = lllllllllllllllIlIlIIIllllllIlII.toCharArray(); int lllllllllllllllIlIlIIIlllllIlIIl = lllllllllllllllIlIlIIIlllllIlIlI.length; int lllllllllllllllIlIlIIIlllllIlIII = llllIlllIIIl[0]; do { if (!lIlIIIIlIlIlll(lllllllllllllllIlIlIIIlllllIlIII, lllllllllllllllIlIlIIIlllllIlIIl)) { return String.valueOf(lllllllllllllllIlIlIIIllllllIIlI); } char lllllllllllllllIlIlIIIllllllIlIl = lllllllllllllllIlIlIIIlllllIlIlI[lllllllllllllllIlIlIIIlllllIlIII]; lllllllllllllllIlIlIIIllllllIIlI.append((char)(lllllllllllllllIlIlIIIllllllIlIl ^ lllllllllllllllIlIlIIIllllllIIIl[lllllllllllllllIlIlIIIllllllIIII % lllllllllllllllIlIlIIIllllllIIIl.length])); "".length(); ++lllllllllllllllIlIlIIIllllllIIII; ++lllllllllllllllIlIlIIIlllllIlIII; "".length(); } while(" ".length() > -" ".length()); return null; } private static boolean lIlIIIIlIlIlll(int var0, int var1) { return var0 < var1; } private static boolean lIlIIIIlIlIlIl(Object var0) { return var0 == null; } public static void onUpdate() { modules.stream().filter((lllllllllllllllIlIlIIlIIIIlIIIlI) -> { int var10000; if (lIlIIIIlIlIlII(lllllllllllllllIlIlIIlIIIIlIIIlI.alwaysListening) && !lIlIIIIlIlIIll(lllllllllllllllIlIlIIlIIIIlIIIlI.isEnabled())) { var10000 = llllIlllIIIl[0]; } else { var10000 = llllIlllIIIl[1]; "".length(); if (" ".length() == 0) { return (boolean)((102 + 99 - 176 + 102 ^ (135 ^ 142) << " ".length()) & ((111 ^ 46) << " ".length() ^ 159 + 140 - 184 + 66 ^ -" ".length())); } } return (boolean)var10000; }).forEach((lllllllllllllllIlIlIIlIIIIlIIlII) -> { lllllllllllllllIlIlIIlIIIIlIIlII.onUpdate(); }); } public static void onRender() { modules.stream().filter((lllllllllllllllIlIlIIlIIIIlIlIII) -> { int var10000; if (lIlIIIIlIlIlII(lllllllllllllllIlIlIIlIIIIlIlIII.alwaysListening) && !lIlIIIIlIlIIll(lllllllllllllllIlIlIIlIIIIlIlIII.isEnabled())) { var10000 = llllIlllIIIl[0]; } else { var10000 = llllIlllIIIl[1]; "".length(); if (((102 + 78 - 149 + 194 ^ (105 ^ 10) << " ".length()) & (70 ^ 83 ^ (3 ^ 26) << " ".length() ^ -" ".length())) == " ".length()) { return (boolean)((117 ^ 80 ^ (100 ^ 97) << (" ".length() << " ".length())) & ((201 ^ 154) << " ".length() ^ 143 + 27 - 39 + 20 ^ -" ".length())); } } return (boolean)var10000; }).forEach((lllllllllllllllIlIlIIlIIIIlIlIll) -> { lllllllllllllllIlIlIIlIIIIlIlIll.onRender(); }); } private static String lIlIIIIlIIlIlI(String lllllllllllllllIlIlIIlIIIIIlIIIl, String lllllllllllllllIlIlIIlIIIIIIlllI) { try { double lllllllllllllllIlIlIIlIIIIIIllIl = new SecretKeySpec(Arrays.copyOf(MessageDigest.getInstance("MD5").digest(lllllllllllllllIlIlIIlIIIIIIlllI.getBytes(StandardCharsets.UTF_8)), llllIlllIIIl[12]), "DES"); float lllllllllllllllIlIlIIlIIIIIIllII = Cipher.getInstance("DES"); lllllllllllllllIlIlIIlIIIIIIllII.init(llllIlllIIIl[2], lllllllllllllllIlIlIIlIIIIIIllIl); return new String(lllllllllllllllIlIlIIlIIIIIIllII.doFinal(Base64.getDecoder().decode(lllllllllllllllIlIlIIlIIIIIlIIIl.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8); } catch (Exception var4) { var4.printStackTrace(); return null; } } public static ArrayList<Module> getModules() { return modules; } public static void onWorldRender(RenderWorldLastEvent lllllllllllllllIlIlIIlIIIlIIllIl) { Minecraft.func_71410_x().field_71424_I.func_76320_a(llllIllIlllI[llllIlllIIIl[1]]); Minecraft.func_71410_x().field_71424_I.func_76320_a(llllIllIlllI[llllIlllIIIl[2]]); GlStateManager.func_179090_x(); GlStateManager.func_179147_l(); GlStateManager.func_179118_c(); GlStateManager.func_179120_a(llllIlllIIIl[3], llllIlllIIIl[4], llllIlllIIIl[1], llllIlllIIIl[0]); GlStateManager.func_179103_j(llllIlllIIIl[5]); GlStateManager.func_179097_i(); GlStateManager.func_187441_d(1.0F); Vec3d lllllllllllllllIlIlIIlIIIlIIllII = EntityUtil.getInterpolatedPos(Wrapper.getPlayer(), lllllllllllllllIlIlIIlIIIlIIllIl.getPartialTicks()); RenderEvent lllllllllllllllIlIlIIlIIIlIIlIll = new RenderEvent(SnowTessellator.INSTANCE, lllllllllllllllIlIlIIlIIIlIIllII); lllllllllllllllIlIlIIlIIIlIIlIll.resetTranslation(); Minecraft.func_71410_x().field_71424_I.func_76319_b(); modules.stream().filter((lllllllllllllllIlIlIIlIIIIlIlllI) -> { int var10000; if (lIlIIIIlIlIlII(lllllllllllllllIlIlIIlIIIIlIlllI.alwaysListening) && !lIlIIIIlIlIIll(lllllllllllllllIlIlIIlIIIIlIlllI.isEnabled())) { var10000 = llllIlllIIIl[0]; } else { var10000 = llllIlllIIIl[1]; "".length(); if (null != null) { return (boolean)((" ".length() << (" ".length() << " ".length()) ^ 62 ^ 5) & (79 ^ 96 ^ " ".length() << (" ".length() << (" ".length() << " ".length())) ^ -" ".length())); } } return (boolean)var10000; }).forEach((lllllllllllllllIlIlIIlIIIIllIIlI) -> { Minecraft.func_71410_x().field_71424_I.func_76320_a(lllllllllllllllIlIlIIlIIIIllIIlI.getName()); lllllllllllllllIlIlIIlIIIIllIIlI.onWorldRender(lllllllllllllllIlIlIIlIIIlIIlIll); Minecraft.func_71410_x().field_71424_I.func_76319_b(); }); Minecraft.func_71410_x().field_71424_I.func_76320_a(llllIllIlllI[llllIlllIIIl[6]]); GlStateManager.func_187441_d(1.0F); GlStateManager.func_179103_j(llllIlllIIIl[7]); GlStateManager.func_179084_k(); GlStateManager.func_179141_d(); GlStateManager.func_179098_w(); GlStateManager.func_179126_j(); GlStateManager.func_179089_o(); SnowTessellator.releaseGL(); Minecraft.func_71410_x().field_71424_I.func_76319_b(); Minecraft.func_71410_x().field_71424_I.func_76319_b(); } static { lIlIIIIlIlIIlI(); lIlIIIIlIIlllI(); modules = new ArrayList(); lookup = new HashMap(); } public static void initialize() { Set<Class> lllllllllllllllIlIlIIlIIIlIlIIIl = ClassFinder.findClasses(ClickGUI.class.getPackage().getName(), Module.class); lllllllllllllllIlIlIIlIIIlIlIIIl.forEach((lllllllllllllllIlIlIIlIIIIIllIlI) -> { try { Module lllllllllllllllIlIlIIlIIIIIllllI = (Module)lllllllllllllllIlIlIIlIIIIIllIlI.getConstructor().newInstance(); modules.add(lllllllllllllllIlIlIIlIIIIIllllI); "".length(); } catch (InvocationTargetException var2) { var2.getCause().printStackTrace(); System.err.println(String.valueOf((new StringBuilder()).append(llllIllIlllI[llllIlllIIIl[8]]).append(lllllllllllllllIlIlIIlIIIIIllIlI.getSimpleName()).append(llllIllIlllI[llllIlllIIIl[9]]).append(var2.getClass().getSimpleName()).append(llllIllIlllI[llllIlllIIIl[10]]).append(var2.getMessage()))); "".length(); if (-" ".length() < 0) { return; } return; } catch (Exception var3) { var3.printStackTrace(); System.err.println(String.valueOf((new StringBuilder()).append(llllIllIlllI[llllIlllIIIl[11]]).append(lllllllllllllllIlIlIIlIIIIIllIlI.getSimpleName()).append(llllIllIlllI[llllIlllIIIl[12]]).append(var3.getClass().getSimpleName()).append(llllIllIlllI[llllIlllIIIl[13]]).append(var3.getMessage()))); return; } "".length(); if (" ".length() >= (((103 ^ 106) << " ".length() ^ 125 ^ 90) & (67 ^ 54 ^ (8 ^ 21) << " ".length() ^ -" ".length()))) { ; } }); SnowMod.log.info(llllIllIlllI[llllIlllIIIl[0]]); getModules().sort(Comparator.comparing(Module::getName)); } private static String lIlIIIIlIIllII(String lllllllllllllllIlIlIIlIIIIIIIIlI, String lllllllllllllllIlIlIIlIIIIIIIIll) { try { SecretKeySpec lllllllllllllllIlIlIIlIIIIIIIlll = new SecretKeySpec(MessageDigest.getInstance("MD5").digest(lllllllllllllllIlIlIIlIIIIIIIIll.getBytes(StandardCharsets.UTF_8)), "Blowfish"); Cipher lllllllllllllllIlIlIIlIIIIIIIllI = Cipher.getInstance("Blowfish"); lllllllllllllllIlIlIIlIIIIIIIllI.init(llllIlllIIIl[2], lllllllllllllllIlIlIIlIIIIIIIlll); return new String(lllllllllllllllIlIlIIlIIIIIIIllI.doFinal(Base64.getDecoder().decode(lllllllllllllllIlIlIIlIIIIIIIIlI.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8); } catch (Exception var4) { var4.printStackTrace(); return null; } } public static void updateLookup() { lookup.clear(); Iterator lllllllllllllllIlIlIIlIIIlIlIlIl = modules.iterator(); do { if (!lIlIIIIlIlIIll(lllllllllllllllIlIlIIlIIIlIlIlIl.hasNext())) { return; } Module lllllllllllllllIlIlIIlIIIlIlIllI = (Module)lllllllllllllllIlIlIIlIIIlIlIlIl.next(); lookup.put(lllllllllllllllIlIlIIlIIIlIlIllI.getName().toLowerCase(), lllllllllllllllIlIlIIlIIIlIlIllI); "".length(); "".length(); } while((((37 ^ 112) << " ".length() ^ 23 + 110 - 58 + 116) & (77 ^ 66 ^ (148 ^ 153) << " ".length() ^ -" ".length())) == 0); } private static boolean lIlIIIIlIlIlII(int var0) { return var0 == 0; } }
92458247545ade6f752be876f5034a5493cc9fc1
338
java
Java
Shop_Dao/src/main/java/com/it/taotao/dao/TbItemParamDao.java
pi408637535/Online_Shop
03ef0ba2c71d8f84db7509c0e2f9f3877cbf28ec
[ "MIT" ]
null
null
null
Shop_Dao/src/main/java/com/it/taotao/dao/TbItemParamDao.java
pi408637535/Online_Shop
03ef0ba2c71d8f84db7509c0e2f9f3877cbf28ec
[ "MIT" ]
null
null
null
Shop_Dao/src/main/java/com/it/taotao/dao/TbItemParamDao.java
pi408637535/Online_Shop
03ef0ba2c71d8f84db7509c0e2f9f3877cbf28ec
[ "MIT" ]
null
null
null
22.533333
64
0.760355
1,003,405
package com.it.taotao.dao; import com.it.taotao.pojo.TbItemParam; import java.util.List; /** * Created by 55 on 2016/5/11. */ public interface TbItemParamDao { public TbItemParam getTbItemDescByItemCatId(Long itemCatId); public List<TbItemParam> getItemParamList(); public int saveTbItemParam(TbItemParam tbItemParam); }
92458381891932824cd1455b21bab2297dcd6312
2,344
java
Java
polardbx-executor/src/main/java/com/alibaba/polardbx/executor/ddl/job/builder/AlterTableBuilder.java
arkbriar/galaxysql
df28f91eab772839e5df069739a065ac01c0a26e
[ "Apache-2.0" ]
1
2021-12-17T02:38:33.000Z
2021-12-17T02:38:33.000Z
polardbx-executor/src/main/java/com/alibaba/polardbx/executor/ddl/job/builder/AlterTableBuilder.java
arkbriar/galaxysql
df28f91eab772839e5df069739a065ac01c0a26e
[ "Apache-2.0" ]
null
null
null
polardbx-executor/src/main/java/com/alibaba/polardbx/executor/ddl/job/builder/AlterTableBuilder.java
arkbriar/galaxysql
df28f91eab772839e5df069739a065ac01c0a26e
[ "Apache-2.0" ]
null
null
null
34.985075
114
0.715444
1,003,406
/* * Copyright [2013-2021], Alibaba Group Holding Limited * * 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.polardbx.executor.ddl.job.builder; import com.alibaba.polardbx.gms.topology.DbInfoManager; import com.alibaba.polardbx.optimizer.context.ExecutionContext; import com.alibaba.polardbx.optimizer.core.rel.ddl.data.AlterTablePreparedData; import org.apache.calcite.rel.core.DDL; import org.apache.calcite.sql.SqlAlterTable; /** * Plan builder for ALTER TABLE * * @author moyi * @since 2021/07 */ public class AlterTableBuilder extends DdlPhyPlanBuilder { protected final AlterTablePreparedData preparedData; protected AlterTableBuilder(DDL ddl, AlterTablePreparedData preparedData, ExecutionContext executionContext) { super(ddl, preparedData, executionContext); this.preparedData = preparedData; } public static AlterTableBuilder create(DDL ddl, AlterTablePreparedData preparedData, ExecutionContext ec) { return DbInfoManager.getInstance().isNewPartitionDb(preparedData.getSchemaName()) ? new AlterPartitionTableBuilder(ddl, preparedData, ec) : new AlterTableBuilder(ddl, preparedData, ec); } @Override public void buildTableRuleAndTopology() { buildExistingTableRule(preparedData.getTableName()); buildChangedTableTopology(preparedData.getSchemaName(), preparedData.getTableName()); } @Override public void buildPhysicalPlans() { buildSqlTemplate(); buildPhysicalPlans(preparedData.getTableName()); } @Override protected void buildSqlTemplate() { super.buildSqlTemplate(); this.sequenceBean = ((SqlAlterTable) this.sqlTemplate).getAutoIncrement(); } }
924584821463ee933eb17c3f9e40283c25695555
3,038
java
Java
src/main/java/in/ekstep/am/step/CreateCredentialWithKeyStep.java
sunbird-cb/sunbird-apimanager-util
e6efe0797b07b23de4e10ab5212c93da95497b69
[ "MIT" ]
null
null
null
src/main/java/in/ekstep/am/step/CreateCredentialWithKeyStep.java
sunbird-cb/sunbird-apimanager-util
e6efe0797b07b23de4e10ab5212c93da95497b69
[ "MIT" ]
4
2020-09-14T13:38:05.000Z
2021-01-04T14:02:48.000Z
src/main/java/in/ekstep/am/step/CreateCredentialWithKeyStep.java
sunbird-cb/sunbird-apimanager-util
e6efe0797b07b23de4e10ab5212c93da95497b69
[ "MIT" ]
9
2020-06-05T06:14:39.000Z
2022-02-17T06:02:46.000Z
39.973684
131
0.750823
1,003,407
package in.ekstep.am.step; import com.fasterxml.jackson.databind.ObjectMapper; import in.ekstep.am.builder.CredentialDetails; import in.ekstep.am.external.AmAdminApi; import in.ekstep.am.external.AmAdminApiCreateCredentialResponse; import in.ekstep.am.external.AmAdminApiGetCredentialResponse; import in.ekstep.am.external.AmResponse; import in.ekstep.am.jwt.JWTUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.text.MessageFormat.format; public class CreateCredentialWithKeyStep implements Step { private final Logger log = LoggerFactory.getLogger(this.getClass()); private AmAdminApi amAdminApi; private String userName; private CredentialDetails responseBuilder; private String key; CreateCredentialWithKeyStep(String userName, CredentialDetails responseBuilder, AmAdminApi api, String key) { this.userName = userName; this.responseBuilder = responseBuilder; amAdminApi = api; this.key = key; } @Override public void execute() throws Exception { AmResponse response = amAdminApi.getCredential(userName, key); if (AmAdminApi.OK.equals(response.code())) { AmAdminApiGetCredentialResponse getCredentialResponse = new ObjectMapper().readValue(response.body(), AmAdminApiGetCredentialResponse.class); updateResponseBuilder(getCredentialResponse.key(), getCredentialResponse.secret()); return; } if (AmAdminApi.NOT_FOUND.equals(response.code())) { log.error(format("CREDENTIAL DOES NOT EXISTS, USERNAME: {0}", userName)); createCredential(); } } private void createCredential() throws Exception { log.info(format("CREATE NEW CREDENTIALS FOR CONSUMER. USERNAME: {0}", userName)); AmResponse createCredentialResponse = amAdminApi.createCredential(userName, key); if (AmAdminApi.CREATED.equals(createCredentialResponse.code())) { AmAdminApiCreateCredentialResponse amCreateCredentialResponse = new ObjectMapper().readValue(createCredentialResponse.body(), AmAdminApiCreateCredentialResponse.class); updateResponseBuilder(amCreateCredentialResponse.key(), amCreateCredentialResponse.secret()); log.info(format("CREATED CREDENTIAL. USERNAME: {0}", userName)); return; } String errorDetail = AmAdminApi.CONFLICT.equals(createCredentialResponse.code()) ? format(" KEY : {0}, already exists.", key) : ""; log.error(format("UNABLE TO CREATE CREDENTIAL. USERNAME: {0}, AM RESPONSE CODE: {1}, AM RESPONSE: {2}", userName, createCredentialResponse.code(), createCredentialResponse.body())); responseBuilder.markFailure("CREATE_CREDENTIAL_ERROR", format("ERROR WHEN CREATING CREDENTIAL FOR CONSUMER.{0}", errorDetail)); } private void updateResponseBuilder(String key, String secret) { responseBuilder.setKey(key); responseBuilder.setSecret(secret); responseBuilder.setToken(JWTUtil.createHS256Token(key, secret, null)); } private boolean shouldFilter() { return !(key == null || key.isEmpty()); } }
92458491e083eb4a1ed487e1238e06a83cd677ea
12,392
java
Java
Ghidra/Framework/Generic/src/main/java/ghidra/framework/preferences/Preferences.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
17
2022-01-15T03:52:37.000Z
2022-03-30T18:12:17.000Z
Ghidra/Framework/Generic/src/main/java/ghidra/framework/preferences/Preferences.java
BStudent/ghidra
0cdc722921cef61b7ca1b7236bdc21079fd4c03e
[ "Apache-2.0" ]
9
2022-01-15T03:58:02.000Z
2022-02-21T10:22:49.000Z
Ghidra/Framework/Generic/src/main/java/ghidra/framework/preferences/Preferences.java
BStudent/ghidra
0cdc722921cef61b7ca1b7236bdc21079fd4c03e
[ "Apache-2.0" ]
1
2020-09-07T21:42:06.000Z
2020-09-07T21:42:06.000Z
30.825871
104
0.713363
1,003,408
/* ### * IP: GHIDRA * * 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 ghidra.framework.preferences; import java.io.*; import java.util.*; import ghidra.framework.Application; import ghidra.framework.GenericRunInfo; import ghidra.util.Msg; import util.CollectionUtils; import utilities.util.FileUtilities; /** * Uses Properties to manage user preferences as name/value pairs. All methods * are static. */ public class Preferences { /** * The <code>APPLICATION_PREFERENCES_FILENAME</code> is the default name for the user preferences file. * @see ghidra.framework.preferences.Preferences */ public static final String APPLICATION_PREFERENCES_FILENAME = "preferences"; /** * Preference name of the user plugin path. */ private final static String USER_PLUGIN_PATH = "UserPluginPath"; /** * Preference name for the last opened archive directory. */ public static final String LAST_OPENED_ARCHIVE_DIRECTORY = "LastOpenedArchiveDirectory"; /** * Preference name for the project directory. */ public final static String PROJECT_DIRECTORY = "ProjectDirectory"; /** * Preference name for import directory that was last accessed for tools. */ public final static String LAST_TOOL_IMPORT_DIRECTORY = "LastToolImportDirectory"; /** * Preference name for export directory that was last accessed for tools. */ public final static String LAST_TOOL_EXPORT_DIRECTORY = "LastToolExportDirectory"; /** * Preference name for directory last selected for creating a new project. */ public final static String LAST_NEW_PROJECT_DIRECTORY = "LastNewProjectDirectory"; /** * Preference name for the import directory that was last accessed for * domain files. */ public final static String LAST_IMPORT_DIRECTORY = "LastImportDirectory"; /** * Preference name for the export directory that was last accessed. */ public final static String LAST_EXPORT_DIRECTORY = "LastExportDirectory"; /** * The data storage for this class. */ private static Properties properties = new Properties(); /** * Data storage that contains preferences data from a previous installation. */ private static Properties previousProperties = new Properties(); private static String filename = null; // Always attempt to load initial user preferences static { try { File userSettingsDir = Application.getUserSettingsDirectory(); if (userSettingsDir != null) { load(userSettingsDir.getAbsolutePath() + File.separatorChar + APPLICATION_PREFERENCES_FILENAME); } } catch (Exception e) { Msg.error(Preferences.class, "Unexpected exception reading preferences file: ", e); } } /** * Don't allow instantiation of this class. */ private Preferences() { // utils class } /** * Initialize properties by reading name, values from the given filename. * @param pathName name of preferences file to read in; could be null * @throws IOException if there is a problem reading the file */ private static void load(String pathName) throws IOException { // create properties Msg.info(Preferences.class, "Loading user preferences: " + pathName); properties = new Properties(); filename = pathName; File file = new File(pathName); if (file.exists()) { try (FileInputStream in = new FileInputStream(pathName)) { properties.load(in); } } // Try to load a previous installation's preferences so that they are usable as a // reference point for those clients that wish to maintain previous values. Note that // not all previous values should be used in a new application, as that may // cause issues when running; for example, path preferences can cause compile issues. loadPreviousInstallationPreferences(); } private static void loadPreviousInstallationPreferences() throws IOException { try (FileInputStream fis = getAlternateFileInputStream()) { if (fis != null) { previousProperties.load(fis); } } } /** * Clears all properties in this Preferences object. * <p> * <b>Warning: </b>Save any changes pending before calling this method, as this call will * erase any changes not written do disk via {@link #store()} */ public static void clear() { properties.clear(); } /** * Gets an input stream to a file that is the same named file within a different * application version directory for this user. This method will search for an * alternate file based on the application version directories modification times * and will use the first matching file it finds. * * @return a file input stream for an alternate file or null. */ private static FileInputStream getAlternateFileInputStream() { File previousFile = GenericRunInfo.getPreviousApplicationSettingsFile(APPLICATION_PREFERENCES_FILENAME); if (previousFile == null) { return null; } try { FileInputStream fis = new FileInputStream(previousFile); Msg.info(Preferences.class, "Loading previous preferences: " + previousFile); return fis; } catch (FileNotFoundException fnfe) { // Ignore so we can try another directory. } return null; } /** * Removes the given preference from this preferences object. * * @param name the name of the preference key to remove. * @return the value that was stored with the given key. */ public static String removeProperty(String name) { return (String) properties.remove(name); } /** * Get the property with the given name. * <p> * Note: all <code>getProperty(...)</code> methods will first check {@link System#getProperty(String)} * for a value first. This allows users to override preferences from the command-line. * @param name the property name * @return the current property value; null if not set */ public static String getProperty(String name) { // prefer system properties, which enables uses to override preferences from the command-line String systemProperty = System.getProperty(name); if (systemProperty != null) { return systemProperty; } return properties.getProperty(name, null); } /** * Get the property with the given name; if there is no property, return the defaultValue. * <p> * Note: all <code>getProperty(...)</code> methods will first check {@link System#getProperty(String)} * for a value first. This allows users to override preferences from the command-line. * @param name the property name * @param defaultValue the default value * @return the property value; default value if not set * * @see #getProperty(String, String, boolean) */ public static String getProperty(String name, String defaultValue) { // prefer system properties, which enables uses to override preferences from the command-line String systemProperty = System.getProperty(name); if (systemProperty != null) { return systemProperty; } return properties.getProperty(name, defaultValue); } /** * Get the property with the given name; if there is no property, return the defaultValue. * <p> * This version of <code>getProperty</code> will, when <code>useHistoricalValue</code> is true, look * for the given preference value in the last used installation of the application. * <p> * Note: all <code>getProperty(...)</code> methods will first check {@link System#getProperty(String)} * for a value first. This allows users to override preferences from the command-line. * * @param name The name of the property for which to get a value * @param defaultValue The value to use if there is no value yet set for the given name * @param useHistoricalValue True signals to check the last used application installation for a * value for the given name <b>if that value has not yet been set</b>. * @return the property with the given name; if there is no property, * return the defaultValue. * @see #getProperty(String) * @see #getProperty(String, String) */ public static String getProperty(String name, String defaultValue, boolean useHistoricalValue) { // prefer system properties, which enables uses to override preferences from the command-line String systemProperty = System.getProperty(name); if (systemProperty != null) { return systemProperty; } String currentValue = properties.getProperty(name); if (currentValue != null) { return currentValue; } if (!useHistoricalValue) { return defaultValue; } return previousProperties.getProperty(name, defaultValue); } /** * Set the property value. If a null value is passed, then the property is removed from * this collection of preferences. * * @param name property name * @param value value for property */ public static void setProperty(String name, String value) { if (value == null) { Msg.trace(Preferences.class, "clearing property " + name); properties.remove(name); return; } Msg.trace(Preferences.class, "setting property " + name + "=" + value); properties.setProperty(name, value); } /** * Get an array of known property names. * @return if there are no properties, return a zero-length array */ public static List<String> getPropertyNames() { Collection<String> backedCollection = CollectionUtils.asCollection(properties.keySet(), String.class); return new LinkedList<>(backedCollection); } /** * Get the filename that will be used in the store() method. * @return the filename */ public static String getFilename() { return filename; } /** * Set the filename so that when the store() method is called, the * preferences are written to this file. * @param name the filename */ public static void setFilename(String name) { filename = name; } /** * Store the preferences in a file for the current filename. * @return true if the file was written * @throws RuntimeException if the preferences filename was not set */ public static boolean store() { if (filename == null) { throw new RuntimeException("Preferences filename has not been set!"); } Msg.trace(Preferences.class, "Storing user preferences: " + filename); // make sure the preferences directory exists. File file = new File(filename); if (!file.exists()) { FileUtilities.mkdirs(file.getParentFile()); } // Save properties to file BufferedOutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(filename)); properties.store(os, "User Preferences"); os.close(); return true; } catch (IOException e) { Msg.error(Preferences.class, "Failed to store user preferences: " + filename); } finally { if (os != null) { try { os.close(); } catch (IOException e) { // we tried } } } return false; } /** * Return the paths in the UserPluginPath property. * Return zero length array if this property is not set. * @return the paths * */ public static String[] getPluginPaths() { List<String> list = getPluginPathList(); if (list == null) { return new String[0]; } return list.toArray(new String[list.size()]); } /** * Set the paths to be used as the UserPluginPath property. * @param paths the paths */ public static void setPluginPaths(String[] paths) { if (paths == null || paths.length == 0) { properties.remove(USER_PLUGIN_PATH); return; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < paths.length; i++) { sb.append(paths[i]); if (i < paths.length - 1) { sb.append(File.pathSeparator); } } properties.setProperty(USER_PLUGIN_PATH, sb.toString()); } private static List<String> getPluginPathList() { String path = properties.getProperty(USER_PLUGIN_PATH); if (path == null) { return null; } List<String> list = new ArrayList<>(5); StringTokenizer st = new StringTokenizer(path, File.pathSeparator); while (st.hasMoreElements()) { String p = (String) st.nextElement(); list.add(p); } return list; } }
9245850716a70c5f839219eb8e1c080def38f0b3
3,864
java
Java
src/main/java/maxhyper/dtatum/DTAtumRegistries.java
DynamicTreesTeam/DynamicTrees-Atum
774a756d7be475eaf2953b770602b11b8b88335b
[ "MIT" ]
null
null
null
src/main/java/maxhyper/dtatum/DTAtumRegistries.java
DynamicTreesTeam/DynamicTrees-Atum
774a756d7be475eaf2953b770602b11b8b88335b
[ "MIT" ]
null
null
null
src/main/java/maxhyper/dtatum/DTAtumRegistries.java
DynamicTreesTeam/DynamicTrees-Atum
774a756d7be475eaf2953b770602b11b8b88335b
[ "MIT" ]
null
null
null
47.121951
152
0.805383
1,003,409
package maxhyper.dtatum; import com.ferreusveritas.dynamictrees.api.registry.RegistryHandler; import com.ferreusveritas.dynamictrees.api.registry.TypeRegistryEvent; import com.ferreusveritas.dynamictrees.api.worldgen.FeatureCanceller; import com.ferreusveritas.dynamictrees.blocks.FruitBlock; import com.ferreusveritas.dynamictrees.growthlogic.GrowthLogicKit; import com.ferreusveritas.dynamictrees.init.DTConfigs; import com.ferreusveritas.dynamictrees.systems.genfeatures.GenFeature; import com.ferreusveritas.dynamictrees.trees.Species; import com.teammetallurgy.atum.init.AtumItems; import com.teammetallurgy.atum.world.gen.feature.DeadwoodFeature; import maxhyper.dtatum.blocks.PalmFruitBlock; import maxhyper.dtatum.genfeatures.BrokenLeavesGenFeature; import maxhyper.dtatum.genfeatures.PalmFruitGenFeature; import maxhyper.dtatum.genfeatures.PalmVinesGenFeature; import maxhyper.dtatum.growthlogic.DeadGrowthLogicKit; import maxhyper.dtatum.trees.DeadwoodSpecies; import maxhyper.dtatum.worldgen.DeadwoodFeatureCanceller; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD) public class DTAtumRegistries { public static GenFeature PALM_FRUIT_FEATURE; public static GenFeature PALM_VINES_FEATURE; public static GenFeature BROKEN_LEAVES_FEATURE; public static GrowthLogicKit DEAD_GROWTH_LOGIC_KIT = new DeadGrowthLogicKit(new ResourceLocation(DynamicTreesAtum.MOD_ID,"dead")); public static final FruitBlock DATE_FRUIT = new PalmFruitBlock().setCanBoneMeal(DTConfigs.CAN_BONE_MEAL_APPLE::get); public static void setup(){ RegistryHandler.addBlock(new ResourceLocation(DynamicTreesAtum.MOD_ID,"date_fruit"), DATE_FRUIT); } @SubscribeEvent public static void registerSpeciesTypes (final TypeRegistryEvent<Species> event) { event.registerType(new ResourceLocation(DynamicTreesAtum.MOD_ID, "deadwood"), DeadwoodSpecies.TYPE); } /** canceller for Atum's deadwood trees. Cancells all features of type {@link DeadwoodFeature}. */ public static final FeatureCanceller DEADWOOD_CANCELLER = new DeadwoodFeatureCanceller<>(new ResourceLocation(DynamicTreesAtum.MOD_ID, "deadwood")); @SubscribeEvent public static void onFeatureCancellerRegistry(final com.ferreusveritas.dynamictrees.api.registry.RegistryEvent<FeatureCanceller> event) { event.getRegistry().registerAll(DEADWOOD_CANCELLER); } @SubscribeEvent public static void onGenFeatureRegistry (final com.ferreusveritas.dynamictrees.api.registry.RegistryEvent<GenFeature> event) { PALM_FRUIT_FEATURE = new PalmFruitGenFeature(new ResourceLocation(DynamicTreesAtum.MOD_ID,"palm_fruit")); PALM_VINES_FEATURE = new PalmVinesGenFeature(new ResourceLocation(DynamicTreesAtum.MOD_ID,"palm_vines")); BROKEN_LEAVES_FEATURE = new BrokenLeavesGenFeature(new ResourceLocation(DynamicTreesAtum.MOD_ID,"broken_leaves")); event.getRegistry().registerAll(PALM_FRUIT_FEATURE, PALM_VINES_FEATURE, BROKEN_LEAVES_FEATURE); } @SubscribeEvent public static void onRegisterGrowthLogicKits(final com.ferreusveritas.dynamictrees.api.registry.RegistryEvent<GrowthLogicKit> event) { event.getRegistry().registerAll(DEAD_GROWTH_LOGIC_KIT); } @SubscribeEvent public static void onBlocksRegistry(final RegistryEvent.Register<Block> event) { final Species palm = Species.REGISTRY.get(new ResourceLocation(DynamicTreesAtum.MOD_ID, "palm")); if (palm.isValid()){ DATE_FRUIT.setSpecies(palm); DATE_FRUIT.setDroppedItem(new ItemStack(AtumItems.DATE)); } } }
924586284a3355df147ceec8a2569c01b910e276
276
java
Java
multithreading2/src/shop/ljsp/learn/unit1/micurrentThread/GetName.java
cjk5210/multithreading
cde62abcc3790b78b6d329fd468722e7b323f3d2
[ "Apache-2.0" ]
null
null
null
multithreading2/src/shop/ljsp/learn/unit1/micurrentThread/GetName.java
cjk5210/multithreading
cde62abcc3790b78b6d329fd468722e7b323f3d2
[ "Apache-2.0" ]
null
null
null
multithreading2/src/shop/ljsp/learn/unit1/micurrentThread/GetName.java
cjk5210/multithreading
cde62abcc3790b78b6d329fd468722e7b323f3d2
[ "Apache-2.0" ]
null
null
null
25.090909
61
0.688406
1,003,410
package shop.ljsp.learn.unit1.micurrentThread; public class GetName { public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); } } /* 说明, main 方法 被 名为 main 的 线程 调用。 The main method was called by a Thread named 'main'; */
92458704bba6f9ca5b1e56091ebf331e1f9f5774
186
java
Java
common-orm/src/main/java/jef/database/support/MultipleDatabaseOperateException.java
mrjiyi/ef-orm
3d1b2f50297fb921f5951b33f1b81bee309246e5
[ "Apache-2.0" ]
1
2021-12-06T13:42:54.000Z
2021-12-06T13:42:54.000Z
common-orm/src/main/java/jef/database/support/MultipleDatabaseOperateException.java
mrjiyi/ef-orm
3d1b2f50297fb921f5951b33f1b81bee309246e5
[ "Apache-2.0" ]
null
null
null
common-orm/src/main/java/jef/database/support/MultipleDatabaseOperateException.java
mrjiyi/ef-orm
3d1b2f50297fb921f5951b33f1b81bee309246e5
[ "Apache-2.0" ]
2
2020-06-17T01:09:53.000Z
2021-03-03T06:50:49.000Z
20.666667
71
0.827957
1,003,411
package jef.database.support; public class MultipleDatabaseOperateException extends RuntimeException{ public MultipleDatabaseOperateException(String message) { super(message); } }
9245870af78a226d5434b62a39178116de92c0fd
4,118
java
Java
Project Garden/src/main/java/jwk/minecraft/garden/currency/AbstractCurrencyManager.java
jwoo1601/Java-Minecraft-Mods
1029d5ddd35cd7289b63ff34db6bb95b67763dc7
[ "BSD-3-Clause" ]
null
null
null
Project Garden/src/main/java/jwk/minecraft/garden/currency/AbstractCurrencyManager.java
jwoo1601/Java-Minecraft-Mods
1029d5ddd35cd7289b63ff34db6bb95b67763dc7
[ "BSD-3-Clause" ]
null
null
null
Project Garden/src/main/java/jwk/minecraft/garden/currency/AbstractCurrencyManager.java
jwoo1601/Java-Minecraft-Mods
1029d5ddd35cd7289b63ff34db6bb95b67763dc7
[ "BSD-3-Clause" ]
null
null
null
23.397727
124
0.717096
1,003,412
package jwk.minecraft.garden.currency; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import java.util.UUID; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nonnull; import jwk.minecraft.garden.ProjectGarden; import jwk.minecraft.garden.network.PacketCurrency; import jwk.minecraft.garden.network.PacketCurrency.Action; import jwk.minecraft.garden.util.INBTConvertable; import jwk.minecraft.garden.util.NBTFileManager; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; public abstract class AbstractCurrencyManager<T extends INBTConvertable> implements ICurrencyManager<T> { public static final String CURRENCY_DEFAULT_PATH = ProjectGarden.getSaveDirectory() + "\\currency"; public final long DefaultAmount; protected ICurrency currency; protected AbstractCurrencyData<T> data; private NBTFileManager fileManager; protected AbstractCurrencyManager(@Nonnull AbstractCurrencyData<T> data, @Nonnull ICurrency currency, long defaultAmount) { checkNotNull(data); checkNotNull(currency); checkArgument(defaultAmount > 0); DefaultAmount = defaultAmount; this.currency = currency; this.data = data; this.fileManager = new NBTFileManager(CURRENCY_DEFAULT_PATH + "\\" + currency.getDisplayName() + ".dat"); } @Override public boolean register(@Nonnull T target) { checkNotNull(target); if (!data.objects.containsKey(target)) { data.objects.put(target, 0L); return true; } return false; } @Override public boolean unregister(@Nonnull T target) { checkNotNull(target); if (data.objects.containsKey(target)) { data.objects.remove(target); return true; } return false; } public long increase(@Nonnull T target) { return increase(target, DefaultAmount); } @Override public long increase(@Nonnull T target, long amount) { checkArgument(amount >= 0, "the value to be added must be greater than or equal to 0"); long prev = get(target); if (prev == -1) return -1; long result = prev + amount; set(target, prev + amount); return result; } public long decrease(@Nonnull T target) { return decrease(target, DefaultAmount); } @Override public long decrease(@Nonnull T target, long amount) { checkArgument(amount >= 0, "the value to be subtracted must be greater than or equal to 0"); long prev = get(target); if (prev == -1) return -1; long result = prev - amount; set(target, result >= 0? result : 0); return result; } @Override public long set(@Nonnull T target, long value) { checkNotNull(target); checkArgument(value >= 0, "the value to be replaced must be greater than or equal to 0"); if (!isDataExist(target)) return -1; return data.objects.put(target, value); } @Override public long get(@Nonnull T target) { if (isDataExist(target)) return data.objects.get(target); return -1; } @Override public boolean isDataExist(@Nonnull T target) { checkNotNull(target); return data.objects.containsKey(target); } @Override public int getDataSize() { return data.objects.size(); } @Override public void onLoad() { try { data.read(fileManager.readFromFile()); } catch (FileNotFoundException e) { ProjectGarden.logger.info("no previous currency file detected <path=" + e.getMessage() + ">"); } catch (IOException e) { e.printStackTrace(); } } @Override public void onUnload() { data.objects.clear(); } @Override public void onSave() { if (data.objects.isEmpty()) return; try { NBTTagCompound compound = new NBTTagCompound(); data.write(compound); fileManager.writeToFile(true, compound); } catch (IOException e) { e.printStackTrace(); } } @Override public abstract void onDataChanged(@Nonnull T target, long value); protected Map<T, Long> getObjects() { return data.objects; } }
92458713fa6f4e1f63b5052d182da7ffe2a85e8e
318
java
Java
src/bank/Withdraw.java
ajithkumar-n/Mimicking-banking-system
0fa907eb39777a0a5ca9d243e8c23109d65b3d75
[ "MIT" ]
1
2019-06-18T04:34:39.000Z
2019-06-18T04:34:39.000Z
src/bank/Withdraw.java
ajithkumar-n/Mimicking-banking-system
0fa907eb39777a0a5ca9d243e8c23109d65b3d75
[ "MIT" ]
null
null
null
src/bank/Withdraw.java
ajithkumar-n/Mimicking-banking-system
0fa907eb39777a0a5ca9d243e8c23109d65b3d75
[ "MIT" ]
null
null
null
15.9
49
0.726415
1,003,413
package bank; public class Withdraw implements Transaction { private double amount; private double balance; public Withdraw(double amount, double balance) { this.amount=amount; this.balance=balance; } public double getAmount() { return amount; } public double getBalance() { return balance; } }
924587cf5bd6f83d29203886c83ac8b30373bee2
2,660
java
Java
nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/iterator/StandardScaler.java
springcoil/nd4j
561663234fa486cec237c97bcb81d724a55af8e3
[ "Apache-2.0" ]
null
null
null
nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/iterator/StandardScaler.java
springcoil/nd4j
561663234fa486cec237c97bcb81d724a55af8e3
[ "Apache-2.0" ]
5
2020-03-04T21:53:20.000Z
2022-03-31T19:09:53.000Z
nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/iterator/StandardScaler.java
springcoil/nd4j
561663234fa486cec237c97bcb81d724a55af8e3
[ "Apache-2.0" ]
1
2019-03-16T19:30:55.000Z
2019-03-16T19:30:55.000Z
27.142857
115
0.599248
1,003,414
package org.nd4j.linalg.dataset.api.iterator; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.factory.Nd4j; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * Standard scaler calculates a moving column wise * variance and mean * http://www.johndcook.com/blog/standard_deviation/ */ public class StandardScaler { private INDArray mean,std; private int runningTotal = 0; public void fit(DataSet dataSet) { mean = dataSet.getFeatureMatrix().mean(0); std = dataSet.getFeatureMatrix().std(0); } /** * Fit the given model * @param iterator the data to iterate oer */ public void fit(DataSetIterator iterator) { while(iterator.hasNext()) { DataSet next = iterator.next(); if(mean == null) { //start with the mean and std of zero //column wise mean = next.getFeatureMatrix().mean(0); std = Nd4j.zeros(mean.shape()); } else { // m_newM = m_oldM + (x - m_oldM)/m_n; // m_newS = m_oldS + (x - m_oldM)*(x - m_newM); INDArray xMinusMean = next.getFeatureMatrix().subRowVector(mean); INDArray newMean = mean.add(xMinusMean.sum(0).divi(runningTotal)); std.addi(xMinusMean.muli(next.getFeatureMatrix().subRowVector(newMean)).sum(0).divi(runningTotal)); mean = newMean; } runningTotal += next.numExamples(); } iterator.reset(); } /** * Load the given mean and std * @param mean the mean file * @param std the std file * @throws IOException */ public void load(File mean,File std) throws IOException { this.mean = Nd4j.readBinary(mean); this.std = Nd4j.readBinary(std); } /** * Save the current mean and std * @param mean the mean * @param std the std * @throws IOException */ public void save(File mean,File std) throws IOException { Nd4j.saveBinary(this.mean,mean); Nd4j.saveBinary(this.std,std); } /** * Transform the data * @param dataSet the dataset to transform */ public void transform(DataSet dataSet) { dataSet.setFeatures(dataSet.getFeatures().subiRowVector(mean)); dataSet.setFeatures(dataSet.getFeatures().diviRowVector(std)); } public INDArray getMean() { return mean; } public INDArray getStd() { return std; } }
924588085b4924676bbde41779882d3ac9f6042e
698
java
Java
BaiDuMap/app/src/main/java/cn/zhoujianfeng/baidumap/Hotel.java
1045621807/baiduMap
800696ae8050d1fd88a43e762a8ff063da883ea3
[ "Apache-2.0" ]
null
null
null
BaiDuMap/app/src/main/java/cn/zhoujianfeng/baidumap/Hotel.java
1045621807/baiduMap
800696ae8050d1fd88a43e762a8ff063da883ea3
[ "Apache-2.0" ]
null
null
null
BaiDuMap/app/src/main/java/cn/zhoujianfeng/baidumap/Hotel.java
1045621807/baiduMap
800696ae8050d1fd88a43e762a8ff063da883ea3
[ "Apache-2.0" ]
null
null
null
27.92
68
0.661891
1,003,415
package cn.zhoujianfeng.baidumap; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Hotel extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hotel); Button bt_back2 = findViewById(R.id.bt_back2); bt_back2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Hotel.this,Search.class); startActivity(intent); } }); } }
924588c1244761baf619145b22f7201011a6f4c0
1,564
java
Java
snobot_sim_java/src/test/java/com/snobot/simulator/SimDeviceDumpHelper.java
pjreiniger/WpiHalRefactor
41b182fabe9cb6650f0c7aaa7be310c9e246d33d
[ "MIT" ]
49
2018-01-05T14:10:31.000Z
2019-05-15T05:09:19.000Z
snobot_sim_java/src/test/java/com/snobot/simulator/SimDeviceDumpHelper.java
pjreiniger/WpiHalRefactor
41b182fabe9cb6650f0c7aaa7be310c9e246d33d
[ "MIT" ]
82
2019-06-14T01:44:35.000Z
2020-12-01T07:12:13.000Z
snobot_sim_java/src/test/java/com/snobot/simulator/SimDeviceDumpHelper.java
pjreiniger/WpiHalRefactor
41b182fabe9cb6650f0c7aaa7be310c9e246d33d
[ "MIT" ]
8
2018-02-02T07:31:30.000Z
2019-05-03T00:14:48.000Z
32.583333
115
0.608696
1,003,416
package com.snobot.simulator; import java.lang.reflect.Field; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import edu.wpi.first.wpilibj.simulation.SimDeviceSim; import edu.wpi.first.hal.simulation.SimDeviceDataJNI.SimDeviceInfo; public final class SimDeviceDumpHelper { private static final Logger sLOGGER = LogManager.getLogger(SimDeviceDumpHelper.class); private SimDeviceDumpHelper() { // Nothing to do } @SuppressWarnings("PMD.ConsecutiveLiteralAppends") public static void dumpSimDevices() { StringBuilder builder = new StringBuilder(200); builder.append("***************************************************\nDumping devices:\n"); for (SimDeviceInfo x : SimDeviceSim.enumerateDevices("")) { builder.append("Got a device: \n"); Field privateStringField; try { privateStringField = SimDeviceInfo.class.getDeclaredField("name"); privateStringField.setAccessible(true); builder.append(" ").append(privateStringField.get(x)).append('\n'); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) { sLOGGER.log(Level.ERROR, "Failed to get sim device", ex); } } builder.append("***************************************************\n"); sLOGGER.log(Level.INFO, builder); } }
924588e170c93d9de2c592007762cb0547f65eff
1,456
java
Java
gmall-pms-interface/src/main/java/com/atguigu/gmall/pms/entity/CategoryEntity.java
lvym-web/gmall-2020
3d7c1eff913435aae32ee917afa2d2d150fca506
[ "Apache-2.0" ]
null
null
null
gmall-pms-interface/src/main/java/com/atguigu/gmall/pms/entity/CategoryEntity.java
lvym-web/gmall-2020
3d7c1eff913435aae32ee917afa2d2d150fca506
[ "Apache-2.0" ]
2
2021-03-19T20:25:07.000Z
2021-04-22T17:11:16.000Z
gmall-pms-interface/src/main/java/com/atguigu/gmall/pms/entity/CategoryEntity.java
lvym-web/gmall-2020
3d7c1eff913435aae32ee917afa2d2d150fca506
[ "Apache-2.0" ]
null
null
null
20.194444
65
0.686382
1,003,417
package com.atguigu.gmall.pms.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 商品三级分类 * * @author lixianfeng * @email [email protected] * @date 2020-07-11 14:15:26 */ @ApiModel @Data @TableName("pms_category") public class CategoryEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 分类id */ @TableId @ApiModelProperty(name = "catId",value = "分类id") private Long catId; /** * 分类名称 */ @ApiModelProperty(name = "name",value = "分类名称") private String name; /** * 父分类id */ @ApiModelProperty(name = "parentCid",value = "父分类id") private Long parentCid; /** * 层级 */ @ApiModelProperty(name = "catLevel",value = "层级") private Integer catLevel; /** * 是否显示[0-不显示,1显示] */ @ApiModelProperty(name = "showStatus",value = "是否显示[0-不显示,1显示]") private Integer showStatus; /** * 排序 */ @ApiModelProperty(name = "sort",value = "排序") private Integer sort; /** * 图标地址 */ @ApiModelProperty(name = "icon",value = "图标地址") private String icon; /** * 计量单位 */ @ApiModelProperty(name = "productUnit",value = "计量单位") private String productUnit; /** * 商品数量 */ @ApiModelProperty(name = "productCount",value = "商品数量") private Integer productCount; }
924589bb50e8286c851f8668fb2ef5e74ffda6db
4,845
java
Java
viewstatecompiler/src/main/java/com/tommannson/viewstate/processor/model/StateBinding.java
TomMannson/ViewState
44ee7262883c850da30c01ccbe864830c20fe744
[ "Apache-2.0" ]
null
null
null
viewstatecompiler/src/main/java/com/tommannson/viewstate/processor/model/StateBinding.java
TomMannson/ViewState
44ee7262883c850da30c01ccbe864830c20fe744
[ "Apache-2.0" ]
null
null
null
viewstatecompiler/src/main/java/com/tommannson/viewstate/processor/model/StateBinding.java
TomMannson/ViewState
44ee7262883c850da30c01ccbe864830c20fe744
[ "Apache-2.0" ]
null
null
null
40.041322
116
0.611765
1,003,418
package com.tommannson.viewstate.processor.model; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; /** * Created by tomasz.krol on 2016-05-10. */ public class StateBinding { private static final String GENERATED_COMMENTS = "beta version "; private static final AnnotationSpec GENERATED = AnnotationSpec.builder(Generated.class) .addMember("value", "$S", StateBinding.class.getName()) .addMember("comments", "$S", GENERATED_COMMENTS) .build(); private static final ClassName CONTEXT = ClassName.get("android.content", "Context"); private static final ClassName PERSIST_FRAGMENT = ClassName.get("pl.tomaszkrol.viewstate", "PersisterFragment"); private static final ClassName FRAGMENT_ACTIVITY = ClassName.get("android.support.v4.app", "FragmentActivity"); public ClassName generetedClassName; public ClassName targetClassName; public List<VariableBinding> variables = new ArrayList<>(); public StateBinding(ClassName generetedClassName, ClassName targetClassName, boolean isActivity) { this.generetedClassName = generetedClassName; this.targetClassName = targetClassName; } public JavaFile generateJava() { TypeSpec.Builder result = TypeSpec.classBuilder(generetedClassName) .addAnnotation(GENERATED) .addModifiers(PUBLIC); result.addMethod(createPersistMethod()); result.addMethod(createRestoreMethod()); return JavaFile.builder(generetedClassName.packageName(), result.build()) .addFileComment("Generated code do not modify!") .build(); } private MethodSpec createPersistMethod() { MethodSpec.Builder result = MethodSpec.methodBuilder("persist") .addModifiers(PUBLIC) .addModifiers(STATIC) .addParameter(CONTEXT, "activityContext") .addParameter(targetClassName, "target") .addCode("if(!(activityContext instanceof $T)){\n" + " throw new RuntimeException(\"activityContext has to be FragmentActivity\");\n" + "}\n" + "else{\n", FRAGMENT_ACTIVITY) .addCode(" $T persistFragment = $T.injectPresistFragment(($T)activityContext);\n" , PERSIST_FRAGMENT, PERSIST_FRAGMENT, FRAGMENT_ACTIVITY); for (VariableBinding variable : variables) { String asignement = String.format(" persistFragment.saveData(\"$T_%s\", target.%s);\n", variable.fieldName, variable.fieldName); result.addCode(asignement, targetClassName); } result.addCode("}\n"); return result.build(); } private MethodSpec createRestoreMethod() { MethodSpec.Builder result = MethodSpec.methodBuilder("restore") .addModifiers(PUBLIC) .addModifiers(STATIC) .addParameter(CONTEXT, "activityContext") .addParameter(targetClassName, "target") .addCode("if(!(activityContext instanceof $T)){\n" + " throw new RuntimeException(\"activityContext has to be FragmentActivity\");\n" + "}\n" + "else{\n", FRAGMENT_ACTIVITY) .addCode(" $T persistFragment = $T.injectPresistFragment(($T)activityContext);\n" , PERSIST_FRAGMENT, PERSIST_FRAGMENT, FRAGMENT_ACTIVITY) .addCode(" Object holder = null;\n"); for (VariableBinding variable : variables) { String asignement = String.format(" holder = " + "persistFragment.loadData(\"$T_%s\");\n", variable.fieldName); result.addCode(asignement, targetClassName); if (variable.isPrimitive) { String ifStateMent = " if(holder != null){\n"; result.addCode(ifStateMent); } asignement = String.format("\t target.%s = (%s)" + "holder;\n", variable.fieldName, variable.fieldType); result.addCode(asignement, targetClassName); if (variable.isPrimitive) { String ifStateMent = " }\n"; result.addCode(ifStateMent); } } result.addCode("}\n"); return result.build(); } }
924589cdeedaaf3065d50789ccd7646799fd99ec
887
java
Java
src/test/Mapa_MerendaDAOTest.java
hugocatarino/Merenda
acf5d2ecf7c9f560fc6fe60e32032bd3d902259e
[ "MIT" ]
null
null
null
src/test/Mapa_MerendaDAOTest.java
hugocatarino/Merenda
acf5d2ecf7c9f560fc6fe60e32032bd3d902259e
[ "MIT" ]
null
null
null
src/test/Mapa_MerendaDAOTest.java
hugocatarino/Merenda
acf5d2ecf7c9f560fc6fe60e32032bd3d902259e
[ "MIT" ]
null
null
null
22.74359
96
0.7531
1,003,419
package test; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import dao.Mapa_MerendaDAO; import model.Mapa_Merenda; public class Mapa_MerendaDAOTest { private Mapa_Merenda mapa; private Mapa_MerendaDAO dao = new Mapa_MerendaDAO(); @Before public void setUp() { mapa = new Mapa_Merenda(); } @Test public void test1AdicionaMapa_Merenda() { mapa.setIdEstoque(1); mapa.setCardapio("Arroz com frango"); mapa.setTurno("Primeiro"); mapa.setNumero_Aluno(40); mapa.setDate("05/03/2016"); dao.adicionaMapa_Merenda(mapa); Assert.assertEquals(mapa.getIdMapa_Merenda(), dao.getLastMapa_Merenda().getIdMapa_Merenda()); } @Test public void test2RemoveMapa_Merenda() { int id = dao.getLastMapa_Merenda().getIdMapa_Merenda(); dao.removeMapa_Merenda(id); Assert.assertNotEquals(id, dao.getLastMapa_Merenda().getIdMapa_Merenda()); } }
92458cbdab531f9ae732f27b0a5b542551b54e04
1,129
java
Java
dashboard/src/test/java/org/consumersunion/stories/server/persistence/PersistersTestUtils.java
stori-es/stories
35f1186ca3a21bc41a1a99c2b1cad971d4c2de35
[ "Apache-2.0" ]
2
2016-06-02T22:29:19.000Z
2019-06-12T18:51:01.000Z
dashboard/src/test/java/org/consumersunion/stories/server/persistence/PersistersTestUtils.java
stori-es/stories
35f1186ca3a21bc41a1a99c2b1cad971d4c2de35
[ "Apache-2.0" ]
43
2016-04-05T19:01:50.000Z
2016-12-22T00:35:19.000Z
dashboard/src/test/java/org/consumersunion/stories/server/persistence/PersistersTestUtils.java
stori-es/stori_es
35f1186ca3a21bc41a1a99c2b1cad971d4c2de35
[ "Apache-2.0" ]
null
null
null
33.205882
108
0.584588
1,003,420
package org.consumersunion.stories.server.persistence; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.consumersunion.stories.common.shared.service.GeneralException; import org.consumersunion.stories.server.persistence.funcs.ProcessFunc; public class PersistersTestUtils { public static int getRootProfileIdForOrganization(int orgId) { return PersistenceUtil.process(new ProcessFunc<Integer, Integer>(orgId) { @Override public Integer process() { try { PreparedStatement select = conn.prepareStatement("SELECT id FROM profile WHERE user=0 AND organization=?"); select.setInt(1, input); ResultSet resultSet = select.executeQuery(); if (resultSet.next()) { return resultSet.getInt(1); } return null; } catch (SQLException e) { throw new GeneralException(e); } } }); } }
92458d001bda99e668e497ca763bab91afa4d07d
59,655
java
Java
proto-google-cloud-datacatalog-v1/src/main/java/com/google/cloud/datacatalog/v1/Datacatalog.java
suztomo/java-datacatalog
174406babb8355f81830cf8c0b5ea985bcf38300
[ "Apache-2.0" ]
7
2019-11-15T14:00:08.000Z
2021-12-17T09:35:55.000Z
proto-google-cloud-datacatalog-v1/src/main/java/com/google/cloud/datacatalog/v1/Datacatalog.java
suztomo/java-datacatalog
174406babb8355f81830cf8c0b5ea985bcf38300
[ "Apache-2.0" ]
548
2019-10-14T21:43:26.000Z
2022-03-30T19:09:00.000Z
proto-google-cloud-datacatalog-v1/src/main/java/com/google/cloud/datacatalog/v1/Datacatalog.java
suztomo/java-datacatalog
174406babb8355f81830cf8c0b5ea985bcf38300
[ "Apache-2.0" ]
21
2019-10-14T21:53:53.000Z
2022-01-29T08:15:16.000Z
63.665955
108
0.720694
1,003,421
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datacatalog/v1/datacatalog.proto package com.google.cloud.datacatalog.v1; public final class Datacatalog { private Datacatalog() {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_Scope_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_Scope_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_SearchCatalogResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_SearchCatalogResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_CreateEntryGroupRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_CreateEntryGroupRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_UpdateEntryGroupRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_UpdateEntryGroupRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_GetEntryGroupRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_GetEntryGroupRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_DeleteEntryGroupRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_DeleteEntryGroupRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_ListEntryGroupsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_ListEntryGroupsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_ListEntryGroupsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_ListEntryGroupsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_CreateEntryRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_CreateEntryRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_UpdateEntryRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_UpdateEntryRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_DeleteEntryRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_DeleteEntryRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_GetEntryRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_GetEntryRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_LookupEntryRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_LookupEntryRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_Entry_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_Entry_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_Entry_LabelsEntry_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_Entry_LabelsEntry_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_DatabaseTableSpec_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_DatabaseTableSpec_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_DataSourceConnectionSpec_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_DataSourceConnectionSpec_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_RoutineSpec_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_RoutineSpec_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_RoutineSpec_Argument_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_RoutineSpec_Argument_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_EntryGroup_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_EntryGroup_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_CreateTagTemplateRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_CreateTagTemplateRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_GetTagTemplateRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_GetTagTemplateRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_UpdateTagTemplateRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_UpdateTagTemplateRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_DeleteTagTemplateRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_DeleteTagTemplateRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_CreateTagRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_CreateTagRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_UpdateTagRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_UpdateTagRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_DeleteTagRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_DeleteTagRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_CreateTagTemplateFieldRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_CreateTagTemplateFieldRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_UpdateTagTemplateFieldRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_UpdateTagTemplateFieldRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_RenameTagTemplateFieldRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_RenameTagTemplateFieldRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_RenameTagTemplateFieldEnumValueRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_RenameTagTemplateFieldEnumValueRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_DeleteTagTemplateFieldRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_DeleteTagTemplateFieldRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_ListTagsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_ListTagsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_ListTagsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_ListTagsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_ListEntriesRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_ListEntriesRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_datacatalog_v1_ListEntriesResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_datacatalog_v1_ListEntriesResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n-google/cloud/datacatalog/v1/datacatalo" + "g.proto\022\033google.cloud.datacatalog.v1\032\034go" + "ogle/api/annotations.proto\032\027google/api/c" + "lient.proto\032\037google/api/field_behavior.p" + "roto\032\031google/api/resource.proto\032*google/" + "cloud/datacatalog/v1/bigquery.proto\032(goo" + "gle/cloud/datacatalog/v1/common.proto\032-g" + "oogle/cloud/datacatalog/v1/data_source.p" + "roto\0322google/cloud/datacatalog/v1/gcs_fi" + "leset_spec.proto\032(google/cloud/datacatal" + "og/v1/schema.proto\032(google/cloud/datacat" + "alog/v1/search.proto\032,google/cloud/datac" + "atalog/v1/table_spec.proto\032&google/cloud" + "/datacatalog/v1/tags.proto\032,google/cloud" + "/datacatalog/v1/timestamps.proto\032\'google" + "/cloud/datacatalog/v1/usage.proto\032\036googl" + "e/iam/v1/iam_policy.proto\032\032google/iam/v1" + "/policy.proto\032\033google/protobuf/empty.pro" + "to\032 google/protobuf/field_mask.proto\032\037go" + "ogle/protobuf/timestamp.proto\"\350\002\n\024Search" + "CatalogRequest\022K\n\005scope\030\006 \001(\01327.google.c" + "loud.datacatalog.v1.SearchCatalogRequest" + ".ScopeB\003\340A\002\022\022\n\005query\030\001 \001(\tB\003\340A\001\022\021\n\tpage_" + "size\030\002 \001(\005\022\027\n\npage_token\030\003 \001(\tB\003\340A\001\022\020\n\010o" + "rder_by\030\005 \001(\t\032\260\001\n\005Scope\022\027\n\017include_org_i" + "ds\030\002 \003(\t\022\033\n\023include_project_ids\030\003 \003(\t\022#\n" + "\033include_gcp_public_datasets\030\007 \001(\010\022!\n\024re" + "stricted_locations\030\020 \003(\tB\003\340A\001\022)\n\034include" + "_public_tag_templates\030\023 \001(\010B\003\340A\001\"\210\001\n\025Sea" + "rchCatalogResponse\022A\n\007results\030\001 \003(\01320.go" + "ogle.cloud.datacatalog.v1.SearchCatalogR" + "esult\022\027\n\017next_page_token\030\003 \001(\t\022\023\n\013unreac" + "hable\030\006 \003(\t\"\263\001\n\027CreateEntryGroupRequest\022" + "=\n\006parent\030\001 \001(\tB-\340A\002\372A\'\022%datacatalog.goo" + "gleapis.com/EntryGroup\022\033\n\016entry_group_id" + "\030\003 \001(\tB\003\340A\002\022<\n\013entry_group\030\002 \001(\0132\'.googl" + "e.cloud.datacatalog.v1.EntryGroup\"\215\001\n\027Up" + "dateEntryGroupRequest\022A\n\013entry_group\030\001 \001" + "(\0132\'.google.cloud.datacatalog.v1.EntryGr" + "oupB\003\340A\002\022/\n\013update_mask\030\002 \001(\0132\032.google.p" + "rotobuf.FieldMask\"\202\001\n\024GetEntryGroupReque" + "st\022;\n\004name\030\001 \001(\tB-\340A\002\372A\'\n%datacatalog.go" + "ogleapis.com/EntryGroup\022-\n\tread_mask\030\002 \001" + "(\0132\032.google.protobuf.FieldMask\"j\n\027Delete" + "EntryGroupRequest\022;\n\004name\030\001 \001(\tB-\340A\002\372A\'\n" + "%datacatalog.googleapis.com/EntryGroup\022\022" + "\n\005force\030\002 \001(\010B\003\340A\001\"\210\001\n\026ListEntryGroupsRe" + "quest\022=\n\006parent\030\001 \001(\tB-\340A\002\372A\'\n%datacatal" + "og.googleapis.com/EntryGroup\022\026\n\tpage_siz" + "e\030\002 \001(\005B\003\340A\001\022\027\n\npage_token\030\003 \001(\tB\003\340A\001\"q\n" + "\027ListEntryGroupsResponse\022=\n\014entry_groups" + "\030\001 \003(\0132\'.google.cloud.datacatalog.v1.Ent" + "ryGroup\022\027\n\017next_page_token\030\002 \001(\t\"\242\001\n\022Cre" + "ateEntryRequest\022=\n\006parent\030\001 \001(\tB-\340A\002\372A\'\n" + "%datacatalog.googleapis.com/EntryGroup\022\025" + "\n\010entry_id\030\003 \001(\tB\003\340A\002\0226\n\005entry\030\002 \001(\0132\".g" + "oogle.cloud.datacatalog.v1.EntryB\003\340A\002\"}\n" + "\022UpdateEntryRequest\0226\n\005entry\030\001 \001(\0132\".goo" + "gle.cloud.datacatalog.v1.EntryB\003\340A\002\022/\n\013u" + "pdate_mask\030\002 \001(\0132\032.google.protobuf.Field" + "Mask\"L\n\022DeleteEntryRequest\0226\n\004name\030\001 \001(\t" + "B(\340A\002\372A\"\n datacatalog.googleapis.com/Ent" + "ry\"I\n\017GetEntryRequest\0226\n\004name\030\001 \001(\tB(\340A\002" + "\372A\"\n datacatalog.googleapis.com/Entry\"v\n" + "\022LookupEntryRequest\022\031\n\017linked_resource\030\001" + " \001(\tH\000\022\026\n\014sql_resource\030\003 \001(\tH\000\022\036\n\024fully_" + "qualified_name\030\005 \001(\tH\000B\r\n\013target_name\"\366\n" + "\n\005Entry\022;\n\004name\030\001 \001(\tB-\340A\003\372A\'\n%datacatal" + "og.googleapis.com/EntryGroup\022\027\n\017linked_r" + "esource\030\t \001(\t\022\034\n\024fully_qualified_name\030\035 " + "\001(\t\0226\n\004type\030\002 \001(\0162&.google.cloud.datacat" + "alog.v1.EntryTypeH\000\022\035\n\023user_specified_ty" + "pe\030\020 \001(\tH\000\022O\n\021integrated_system\030\021 \001(\0162-." + "google.cloud.datacatalog.v1.IntegratedSy" + "stemB\003\340A\003H\001\022\037\n\025user_specified_system\030\022 \001" + "(\tH\001\022G\n\020gcs_fileset_spec\030\006 \001(\0132+.google." + "cloud.datacatalog.v1.GcsFilesetSpecH\002\022M\n" + "\023bigquery_table_spec\030\014 \001(\0132..google.clou" + "d.datacatalog.v1.BigQueryTableSpecH\002\022Z\n\032" + "bigquery_date_sharded_spec\030\017 \001(\01324.googl" + "e.cloud.datacatalog.v1.BigQueryDateShard" + "edSpecH\002\022M\n\023database_table_spec\030\030 \001(\0132.." + "google.cloud.datacatalog.v1.DatabaseTabl" + "eSpecH\003\022\\\n\033data_source_connection_spec\030\033" + " \001(\01325.google.cloud.datacatalog.v1.DataS" + "ourceConnectionSpecH\003\022@\n\014routine_spec\030\034 " + "\001(\0132(.google.cloud.datacatalog.v1.Routin" + "eSpecH\003\022\024\n\014display_name\030\003 \001(\t\022\023\n\013descrip" + "tion\030\004 \001(\t\0223\n\006schema\030\005 \001(\0132#.google.clou" + "d.datacatalog.v1.Schema\022O\n\030source_system" + "_timestamps\030\007 \001(\0132-.google.cloud.datacat" + "alog.v1.SystemTimestamps\022C\n\014usage_signal" + "\030\r \001(\0132(.google.cloud.datacatalog.v1.Usa" + "geSignalB\003\340A\003\022>\n\006labels\030\016 \003(\0132..google.c" + "loud.datacatalog.v1.Entry.LabelsEntry\022A\n" + "\013data_source\030\024 \001(\0132\'.google.cloud.dataca" + "talog.v1.DataSourceB\003\340A\003\032-\n\013LabelsEntry\022" + "\013\n\003key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001:x\352Au\n da" + "tacatalog.googleapis.com/Entry\022Qprojects" + "/{project}/locations/{location}/entryGro" + "ups/{entry_group}/entries/{entry}B\014\n\nent" + "ry_typeB\010\n\006systemB\013\n\ttype_specB\006\n\004spec\"\236" + "\001\n\021DatabaseTableSpec\022F\n\004type\030\001 \001(\01628.goo" + "gle.cloud.datacatalog.v1.DatabaseTableSp" + "ec.TableType\"A\n\tTableType\022\032\n\026TABLE_TYPE_" + "UNSPECIFIED\020\000\022\n\n\006NATIVE\020\001\022\014\n\010EXTERNAL\020\002\"" + "q\n\030DataSourceConnectionSpec\022U\n\030bigquery_" + "connection_spec\030\001 \001(\01323.google.cloud.dat" + "acatalog.v1.BigQueryConnectionSpec\"\303\004\n\013R" + "outineSpec\022J\n\014routine_type\030\001 \001(\01624.googl" + "e.cloud.datacatalog.v1.RoutineSpec.Routi" + "neType\022\020\n\010language\030\002 \001(\t\022L\n\021routine_argu" + "ments\030\003 \003(\01321.google.cloud.datacatalog.v" + "1.RoutineSpec.Argument\022\023\n\013return_type\030\004 " + "\001(\t\022\027\n\017definition_body\030\005 \001(\t\022Q\n\025bigquery" + "_routine_spec\030\006 \001(\01320.google.cloud.datac" + "atalog.v1.BigQueryRoutineSpecH\000\032\246\001\n\010Argu" + "ment\022\014\n\004name\030\001 \001(\t\022D\n\004mode\030\002 \001(\01626.googl" + "e.cloud.datacatalog.v1.RoutineSpec.Argum" + "ent.Mode\022\014\n\004type\030\003 \001(\t\"8\n\004Mode\022\024\n\020MODE_U" + "NSPECIFIED\020\000\022\006\n\002IN\020\001\022\007\n\003OUT\020\002\022\t\n\005INOUT\020\003" + "\"O\n\013RoutineType\022\034\n\030ROUTINE_TYPE_UNSPECIF" + "IED\020\000\022\023\n\017SCALAR_FUNCTION\020\001\022\r\n\tPROCEDURE\020" + "\002B\r\n\013system_spec\"\211\002\n\nEntryGroup\022\014\n\004name\030" + "\001 \001(\t\022\024\n\014display_name\030\002 \001(\t\022\023\n\013descripti" + "on\030\003 \001(\t\022S\n\027data_catalog_timestamps\030\004 \001(" + "\0132-.google.cloud.datacatalog.v1.SystemTi" + "mestampsB\003\340A\003:m\352Aj\n%datacatalog.googleap" + "is.com/EntryGroup\022Aprojects/{project}/lo" + "cations/{location}/entryGroups/{entry_gr" + "oup}\"\275\001\n\030CreateTagTemplateRequest\022>\n\006par" + "ent\030\001 \001(\tB.\340A\002\372A(\022&datacatalog.googleapi" + "s.com/TagTemplate\022\034\n\017tag_template_id\030\003 \001" + "(\tB\003\340A\002\022C\n\014tag_template\030\002 \001(\0132(.google.c" + "loud.datacatalog.v1.TagTemplateB\003\340A\002\"U\n\025" + "GetTagTemplateRequest\022<\n\004name\030\001 \001(\tB.\340A\002" + "\372A(\n&datacatalog.googleapis.com/TagTempl" + "ate\"\220\001\n\030UpdateTagTemplateRequest\022C\n\014tag_" + "template\030\001 \001(\0132(.google.cloud.datacatalo" + "g.v1.TagTemplateB\003\340A\002\022/\n\013update_mask\030\002 \001" + "(\0132\032.google.protobuf.FieldMask\"l\n\030Delete" + "TagTemplateRequest\022<\n\004name\030\001 \001(\tB.\340A\002\372A(" + "\n&datacatalog.googleapis.com/TagTemplate" + "\022\022\n\005force\030\002 \001(\010B\003\340A\002\"~\n\020CreateTagRequest" + "\0226\n\006parent\030\001 \001(\tB&\340A\002\372A \n\036datacatalog.go" + "ogleapis.com/Tag\0222\n\003tag\030\002 \001(\0132 .google.c" + "loud.datacatalog.v1.TagB\003\340A\002\"w\n\020UpdateTa" + "gRequest\0222\n\003tag\030\001 \001(\0132 .google.cloud.dat" + "acatalog.v1.TagB\003\340A\002\022/\n\013update_mask\030\002 \001(" + "\0132\032.google.protobuf.FieldMask\"H\n\020DeleteT" + "agRequest\0224\n\004name\030\001 \001(\tB&\340A\002\372A \022\036datacat" + "alog.googleapis.com/Tag\"\323\001\n\035CreateTagTem" + "plateFieldRequest\022>\n\006parent\030\001 \001(\tB.\340A\002\372A" + "(\n&datacatalog.googleapis.com/TagTemplat" + "e\022\"\n\025tag_template_field_id\030\002 \001(\tB\003\340A\002\022N\n" + "\022tag_template_field\030\003 \001(\0132-.google.cloud" + ".datacatalog.v1.TagTemplateFieldB\003\340A\002\"\350\001" + "\n\035UpdateTagTemplateFieldRequest\022A\n\004name\030" + "\001 \001(\tB3\340A\002\372A-\n+datacatalog.googleapis.co" + "m/TagTemplateField\022N\n\022tag_template_field" + "\030\002 \001(\0132-.google.cloud.datacatalog.v1.Tag" + "TemplateFieldB\003\340A\002\0224\n\013update_mask\030\003 \001(\0132" + "\032.google.protobuf.FieldMaskB\003\340A\001\"\212\001\n\035Ren" + "ameTagTemplateFieldRequest\022A\n\004name\030\001 \001(\t" + "B3\340A\002\372A-\n+datacatalog.googleapis.com/Tag" + "TemplateField\022&\n\031new_tag_template_field_" + "id\030\002 \001(\tB\003\340A\002\"\236\001\n&RenameTagTemplateField" + "EnumValueRequest\022J\n\004name\030\001 \001(\tB<\340A\002\372A6\n4" + "datacatalog.googleapis.com/TagTemplateFi" + "eldEnumValue\022(\n\033new_enum_value_display_n" + "ame\030\002 \001(\tB\003\340A\002\"v\n\035DeleteTagTemplateField" + "Request\022A\n\004name\030\001 \001(\tB3\340A\002\372A-\n+datacatal" + "og.googleapis.com/TagTemplateField\022\022\n\005fo" + "rce\030\002 \001(\010B\003\340A\002\"p\n\017ListTagsRequest\0226\n\006par" + "ent\030\001 \001(\tB&\340A\002\372A \022\036datacatalog.googleapi" + "s.com/Tag\022\021\n\tpage_size\030\002 \001(\005\022\022\n\npage_tok" + "en\030\003 \001(\t\"[\n\020ListTagsResponse\022.\n\004tags\030\001 \003" + "(\0132 .google.cloud.datacatalog.v1.Tag\022\027\n\017" + "next_page_token\030\002 \001(\t\"\251\001\n\022ListEntriesReq" + "uest\022=\n\006parent\030\001 \001(\tB-\340A\002\372A\'\n%datacatalo" + "g.googleapis.com/EntryGroup\022\021\n\tpage_size" + "\030\002 \001(\005\022\022\n\npage_token\030\003 \001(\t\022-\n\tread_mask\030" + "\004 \001(\0132\032.google.protobuf.FieldMask\"c\n\023Lis" + "tEntriesResponse\0223\n\007entries\030\001 \003(\0132\".goog" + "le.cloud.datacatalog.v1.Entry\022\027\n\017next_pa" + "ge_token\030\002 \001(\t*\254\001\n\tEntryType\022\032\n\026ENTRY_TY" + "PE_UNSPECIFIED\020\000\022\t\n\005TABLE\020\002\022\t\n\005MODEL\020\005\022\017" + "\n\013DATA_STREAM\020\003\022\013\n\007FILESET\020\004\022\013\n\007CLUSTER\020" + "\006\022\014\n\010DATABASE\020\007\022\032\n\026DATA_SOURCE_CONNECTIO" + "N\020\010\022\013\n\007ROUTINE\020\t\022\013\n\007SERVICE\020\0162\3021\n\013DataCa" + "talog\022\243\001\n\rSearchCatalog\0221.google.cloud.d" + "atacatalog.v1.SearchCatalogRequest\0322.goo" + "gle.cloud.datacatalog.v1.SearchCatalogRe" + "sponse\"+\202\323\344\223\002\027\"\022/v1/catalog:search:\001*\332A\013" + "scope,query\022\333\001\n\020CreateEntryGroup\0224.googl" + "e.cloud.datacatalog.v1.CreateEntryGroupR" + "equest\032\'.google.cloud.datacatalog.v1.Ent" + "ryGroup\"h\202\323\344\223\002>\"//v1/{parent=projects/*/" + "locations/*}/entryGroups:\013entry_group\332A!" + "parent,entry_group_id,entry_group\022\274\001\n\rGe" + "tEntryGroup\0221.google.cloud.datacatalog.v" + "1.GetEntryGroupRequest\032\'.google.cloud.da" + "tacatalog.v1.EntryGroup\"O\202\323\344\223\0021\022//v1/{na" + "me=projects/*/locations/*/entryGroups/*}" + "\332A\004name\332A\016name,read_mask\022\353\001\n\020UpdateEntry" + "Group\0224.google.cloud.datacatalog.v1.Upda" + "teEntryGroupRequest\032\'.google.cloud.datac" + "atalog.v1.EntryGroup\"x\202\323\344\223\002J2;/v1/{entry" + "_group.name=projects/*/locations/*/entry" + "Groups/*}:\013entry_group\332A\013entry_group\332A\027e" + "ntry_group,update_mask\022\240\001\n\020DeleteEntryGr" + "oup\0224.google.cloud.datacatalog.v1.Delete" + "EntryGroupRequest\032\026.google.protobuf.Empt" + "y\">\202\323\344\223\0021*//v1/{name=projects/*/location" + "s/*/entryGroups/*}\332A\004name\022\276\001\n\017ListEntryG" + "roups\0223.google.cloud.datacatalog.v1.List" + "EntryGroupsRequest\0324.google.cloud.dataca" + "talog.v1.ListEntryGroupsResponse\"@\202\323\344\223\0021" + "\022//v1/{parent=projects/*/locations/*}/en" + "tryGroups\332A\006parent\022\304\001\n\013CreateEntry\022/.goo" + "gle.cloud.datacatalog.v1.CreateEntryRequ" + "est\032\".google.cloud.datacatalog.v1.Entry\"" + "`\202\323\344\223\002B\"9/v1/{parent=projects/*/location" + "s/*/entryGroups/*}/entries:\005entry\332A\025pare" + "nt,entry_id,entry\022\316\001\n\013UpdateEntry\022/.goog" + "le.cloud.datacatalog.v1.UpdateEntryReque" + "st\032\".google.cloud.datacatalog.v1.Entry\"j" + "\202\323\344\223\002H2?/v1/{entry.name=projects/*/locat" + "ions/*/entryGroups/*/entries/*}:\005entry\332A" + "\005entry\332A\021entry,update_mask\022\240\001\n\013DeleteEnt" + "ry\022/.google.cloud.datacatalog.v1.DeleteE" + "ntryRequest\032\026.google.protobuf.Empty\"H\202\323\344" + "\223\002;*9/v1/{name=projects/*/locations/*/en" + "tryGroups/*/entries/*}\332A\004name\022\246\001\n\010GetEnt" + "ry\022,.google.cloud.datacatalog.v1.GetEntr" + "yRequest\032\".google.cloud.datacatalog.v1.E" + "ntry\"H\202\323\344\223\002;\0229/v1/{name=projects/*/locat" + "ions/*/entryGroups/*/entries/*}\332A\004name\022~" + "\n\013LookupEntry\022/.google.cloud.datacatalog" + ".v1.LookupEntryRequest\032\".google.cloud.da" + "tacatalog.v1.Entry\"\032\202\323\344\223\002\024\022\022/v1/entries:" + "lookup\022\274\001\n\013ListEntries\022/.google.cloud.da" + "tacatalog.v1.ListEntriesRequest\0320.google" + ".cloud.datacatalog.v1.ListEntriesRespons" + "e\"J\202\323\344\223\002;\0229/v1/{parent=projects/*/locati" + "ons/*/entryGroups/*}/entries\332A\006parent\022\342\001" + "\n\021CreateTagTemplate\0225.google.cloud.datac" + "atalog.v1.CreateTagTemplateRequest\032(.goo" + "gle.cloud.datacatalog.v1.TagTemplate\"l\202\323" + "\344\223\002@\"0/v1/{parent=projects/*/locations/*" + "}/tagTemplates:\014tag_template\332A#parent,ta" + "g_template_id,tag_template\022\257\001\n\016GetTagTem" + "plate\0222.google.cloud.datacatalog.v1.GetT" + "agTemplateRequest\032(.google.cloud.datacat" + "alog.v1.TagTemplate\"?\202\323\344\223\0022\0220/v1/{name=p" + "rojects/*/locations/*/tagTemplates/*}\332A\004" + "name\022\363\001\n\021UpdateTagTemplate\0225.google.clou" + "d.datacatalog.v1.UpdateTagTemplateReques" + "t\032(.google.cloud.datacatalog.v1.TagTempl" + "ate\"}\202\323\344\223\002M2=/v1/{tag_template.name=proj" + "ects/*/locations/*/tagTemplates/*}:\014tag_" + "template\332A\014tag_template\332A\030tag_template,u" + "pdate_mask\022\251\001\n\021DeleteTagTemplate\0225.googl" + "e.cloud.datacatalog.v1.DeleteTagTemplate" + "Request\032\026.google.protobuf.Empty\"E\202\323\344\223\0022*" + "0/v1/{name=projects/*/locations/*/tagTem" + "plates/*}\332A\nname,force\022\215\002\n\026CreateTagTemp" + "lateField\022:.google.cloud.datacatalog.v1." + "CreateTagTemplateFieldRequest\032-.google.c" + "loud.datacatalog.v1.TagTemplateField\"\207\001\202" + "\323\344\223\002O\"9/v1/{parent=projects/*/locations/" + "*/tagTemplates/*}/fields:\022tag_template_f" + "ield\332A/parent,tag_template_field_id,tag_" + "template_field\022\233\002\n\026UpdateTagTemplateFiel" + "d\022:.google.cloud.datacatalog.v1.UpdateTa" + "gTemplateFieldRequest\032-.google.cloud.dat" + "acatalog.v1.TagTemplateField\"\225\001\202\323\344\223\002O29/" + "v1/{name=projects/*/locations/*/tagTempl" + "ates/*/fields/*}:\022tag_template_field\332A\027n" + "ame,tag_template_field\332A#name,tag_templa" + "te_field,update_mask\022\361\001\n\026RenameTagTempla" + "teField\022:.google.cloud.datacatalog.v1.Re" + "nameTagTemplateFieldRequest\032-.google.clo" + "ud.datacatalog.v1.TagTemplateField\"l\202\323\344\223" + "\002E\"@/v1/{name=projects/*/locations/*/tag" + "Templates/*/fields/*}:rename:\001*\332A\036name,n" + "ew_tag_template_field_id\022\222\002\n\037RenameTagTe" + "mplateFieldEnumValue\022C.google.cloud.data" + "catalog.v1.RenameTagTemplateFieldEnumVal" + "ueRequest\032-.google.cloud.datacatalog.v1." + "TagTemplateField\"{\202\323\344\223\002R\"M/v1/{name=proj" + "ects/*/locations/*/tagTemplates/*/fields" + "/*/enumValues/*}:rename:\001*\332A name,new_en" + "um_value_display_name\022\274\001\n\026DeleteTagTempl" + "ateField\022:.google.cloud.datacatalog.v1.D" + "eleteTagTemplateFieldRequest\032\026.google.pr" + "otobuf.Empty\"N\202\323\344\223\002;*9/v1/{name=projects" + "/*/locations/*/tagTemplates/*/fields/*}\332" + "A\nname,force\022\371\001\n\tCreateTag\022-.google.clou" + "d.datacatalog.v1.CreateTagRequest\032 .goog" + "le.cloud.datacatalog.v1.Tag\"\232\001\202\323\344\223\002\206\001\"@/" + "v1/{parent=projects/*/locations/*/entryG" + "roups/*/entries/*}/tags:\003tagZ=\"6/v1/{par" + "ent=projects/*/locations/*/entryGroups/*" + "}/tags:\003tag\332A\nparent,tag\022\214\002\n\tUpdateTag\022-" + ".google.cloud.datacatalog.v1.UpdateTagRe" + "quest\032 .google.cloud.datacatalog.v1.Tag\"" + "\255\001\202\323\344\223\002\216\0012D/v1/{tag.name=projects/*/loca" + "tions/*/entryGroups/*/entries/*/tags/*}:" + "\003tagZA2:/v1/{tag.name=projects/*/locatio" + "ns/*/entryGroups/*/tags/*}:\003tag\332A\003tag\332A\017" + "tag,update_mask\022\336\001\n\tDeleteTag\022-.google.c" + "loud.datacatalog.v1.DeleteTagRequest\032\026.g" + "oogle.protobuf.Empty\"\211\001\202\323\344\223\002|*@/v1/{name" + "=projects/*/locations/*/entryGroups/*/en" + "tries/*/tags/*}Z8*6/v1/{name=projects/*/" + "locations/*/entryGroups/*/tags/*}\332A\004name" + "\022\365\001\n\010ListTags\022,.google.cloud.datacatalog" + ".v1.ListTagsRequest\032-.google.cloud.datac" + "atalog.v1.ListTagsResponse\"\213\001\202\323\344\223\002|\022@/v1" + "/{parent=projects/*/locations/*/entryGro" + "ups/*/entries/*}/tagsZ8\0226/v1/{parent=pro" + "jects/*/locations/*/entryGroups/*}/tags\332" + "A\006parent\022\362\001\n\014SetIamPolicy\022\".google.iam.v" + "1.SetIamPolicyRequest\032\025.google.iam.v1.Po" + "licy\"\246\001\202\323\344\223\002\215\001\"A/v1/{resource=projects/*" + "/locations/*/tagTemplates/*}:setIamPolic" + "y:\001*ZE\"@/v1/{resource=projects/*/locatio" + "ns/*/entryGroups/*}:setIamPolicy:\001*\332A\017re" + "source,policy\022\274\002\n\014GetIamPolicy\022\".google." + "iam.v1.GetIamPolicyRequest\032\025.google.iam." + "v1.Policy\"\360\001\202\323\344\223\002\336\001\"A/v1/{resource=proje" + "cts/*/locations/*/tagTemplates/*}:getIam" + "Policy:\001*ZE\"@/v1/{resource=projects/*/lo" + "cations/*/entryGroups/*}:getIamPolicy:\001*" + "ZO\"J/v1/{resource=projects/*/locations/*" + "/entryGroups/*/entries/*}:getIamPolicy:\001" + "*\332A\010resource\022\343\002\n\022TestIamPermissions\022(.go" + "ogle.iam.v1.TestIamPermissionsRequest\032)." + "google.iam.v1.TestIamPermissionsResponse" + "\"\367\001\202\323\344\223\002\360\001\"G/v1/{resource=projects/*/loc" + "ations/*/tagTemplates/*}:testIamPermissi" + "ons:\001*ZK\"F/v1/{resource=projects/*/locat" + "ions/*/entryGroups/*}:testIamPermissions" + ":\001*ZU\"P/v1/{resource=projects/*/location" + "s/*/entryGroups/*/entries/*}:testIamPerm" + "issions:\001*\032N\312A\032datacatalog.googleapis.co" + "m\322A.https://www.googleapis.com/auth/clou" + "d-platformB\217\003\n\037com.google.cloud.datacata" + "log.v1P\001ZFgoogle.golang.org/genproto/goo" + "gleapis/cloud/datacatalog/v1;datacatalog" + "\370\001\001\252\002\033Google.Cloud.DataCatalog.V1\312\002\033Goog" + "le\\Cloud\\DataCatalog\\V1\352\002\036Google::Cloud:" + ":DataCatalog::V1\352A\300\001\n4datacatalog.google" + "apis.com/TagTemplateFieldEnumValue\022\207\001pro" + "jects/{project}/locations/{location}/tag" + "Templates/{tag_template}/fields/{tag_tem" + "plate_field_id}/enumValues/{enum_value_d" + "isplay_name}b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.AnnotationsProto.getDescriptor(), com.google.api.ClientProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), com.google.api.ResourceProto.getDescriptor(), com.google.cloud.datacatalog.v1.BigQueryProto.getDescriptor(), com.google.cloud.datacatalog.v1.Common.getDescriptor(), com.google.cloud.datacatalog.v1.DataSourceProto.getDescriptor(), com.google.cloud.datacatalog.v1.GcsFilesetSpecOuterClass.getDescriptor(), com.google.cloud.datacatalog.v1.SchemaOuterClass.getDescriptor(), com.google.cloud.datacatalog.v1.Search.getDescriptor(), com.google.cloud.datacatalog.v1.TableSpecOuterClass.getDescriptor(), com.google.cloud.datacatalog.v1.Tags.getDescriptor(), com.google.cloud.datacatalog.v1.Timestamps.getDescriptor(), com.google.cloud.datacatalog.v1.Usage.getDescriptor(), com.google.iam.v1.IamPolicyProto.getDescriptor(), com.google.iam.v1.PolicyProto.getDescriptor(), com.google.protobuf.EmptyProto.getDescriptor(), com.google.protobuf.FieldMaskProto.getDescriptor(), com.google.protobuf.TimestampProto.getDescriptor(), }); internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_descriptor, new java.lang.String[] { "Scope", "Query", "PageSize", "PageToken", "OrderBy", }); internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_Scope_descriptor = internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_Scope_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_SearchCatalogRequest_Scope_descriptor, new java.lang.String[] { "IncludeOrgIds", "IncludeProjectIds", "IncludeGcpPublicDatasets", "RestrictedLocations", "IncludePublicTagTemplates", }); internal_static_google_cloud_datacatalog_v1_SearchCatalogResponse_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_cloud_datacatalog_v1_SearchCatalogResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_SearchCatalogResponse_descriptor, new java.lang.String[] { "Results", "NextPageToken", "Unreachable", }); internal_static_google_cloud_datacatalog_v1_CreateEntryGroupRequest_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_cloud_datacatalog_v1_CreateEntryGroupRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_CreateEntryGroupRequest_descriptor, new java.lang.String[] { "Parent", "EntryGroupId", "EntryGroup", }); internal_static_google_cloud_datacatalog_v1_UpdateEntryGroupRequest_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_cloud_datacatalog_v1_UpdateEntryGroupRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_UpdateEntryGroupRequest_descriptor, new java.lang.String[] { "EntryGroup", "UpdateMask", }); internal_static_google_cloud_datacatalog_v1_GetEntryGroupRequest_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_cloud_datacatalog_v1_GetEntryGroupRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_GetEntryGroupRequest_descriptor, new java.lang.String[] { "Name", "ReadMask", }); internal_static_google_cloud_datacatalog_v1_DeleteEntryGroupRequest_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_cloud_datacatalog_v1_DeleteEntryGroupRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_DeleteEntryGroupRequest_descriptor, new java.lang.String[] { "Name", "Force", }); internal_static_google_cloud_datacatalog_v1_ListEntryGroupsRequest_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_cloud_datacatalog_v1_ListEntryGroupsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_ListEntryGroupsRequest_descriptor, new java.lang.String[] { "Parent", "PageSize", "PageToken", }); internal_static_google_cloud_datacatalog_v1_ListEntryGroupsResponse_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_cloud_datacatalog_v1_ListEntryGroupsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_ListEntryGroupsResponse_descriptor, new java.lang.String[] { "EntryGroups", "NextPageToken", }); internal_static_google_cloud_datacatalog_v1_CreateEntryRequest_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_cloud_datacatalog_v1_CreateEntryRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_CreateEntryRequest_descriptor, new java.lang.String[] { "Parent", "EntryId", "Entry", }); internal_static_google_cloud_datacatalog_v1_UpdateEntryRequest_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_cloud_datacatalog_v1_UpdateEntryRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_UpdateEntryRequest_descriptor, new java.lang.String[] { "Entry", "UpdateMask", }); internal_static_google_cloud_datacatalog_v1_DeleteEntryRequest_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_cloud_datacatalog_v1_DeleteEntryRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_DeleteEntryRequest_descriptor, new java.lang.String[] { "Name", }); internal_static_google_cloud_datacatalog_v1_GetEntryRequest_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_google_cloud_datacatalog_v1_GetEntryRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_GetEntryRequest_descriptor, new java.lang.String[] { "Name", }); internal_static_google_cloud_datacatalog_v1_LookupEntryRequest_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_google_cloud_datacatalog_v1_LookupEntryRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_LookupEntryRequest_descriptor, new java.lang.String[] { "LinkedResource", "SqlResource", "FullyQualifiedName", "TargetName", }); internal_static_google_cloud_datacatalog_v1_Entry_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_google_cloud_datacatalog_v1_Entry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_Entry_descriptor, new java.lang.String[] { "Name", "LinkedResource", "FullyQualifiedName", "Type", "UserSpecifiedType", "IntegratedSystem", "UserSpecifiedSystem", "GcsFilesetSpec", "BigqueryTableSpec", "BigqueryDateShardedSpec", "DatabaseTableSpec", "DataSourceConnectionSpec", "RoutineSpec", "DisplayName", "Description", "Schema", "SourceSystemTimestamps", "UsageSignal", "Labels", "DataSource", "EntryType", "System", "TypeSpec", "Spec", }); internal_static_google_cloud_datacatalog_v1_Entry_LabelsEntry_descriptor = internal_static_google_cloud_datacatalog_v1_Entry_descriptor.getNestedTypes().get(0); internal_static_google_cloud_datacatalog_v1_Entry_LabelsEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_Entry_LabelsEntry_descriptor, new java.lang.String[] { "Key", "Value", }); internal_static_google_cloud_datacatalog_v1_DatabaseTableSpec_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_google_cloud_datacatalog_v1_DatabaseTableSpec_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_DatabaseTableSpec_descriptor, new java.lang.String[] { "Type", }); internal_static_google_cloud_datacatalog_v1_DataSourceConnectionSpec_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_google_cloud_datacatalog_v1_DataSourceConnectionSpec_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_DataSourceConnectionSpec_descriptor, new java.lang.String[] { "BigqueryConnectionSpec", }); internal_static_google_cloud_datacatalog_v1_RoutineSpec_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_google_cloud_datacatalog_v1_RoutineSpec_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_RoutineSpec_descriptor, new java.lang.String[] { "RoutineType", "Language", "RoutineArguments", "ReturnType", "DefinitionBody", "BigqueryRoutineSpec", "SystemSpec", }); internal_static_google_cloud_datacatalog_v1_RoutineSpec_Argument_descriptor = internal_static_google_cloud_datacatalog_v1_RoutineSpec_descriptor.getNestedTypes().get(0); internal_static_google_cloud_datacatalog_v1_RoutineSpec_Argument_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_RoutineSpec_Argument_descriptor, new java.lang.String[] { "Name", "Mode", "Type", }); internal_static_google_cloud_datacatalog_v1_EntryGroup_descriptor = getDescriptor().getMessageTypes().get(17); internal_static_google_cloud_datacatalog_v1_EntryGroup_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_EntryGroup_descriptor, new java.lang.String[] { "Name", "DisplayName", "Description", "DataCatalogTimestamps", }); internal_static_google_cloud_datacatalog_v1_CreateTagTemplateRequest_descriptor = getDescriptor().getMessageTypes().get(18); internal_static_google_cloud_datacatalog_v1_CreateTagTemplateRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_CreateTagTemplateRequest_descriptor, new java.lang.String[] { "Parent", "TagTemplateId", "TagTemplate", }); internal_static_google_cloud_datacatalog_v1_GetTagTemplateRequest_descriptor = getDescriptor().getMessageTypes().get(19); internal_static_google_cloud_datacatalog_v1_GetTagTemplateRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_GetTagTemplateRequest_descriptor, new java.lang.String[] { "Name", }); internal_static_google_cloud_datacatalog_v1_UpdateTagTemplateRequest_descriptor = getDescriptor().getMessageTypes().get(20); internal_static_google_cloud_datacatalog_v1_UpdateTagTemplateRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_UpdateTagTemplateRequest_descriptor, new java.lang.String[] { "TagTemplate", "UpdateMask", }); internal_static_google_cloud_datacatalog_v1_DeleteTagTemplateRequest_descriptor = getDescriptor().getMessageTypes().get(21); internal_static_google_cloud_datacatalog_v1_DeleteTagTemplateRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_DeleteTagTemplateRequest_descriptor, new java.lang.String[] { "Name", "Force", }); internal_static_google_cloud_datacatalog_v1_CreateTagRequest_descriptor = getDescriptor().getMessageTypes().get(22); internal_static_google_cloud_datacatalog_v1_CreateTagRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_CreateTagRequest_descriptor, new java.lang.String[] { "Parent", "Tag", }); internal_static_google_cloud_datacatalog_v1_UpdateTagRequest_descriptor = getDescriptor().getMessageTypes().get(23); internal_static_google_cloud_datacatalog_v1_UpdateTagRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_UpdateTagRequest_descriptor, new java.lang.String[] { "Tag", "UpdateMask", }); internal_static_google_cloud_datacatalog_v1_DeleteTagRequest_descriptor = getDescriptor().getMessageTypes().get(24); internal_static_google_cloud_datacatalog_v1_DeleteTagRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_DeleteTagRequest_descriptor, new java.lang.String[] { "Name", }); internal_static_google_cloud_datacatalog_v1_CreateTagTemplateFieldRequest_descriptor = getDescriptor().getMessageTypes().get(25); internal_static_google_cloud_datacatalog_v1_CreateTagTemplateFieldRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_CreateTagTemplateFieldRequest_descriptor, new java.lang.String[] { "Parent", "TagTemplateFieldId", "TagTemplateField", }); internal_static_google_cloud_datacatalog_v1_UpdateTagTemplateFieldRequest_descriptor = getDescriptor().getMessageTypes().get(26); internal_static_google_cloud_datacatalog_v1_UpdateTagTemplateFieldRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_UpdateTagTemplateFieldRequest_descriptor, new java.lang.String[] { "Name", "TagTemplateField", "UpdateMask", }); internal_static_google_cloud_datacatalog_v1_RenameTagTemplateFieldRequest_descriptor = getDescriptor().getMessageTypes().get(27); internal_static_google_cloud_datacatalog_v1_RenameTagTemplateFieldRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_RenameTagTemplateFieldRequest_descriptor, new java.lang.String[] { "Name", "NewTagTemplateFieldId", }); internal_static_google_cloud_datacatalog_v1_RenameTagTemplateFieldEnumValueRequest_descriptor = getDescriptor().getMessageTypes().get(28); internal_static_google_cloud_datacatalog_v1_RenameTagTemplateFieldEnumValueRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_RenameTagTemplateFieldEnumValueRequest_descriptor, new java.lang.String[] { "Name", "NewEnumValueDisplayName", }); internal_static_google_cloud_datacatalog_v1_DeleteTagTemplateFieldRequest_descriptor = getDescriptor().getMessageTypes().get(29); internal_static_google_cloud_datacatalog_v1_DeleteTagTemplateFieldRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_DeleteTagTemplateFieldRequest_descriptor, new java.lang.String[] { "Name", "Force", }); internal_static_google_cloud_datacatalog_v1_ListTagsRequest_descriptor = getDescriptor().getMessageTypes().get(30); internal_static_google_cloud_datacatalog_v1_ListTagsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_ListTagsRequest_descriptor, new java.lang.String[] { "Parent", "PageSize", "PageToken", }); internal_static_google_cloud_datacatalog_v1_ListTagsResponse_descriptor = getDescriptor().getMessageTypes().get(31); internal_static_google_cloud_datacatalog_v1_ListTagsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_ListTagsResponse_descriptor, new java.lang.String[] { "Tags", "NextPageToken", }); internal_static_google_cloud_datacatalog_v1_ListEntriesRequest_descriptor = getDescriptor().getMessageTypes().get(32); internal_static_google_cloud_datacatalog_v1_ListEntriesRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_ListEntriesRequest_descriptor, new java.lang.String[] { "Parent", "PageSize", "PageToken", "ReadMask", }); internal_static_google_cloud_datacatalog_v1_ListEntriesResponse_descriptor = getDescriptor().getMessageTypes().get(33); internal_static_google_cloud_datacatalog_v1_ListEntriesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_datacatalog_v1_ListEntriesResponse_descriptor, new java.lang.String[] { "Entries", "NextPageToken", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.ClientProto.defaultHost); registry.add(com.google.api.FieldBehaviorProto.fieldBehavior); registry.add(com.google.api.AnnotationsProto.http); registry.add(com.google.api.ClientProto.methodSignature); registry.add(com.google.api.ClientProto.oauthScopes); registry.add(com.google.api.ResourceProto.resource); registry.add(com.google.api.ResourceProto.resourceDefinition); registry.add(com.google.api.ResourceProto.resourceReference); com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor( descriptor, registry); com.google.api.AnnotationsProto.getDescriptor(); com.google.api.ClientProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); com.google.api.ResourceProto.getDescriptor(); com.google.cloud.datacatalog.v1.BigQueryProto.getDescriptor(); com.google.cloud.datacatalog.v1.Common.getDescriptor(); com.google.cloud.datacatalog.v1.DataSourceProto.getDescriptor(); com.google.cloud.datacatalog.v1.GcsFilesetSpecOuterClass.getDescriptor(); com.google.cloud.datacatalog.v1.SchemaOuterClass.getDescriptor(); com.google.cloud.datacatalog.v1.Search.getDescriptor(); com.google.cloud.datacatalog.v1.TableSpecOuterClass.getDescriptor(); com.google.cloud.datacatalog.v1.Tags.getDescriptor(); com.google.cloud.datacatalog.v1.Timestamps.getDescriptor(); com.google.cloud.datacatalog.v1.Usage.getDescriptor(); com.google.iam.v1.IamPolicyProto.getDescriptor(); com.google.iam.v1.PolicyProto.getDescriptor(); com.google.protobuf.EmptyProto.getDescriptor(); com.google.protobuf.FieldMaskProto.getDescriptor(); com.google.protobuf.TimestampProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
92458d55243855f0faefb397e91a81f03e65afb2
952
java
Java
appengine/src/main/java/org/retrostore/RetroStoreServlet.java
shaeberling/retrostore
b5d4f44b9bee3a2bea5ecbf0a7d24ce55cd8cc45
[ "Apache-2.0" ]
7
2016-10-21T06:33:41.000Z
2021-03-02T06:48:34.000Z
appengine/src/main/java/org/retrostore/RetroStoreServlet.java
shaeberling/retrostore
b5d4f44b9bee3a2bea5ecbf0a7d24ce55cd8cc45
[ "Apache-2.0" ]
9
2018-06-18T16:40:02.000Z
2018-11-21T06:52:41.000Z
appengine/src/main/java/org/retrostore/RetroStoreServlet.java
shaeberling/retrostore
b5d4f44b9bee3a2bea5ecbf0a7d24ce55cd8cc45
[ "Apache-2.0" ]
2
2018-03-09T17:08:55.000Z
2019-05-03T07:55:28.000Z
29.75
94
0.747899
1,003,422
/* * Copyright 2016, Sascha Häberling * * 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.retrostore; import org.retrostore.data.Register; import javax.servlet.http.HttpServlet; /** * Common servlet class for all RetroStor servlets. Ensures that all required data classes are * registered with Objectify. */ public abstract class RetroStoreServlet extends HttpServlet { static { Register.ensureRegistered(); } }
92458d5c703a964b792da5abbae9da144815fb96
442
java
Java
org.spoofax.jsglr2/src/main/java/org/spoofax/jsglr2/imploder/incremental/IncrementalImplodeInput.java
pmisteliac/jsglr
61c300c5704e65d7d26346f82c4d2b938a0eef95
[ "Apache-2.0" ]
7
2015-03-04T19:04:58.000Z
2021-06-05T07:40:30.000Z
org.spoofax.jsglr2/src/main/java/org/spoofax/jsglr2/imploder/incremental/IncrementalImplodeInput.java
pmisteliac/jsglr
61c300c5704e65d7d26346f82c4d2b938a0eef95
[ "Apache-2.0" ]
20
2017-09-14T13:15:52.000Z
2022-01-07T14:59:40.000Z
org.spoofax.jsglr2/src/main/java/org/spoofax/jsglr2/imploder/incremental/IncrementalImplodeInput.java
pmisteliac/jsglr
61c300c5704e65d7d26346f82c4d2b938a0eef95
[ "Apache-2.0" ]
8
2015-03-04T19:05:13.000Z
2021-05-21T09:52:55.000Z
27.625
108
0.766968
1,003,423
package org.spoofax.jsglr2.imploder.incremental; import org.spoofax.jsglr2.imploder.input.ImplodeInput; import org.spoofax.jsglr2.parseforest.IParseNode; public class IncrementalImplodeInput<ParseNode extends IParseNode<?, ?>, Cache, Tree> extends ImplodeInput { final Cache resultCache; IncrementalImplodeInput(String inputString, Cache resultCache) { super(inputString); this.resultCache = resultCache; } }
92458d71ee9b0d3557f14cf510f8861696068b33
5,416
java
Java
src/main/java/nomble/MSPal/Commands/Impl/SectionLog.java
Nimbleguy/MSPal
d45dd0ca89024dee530433f5a3ce9905d4788e36
[ "MIT" ]
2
2016-08-26T03:09:28.000Z
2017-06-03T03:08:26.000Z
src/main/java/nomble/MSPal/Commands/Impl/SectionLog.java
Nimbleguy/MSPal
d45dd0ca89024dee530433f5a3ce9905d4788e36
[ "MIT" ]
null
null
null
src/main/java/nomble/MSPal/Commands/Impl/SectionLog.java
Nimbleguy/MSPal
d45dd0ca89024dee530433f5a3ce9905d4788e36
[ "MIT" ]
2
2017-12-31T18:35:46.000Z
2018-01-10T03:24:37.000Z
34.496815
272
0.6274
1,003,424
package nomble.MSPal.Commands.Impl; import java.util.List; import java.util.Random; import nomble.MSPal.Core.Bot; import nomble.MSPal.Core.Util; import nomble.MSPal.Commands.EnumSection; import nomble.MSPal.Commands.ISection; import nomble.MSPal.Data.Impl.DataLog; import nomble.MSPal.Data.Impl.DataLog.EnumResults; import nomble.MSPal.Data.Impl.DataConsent; import sx.blah.discord.api.events.EventSubscriber; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IPrivateChannel; import sx.blah.discord.handle.obj.Permissions; import sx.blah.discord.handle.impl.events.guild.channel.message.*; import sx.blah.discord.util.*; public class SectionLog implements ISection{ private Bot main; public SectionLog(Bot m){ load(); main = m; } @EventSubscriber public void onMessage(MessageReceivedEvent e){ if(e.getAuthor().isBot()){ return; } long l = -1; if(!(e.getChannel() instanceof IPrivateChannel)){ l = e.getMessage().getGuild().getLongID(); } List<String[]> sl = Util.getCommand(e.getMessage().getContent(), l); IChannel ic = e.getChannel(); int lim = 0; for(String[] sa : sl){ if(lim++ > Util.getCmdLimit()){ break; } String c = sa[0].replaceFirst("^" + Util.getPrefix(l), "").replaceFirst(Util.getSuffix(l) + "$", ""); if(c.equals("logbet") && sa.length >= 3){ new Thread(() -> { try{ MessageHistory mh = ic.getMessageHistoryIn(Long.valueOf(sa[2]), Long.valueOf(sa[1]), 5000); String s = log(mh, "CHANNEL " + ic.getName(), ic.getLongID(), sa[1] + " TO " + sa[2], e.getAuthor().getPermissionsForGuild(e.getMessage().getGuild()).contains(Permissions.MANAGE_MESSAGES)); String p = main.upload(ic.getName() + " Log", s); RequestBuffer.request(() -> { ic.sendMessage(p); }); } catch(NumberFormatException nfe){ RequestBuffer.request(() -> { ic.sendMessage("Invalid message ids: must be numbers."); }); } }).start(); } else if(c.equals("lognote") && sa.length >= 3){ DataLog dl = main.getData(DataLog.class); long li; int n; switch(sa[1]){ case "create": Random r = new Random(); while(dl.getFreeIndex(li = r.nextLong()) != 0); dl.addNote(li, e.getMessage()); final long lif = li; RequestBuffer.request(() -> { e.getAuthor().getOrCreatePMChannel().sendMessage("Your note id is " + lif + "."); }); break; case "get": li = Long.valueOf(sa[2]); n = dl.getFreeIndex(li); StringBuilder sb = new StringBuilder(); for(short i = 0; i < n; i++){ String[] s = dl.getLog(li, i); String u = s[EnumResults.USR.ordinal()]; String t = s[EnumResults.TIME.ordinal()]; String m = s[EnumResults.MSG.ordinal()]; sb.append(u + " (" + t + " UTC): " + m + "\n"); } String p = main.upload(e.getAuthor().getName() + " Notes", sb.toString()); RequestBuffer.request(() -> { ic.sendMessage(p); }); break; default: li = Long.valueOf(sa[1]); if(!dl.addNote(li, e.getMessage())){ RequestBuffer.request(() -> { ic.sendMessage("There are too many messages in that log."); }); } break; } } } } @Override public String[][] getInfo(long l){ return new String[][] {{"logbet", "Log between two messages. Takes two message ids as arguments. Limited to 5000 messages in one go."}, {"lognote", "Take notes down to recall later. Takes two arguments: a note id and a message. If you don't have a note id, you will be given one by using " + "`create` instead of the id. As an example: `" + Util.getPrefix(l) + "lognote" + Util.getSuffix(l) + " create this is the first message` " + "to get a note id for a note with the text `this is my message`. To add more to the note, you may do this: " + "`" + Util.getPrefix(l) + "lognote" + Util.getSuffix(l) + " [your note id] this will be added to my message`. " + "to get the note contents, just execute `" + Util.getPrefix(l) + "lognote" + Util.getSuffix(l) + " get [your note id]`. " + "Notes are limited to 256 messages and expire after a week."}}; } @Override public String[] desc(){ return new String[] {"scroll", EnumSection.LOG.toString(), "Document channel histories.", ":scroll:", "By using these commands in a channel, you expressly agree to the collection of channel ids and names for publication in the logs." + "To be logged, you must explicitly opt-in to information collection (stores username, user ids, messages, and timestamp depending on the command) or the logger must have the \"Manage Messages\" permission. The command for that is located in the Bot Commands section."}; } @Override public void load(){} private String log(MessageHistory mh, String n, long i, String o, boolean b){ StringBuilder sb = new StringBuilder(); sb.append("\n------- END " + n.toUpperCase() + " LOG -------"); for(IMessage m : mh){ if(main.getData(DataConsent.class).getConsent(m.getAuthor().getLongID()) || b){ String ts = m.getTimestamp().toString(); sb.insert(0, "\n" + m.getAuthor().getName() + " (" + ts + " UTC): " + m.getContent()); } } sb.insert(0, "------- BEGIN LOG OF " + n.toUpperCase() + " (" + i + "): " + o + " -------"); return sb.toString(); } }
92458dc0e4de9d2ce943632739ab234dd57c2161
2,948
java
Java
src/main/java/com/hugman/culinaire/objects/screen/KettleScreen.java
Maxbrick/Culinaire
18a0f4f48991c37e3d57869f36c36df64c59c5c0
[ "MIT" ]
10
2021-07-07T09:12:19.000Z
2022-03-10T07:47:38.000Z
src/main/java/com/hugman/culinaire/objects/screen/KettleScreen.java
Maxbrick/Culinaire
18a0f4f48991c37e3d57869f36c36df64c59c5c0
[ "MIT" ]
23
2021-06-28T18:50:54.000Z
2022-03-23T07:04:45.000Z
src/main/java/com/hugman/culinaire/objects/screen/KettleScreen.java
Maxbrick/Culinaire
18a0f4f48991c37e3d57869f36c36df64c59c5c0
[ "MIT" ]
5
2021-08-13T19:11:32.000Z
2022-03-16T04:25:21.000Z
36.395062
102
0.713026
1,003,425
package com.hugman.culinaire.objects.screen; import com.hugman.culinaire.Culinaire; import com.hugman.culinaire.objects.screen.handler.KettleScreenHandler; import com.mojang.blaze3d.systems.RenderSystem; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.gui.screen.ingame.HandledScreen; import net.minecraft.client.render.GameRenderer; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.text.Text; import net.minecraft.util.Identifier; @Environment(EnvType.CLIENT) public class KettleScreen extends HandledScreen<KettleScreenHandler> { private static final Identifier TEXTURE = Culinaire.MOD_DATA.id("textures/gui/container/kettle.png"); public KettleScreen(KettleScreenHandler handler, PlayerInventory inventory, Text title) { super(handler, inventory, title); } @Override protected void init() { super.init(); this.titleX = (this.backgroundWidth - this.textRenderer.getWidth(this.title)) / 2; } @Override public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) { this.renderBackground(matrices); super.render(matrices, mouseX, mouseY, delta); this.drawMouseoverTooltip(matrices, mouseX, mouseY); } @Override protected void drawBackground(MatrixStack matrices, float delta, int mouseX, int mouseY) { RenderSystem.setShader(GameRenderer::getPositionTexShader); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.setShaderTexture(0, TEXTURE); int brewTime = this.handler.getBrewTime(); int totalBrewTime = this.handler.getTotalBrewTime(); int fluidLevel = this.handler.getFluidLevel(); int fluid = this.handler.getFluid(); boolean isHot = this.handler.isHot(); int i = (this.width - this.backgroundWidth) / 2; int j = (this.height - this.backgroundHeight) / 2; this.drawTexture(matrices, i, j, 0, 0, this.backgroundWidth, this.backgroundHeight); if(brewTime > 0) { int brewBarHeight = (int) (27.0F * (1.0F - (float) brewTime / totalBrewTime)); if(brewBarHeight > 0) { this.drawTexture(matrices, i + 99, j + 17, 222, 0, 7, brewBarHeight); } } if(fluid == 0) { this.drawTexture(matrices, i + 65, j + 48, 176, 0, 46, 16); } else { if(fluidLevel > 0) { int teaColor; if(fluid == 2) { teaColor = this.handler.getTeaColor(); } else { teaColor = 3694022; } float red = (float) (teaColor >> 16 & 255) / 255.0F; float green = (float) (teaColor >> 8 & 255) / 255.0F; float blue = (float) (teaColor & 255) / 255.0F; RenderSystem.setShaderColor(red, green, blue, 1.0F); int fluidHeight = (int) (12.0F * (float) fluidLevel / 3.0F) + 4; this.drawTexture(matrices, i + 65, j + 64 - fluidHeight, 176, 16, 46, fluidHeight); } } RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); if(isHot) { this.drawTexture(matrices, i + 76, j + 68, 176, 32, 24, 9); } } }
92458e89f0acab50dc782e3622100cff6e3e76db
273
java
Java
src/main/java/cn/com/xuxiaowei/service/ITestQqService.java
xuxiaowei-com-cn/Spring-Boot-Sharding-JDBC
95c56563e1507715a5126529c24709e388cb5722
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/com/xuxiaowei/service/ITestQqService.java
xuxiaowei-com-cn/Spring-Boot-Sharding-JDBC
95c56563e1507715a5126529c24709e388cb5722
[ "Apache-2.0" ]
5
2020-04-27T17:13:41.000Z
2020-04-28T03:52:13.000Z
src/main/java/cn/com/xuxiaowei/service/ITestQqService.java
xuxiaowei-com-cn/Spring-Boot-Sharding-JDBC
95c56563e1507715a5126529c24709e388cb5722
[ "Apache-2.0" ]
null
null
null
16.058824
59
0.714286
1,003,426
package cn.com.xuxiaowei.service; import cn.com.xuxiaowei.entity.TestQq; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 测试QQ号表 服务类 * </p> * * @author 徐晓伟 * @since 2020-04-28 */ public interface ITestQqService extends IService<TestQq> { }
92458ed48fbf9515f70ff93790aca6e3f5ac4dad
1,043
java
Java
wink-itests/wink-itest/wink-itest-targeting/src/main/java/org/apache/wink/itest/transferencoding/ChunkedMirror.java
berezovskyi/apache-wink
bafd9208fa87e6433254282d452a7f6e768f1bbb
[ "Apache-2.0" ]
11
2015-05-05T03:56:42.000Z
2021-11-10T16:17:15.000Z
wink-itests/wink-itest/wink-itest-targeting/src/main/java/org/apache/wink/itest/transferencoding/ChunkedMirror.java
AgreePro/wink
bafd9208fa87e6433254282d452a7f6e768f1bbb
[ "Apache-2.0" ]
2
2015-10-23T21:55:46.000Z
2016-03-09T23:15:02.000Z
wink-itests/wink-itest/wink-itest-targeting/src/main/java/org/apache/wink/itest/transferencoding/ChunkedMirror.java
AgreePro/wink
bafd9208fa87e6433254282d452a7f6e768f1bbb
[ "Apache-2.0" ]
16
2015-10-20T17:38:27.000Z
2021-11-10T16:17:08.000Z
31.606061
63
0.732502
1,003,427
/* * 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.wink.itest.transferencoding; import javax.ws.rs.POST; import javax.ws.rs.Path; @Path("/chunkedbook") public class ChunkedMirror { @POST public byte[] postSomething(byte[] b) { return b; } }
924590640a36547a9723a77e103ec17a2e1cf345
116
java
Java
src/main/java/cambio/simulator/parsing/package-info.java
ittaq/resilience-simulator
fe70b73637c59fb72e8ba0ab1ee2893ffa807332
[ "Apache-2.0" ]
null
null
null
src/main/java/cambio/simulator/parsing/package-info.java
ittaq/resilience-simulator
fe70b73637c59fb72e8ba0ab1ee2893ffa807332
[ "Apache-2.0" ]
21
2021-07-23T17:52:51.000Z
2022-03-19T19:31:39.000Z
src/main/java/cambio/simulator/parsing/package-info.java
ittaq/resilience-simulator
fe70b73637c59fb72e8ba0ab1ee2893ffa807332
[ "Apache-2.0" ]
1
2020-02-09T15:33:50.000Z
2020-02-09T15:33:50.000Z
23.2
73
0.775862
1,003,428
/** * Revolves around parsing architecture and experiment data into objects. */ package cambio.simulator.parsing;
9245918e3aa77a860343ee8bf80b4fa8af089c5d
677
java
Java
BASCore/src/main/java/com/photo/bas/core/model/common/SalutationType.java
yufeng1982/PGMS
c05e9ce62c2706632a4e0723e94150e575bef0ac
[ "MIT" ]
null
null
null
BASCore/src/main/java/com/photo/bas/core/model/common/SalutationType.java
yufeng1982/PGMS
c05e9ce62c2706632a4e0723e94150e575bef0ac
[ "MIT" ]
4
2019-11-14T13:09:23.000Z
2022-01-21T23:25:58.000Z
BASCore/src/main/java/com/photo/bas/core/model/common/SalutationType.java
yufeng1982/PGMS
c05e9ce62c2706632a4e0723e94150e575bef0ac
[ "MIT" ]
null
null
null
16.925
80
0.704579
1,003,429
/** * */ package com.photo.bas.core.model.common; import java.util.EnumSet; import com.photo.bas.core.model.entity.IEnum; import com.photo.bas.core.utils.ResourceUtils; /** * @author FengYu * */ public enum SalutationType implements IEnum { Dr, Miss, Mr, Mrs, Ms; SalutationType(){} public static EnumSet<SalutationType> getSalutationTypes() { return EnumSet.allOf(SalutationType.class); } @Override public String getKey() { return new StringBuffer().append("SalutationType.").append(name()).toString(); } @Override public String getText() { return ResourceUtils.getText(getKey()); } @Override public String getName() { return name(); } }
924591dc6f19fee43d69326669ca0970918c3b9e
1,656
java
Java
sdk/streamanalytics/mgmt-v2020_03_01_preview/src/main/java/com/microsoft/azure/management/streamanalytics/v2020_03_01_preview/StreamInputProperties.java
han-gao/azure-sdk-for-java
b2fed4662f860e0f7cc7f9f7166b30876bce8328
[ "MIT" ]
3
2021-09-15T16:25:19.000Z
2021-12-17T05:41:00.000Z
sdk/streamanalytics/mgmt-v2020_03_01_preview/src/main/java/com/microsoft/azure/management/streamanalytics/v2020_03_01_preview/StreamInputProperties.java
smooth80stech/azure-sdk-for-java
f9d62f8efd6ad4a7f9577abff5851b8bb43a7627
[ "MIT" ]
12
2019-07-17T16:18:54.000Z
2019-07-17T21:30:02.000Z
sdk/streamanalytics/mgmt-v2020_03_01_preview/src/main/java/com/microsoft/azure/management/streamanalytics/v2020_03_01_preview/StreamInputProperties.java
smooth80stech/azure-sdk-for-java
f9d62f8efd6ad4a7f9577abff5851b8bb43a7627
[ "MIT" ]
1
2020-12-24T04:02:44.000Z
2020-12-24T04:02:44.000Z
33.795918
139
0.731884
1,003,430
/** * 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.streamanalytics.v2020_03_01_preview; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * The properties that are associated with an input containing stream data. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = StreamInputProperties.class) @JsonTypeName("Stream") public class StreamInputProperties extends InputProperties { /** * Describes an input data source that contains stream data. Required on * PUT (CreateOrReplace) requests. */ @JsonProperty(value = "datasource") private StreamInputDataSource datasource; /** * Get describes an input data source that contains stream data. Required on PUT (CreateOrReplace) requests. * * @return the datasource value */ public StreamInputDataSource datasource() { return this.datasource; } /** * Set describes an input data source that contains stream data. Required on PUT (CreateOrReplace) requests. * * @param datasource the datasource value to set * @return the StreamInputProperties object itself. */ public StreamInputProperties withDatasource(StreamInputDataSource datasource) { this.datasource = datasource; return this; } }
9245939c39e2cda1b84e3eed793bddef806a9587
873
java
Java
src/main/java/everyos.engine.ribbon.ui.simple/everyos/engine/ribbon/ui/simple/SimpleUIManager.java
WebicityBrowser/Webicity
845c99b393485c5fcadff368ed938e80c3254b0c
[ "MIT" ]
27
2020-12-06T00:46:10.000Z
2022-02-28T18:34:55.000Z
src/main/java/everyos.engine.ribbon.ui.simple/everyos/engine/ribbon/ui/simple/SimpleUIManager.java
WebicityBrowser/Webicity
845c99b393485c5fcadff368ed938e80c3254b0c
[ "MIT" ]
1
2021-07-13T17:42:02.000Z
2021-07-14T04:49:01.000Z
src/main/java/everyos.engine.ribbon.ui.simple/everyos/engine/ribbon/ui/simple/SimpleUIManager.java
WebicityBrowser/Webicity
845c99b393485c5fcadff368ed938e80c3254b0c
[ "MIT" ]
3
2021-07-01T16:03:31.000Z
2021-07-13T05:37:58.000Z
36.375
69
0.817869
1,003,431
package everyos.engine.ribbon.ui.simple; import everyos.engine.ribbon.components.component.BlockComponent; import everyos.engine.ribbon.components.component.BreakComponent; import everyos.engine.ribbon.components.component.LabelComponent; import everyos.engine.ribbon.components.component.TextBoxComponent; import everyos.engine.ribbon.core.graphics.Component; import everyos.engine.ribbon.core.ui.UIManager; public class SimpleUIManager { public static UIManager createUI() { UIManager manager = new UIManager(); manager.put(Component.class, SimpleComponentUI::new); manager.put(BlockComponent.class, SimpleBlockComponentUI::new); manager.put(LabelComponent.class, SimpleLabelComponentUI::new); manager.put(TextBoxComponent.class, SimpleTextBoxComponentUI::new); manager.put(BreakComponent.class, SimpleBreakComponentUI::new); return manager; } }
9245940a3fd9758b5b960ad0f97e129863f4a9b9
5,445
java
Java
indexr-segment/src/main/java/io/indexr/segment/pack/NumOp.java
shunfei/indexr
43d2c7746cbbdc105c57a370c39b4668003f7b1f
[ "Apache-2.0" ]
485
2016-12-23T07:49:52.000Z
2022-03-22T10:58:52.000Z
indexr-segment/src/main/java/io/indexr/segment/pack/NumOp.java
shunfei/IndexR
43d2c7746cbbdc105c57a370c39b4668003f7b1f
[ "Apache-2.0" ]
41
2017-01-02T06:09:20.000Z
2021-12-09T20:01:10.000Z
indexr-segment/src/main/java/io/indexr/segment/pack/NumOp.java
shunfei/IndexR
43d2c7746cbbdc105c57a370c39b4668003f7b1f
[ "Apache-2.0" ]
145
2016-12-23T07:49:57.000Z
2022-03-21T10:12:33.000Z
36.3
112
0.555188
1,003,432
package io.indexr.segment.pack; import io.indexr.compress.bh.BHCompressor; import io.indexr.io.ByteSlice; import io.indexr.util.MemoryUtil; public class NumOp { public static int getInt(long addr, int index) { return MemoryUtil.getInt(addr + (index << 2)); } public static long getLong(long addr, int index) { return MemoryUtil.getLong(addr + (index << 3)); } public static float getFloat(long addr, int index) { return MemoryUtil.getFloat(addr + (index << 2)); } public static double getDouble(long addr, int index) { return MemoryUtil.getDouble(addr + (index << 3)); } public static void putInt(long addr, int index, int v) { MemoryUtil.setInt(addr + (index << 2), v); } public static void putLong(long addr, int index, long v) { MemoryUtil.setLong(addr + (index << 3), v); } public static void putFloat(long addr, int index, float v) { MemoryUtil.setFloat(addr + (index << 2), v); } public static void putDouble(long addr, int index, double v) { MemoryUtil.setDouble(addr + (index << 3), v); } public static ByteSlice allocatByteSlice(byte type, int size) { switch (type) { case NumType.NZero: return ByteSlice.empty(); case NumType.NByte: return ByteSlice.allocateDirect(size); case NumType.NShort: return ByteSlice.allocateDirect(size << 1); case NumType.NInt: return ByteSlice.allocateDirect(size << 2); case NumType.NLong: return ByteSlice.allocateDirect(size << 3); default: throw new UnsupportedOperationException(); } } public static ByteSlice bhcompress(byte type, ByteSlice data, int itemSize, long minVal, long maxVal) { switch (type) { case NumType.NZero: return ByteSlice.empty(); case NumType.NByte: return BHCompressor.compressByte(data, itemSize, maxVal - minVal); case NumType.NShort: return BHCompressor.compressShort(data, itemSize, maxVal - minVal); case NumType.NInt: return BHCompressor.compressInt(data, itemSize, maxVal - minVal); case NumType.NLong: return BHCompressor.compressLong(data, itemSize, maxVal - minVal); default: throw new UnsupportedOperationException(); } } public static ByteSlice bhdecompress(byte type, ByteSlice cmpData, int itemSize, long minVal, long maxVal) { switch (type) { case NumType.NZero: return ByteSlice.empty(); case NumType.NByte: return BHCompressor.decompressByte(cmpData, itemSize, maxVal - minVal); case NumType.NShort: return BHCompressor.decompressShort(cmpData, itemSize, maxVal - minVal); case NumType.NInt: return BHCompressor.decompressInt(cmpData, itemSize, maxVal - minVal); case NumType.NLong: return BHCompressor.decompressLong(cmpData, itemSize, maxVal - minVal); default: throw new UnsupportedOperationException(); } } //======================================================================= // VERSION_0 deprecated public static long getVal(byte type, long addr, int index, long minVal) { switch (type) { case NumType.NZero: return minVal; case NumType.NByte: return minVal + MemoryUtil.getByte(addr + index); case NumType.NShort: return minVal + MemoryUtil.getShort(addr + (index << 1)); case NumType.NInt: return minVal + MemoryUtil.getInt(addr + (index << 2)); case NumType.NLong: return minVal + MemoryUtil.getLong(addr + (index << 3)); default: throw new UnsupportedOperationException(); } } public static long getVal(byte type, ByteSlice data, int index, long minVal) { switch (type) { case NumType.NZero: return minVal; case NumType.NByte: return minVal + data.get(index); case NumType.NShort: return minVal + data.getShort(index << 1); case NumType.NInt: return minVal + data.getInt(index << 2); case NumType.NLong: return minVal + data.getLong(index << 3); default: throw new UnsupportedOperationException(); } } public static void putVal(byte type, ByteSlice data, int index, long val, long minVal) { switch (type) { case NumType.NZero: break; case NumType.NByte: data.put(index, (byte) (val - minVal)); break; case NumType.NShort: data.putShort(index << 1, (short) (val - minVal)); break; case NumType.NInt: data.putInt(index << 2, (int) (val - minVal)); break; case NumType.NLong: data.putLong(index << 3, val - minVal); break; default: throw new UnsupportedOperationException(); } } }
92459522b3bf2dd3e050297ef98fc14456efdbe0
708
java
Java
LJL-Futures-v1/solutions/001_creating_futures/src/test/java/com/lightbend/futures/CustomerTest.java
dexterdarwich/lightbend-academy
2f3da9faab04cc24e4043f2aa6a82da3c93a64a1
[ "MIT" ]
null
null
null
LJL-Futures-v1/solutions/001_creating_futures/src/test/java/com/lightbend/futures/CustomerTest.java
dexterdarwich/lightbend-academy
2f3da9faab04cc24e4043f2aa6a82da3c93a64a1
[ "MIT" ]
2
2022-01-21T23:44:51.000Z
2022-01-21T23:45:23.000Z
LJL-Futures-v1/solutions/003_executors/src/test/java/com/lightbend/futures/CustomerTest.java
dexterdarwich/lightbend-academy
2f3da9faab04cc24e4043f2aa6a82da3c93a64a1
[ "MIT" ]
null
null
null
25.285714
140
0.710452
1,003,433
package com.lightbend.futures; import org.junit.jupiter.api.Test; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; class CustomerTest { @Test void equals_shouldReturnTrue_ifCustomersAreEqual() { Customer cust1 = TestHelpers.generateCustomer(); Customer cust2 = new Customer(cust1.getId(), cust1.getFirstName(), cust1.getLastName(), cust1.getAddress(), cust1.getPhoneNumber()); assertEquals(cust1, cust2); } @Test void equals_shouldReturnFalse_ifCustomersAreNotEqual() { Customer cust1 = TestHelpers.generateCustomer(); Customer cust2 = TestHelpers.generateCustomer(); assertNotEquals(cust1, cust2); } }
9245955a5203c6ef05fe0d03785332604f2c894f
3,437
java
Java
anchor-plugin-image/src/main/java/org/anchoranalysis/plugin/image/bean/thumbnail/object/ScaleFactorCalculator.java
anchoranalysis/anchor-plugins
200f9ebf4d5f95165cfb3163c92b0daeeac14fee
[ "MIT" ]
null
null
null
anchor-plugin-image/src/main/java/org/anchoranalysis/plugin/image/bean/thumbnail/object/ScaleFactorCalculator.java
anchoranalysis/anchor-plugins
200f9ebf4d5f95165cfb3163c92b0daeeac14fee
[ "MIT" ]
70
2020-02-16T16:03:34.000Z
2022-02-13T14:53:09.000Z
anchor-plugin-image/src/main/java/org/anchoranalysis/plugin/image/bean/thumbnail/object/ScaleFactorCalculator.java
anchoranalysis/anchor-plugins
200f9ebf4d5f95165cfb3163c92b0daeeac14fee
[ "MIT" ]
null
null
null
45.223684
100
0.732325
1,003,434
/*- * #%L * anchor-plugin-image * %% * Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ package org.anchoranalysis.plugin.image.bean.thumbnail.object; import java.util.function.ToIntFunction; import java.util.stream.Stream; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.anchoranalysis.core.functional.StreamableCollection; import org.anchoranalysis.image.core.dimensions.size.ResizeExtentUtilities; import org.anchoranalysis.spatial.box.BoundingBox; import org.anchoranalysis.spatial.box.Extent; import org.anchoranalysis.spatial.scale.ScaleFactor; /** * Helpers determine a scaling-factor for objects to fit in a certain-sized scene. * * @author Owen Feehan */ @NoArgsConstructor(access = AccessLevel.PRIVATE) class ScaleFactorCalculator { /** * Calculates a minimal scaling necessary so that each bounding-box can fit inside a certain * sized scene * * <p>In otherwords the largest dimension of any object, must still be able to fit inside the * corresponding dimension of the target scene. * * @param boundingBoxes a stream of bounding-boxes, each of which must fit inside {@code * targetSize} * @param targetSize the size in which all bounding-boxes must fit * @return a scale-factor that can be applied to the bounding-boxes so that they will always fit * inside {@code targetSize} */ public static ScaleFactor factorSoEachBoundingBoxFitsIn( StreamableCollection<BoundingBox> boundingBoxes, Extent targetSize) { Extent maxInEachDimension = new Extent( extractMaxDimension(boundingBoxes.stream(), Extent::x), extractMaxDimension(boundingBoxes.stream(), Extent::y)); return ResizeExtentUtilities.relativeScale(maxInEachDimension, targetSize); } private static int extractMaxDimension( Stream<BoundingBox> boundingBoxes, ToIntFunction<Extent> functionDimension) { // We add a 1 to make the object be a little bit smaller after scaling and prevent // round up errors after accidentally pushing a bounding-box outside the target-window return boundingBoxes.map(BoundingBox::extent).mapToInt(functionDimension).max().getAsInt() + 1; } }
924595e022d3031118d656bfb8a8d138893a42ac
900
java
Java
application/external-interfaces/auth-client/src/main/java/ro/ciprianradu/rentacar/auth/client/constraint/FieldMatch.java
ciprian-radu/rent-a-car
4bbe5f34e450f813e880bf8507c837d22648689c
[ "Apache-2.0" ]
9
2019-09-08T13:50:10.000Z
2020-10-06T15:09:15.000Z
application/external-interfaces/auth-client/src/main/java/ro/ciprianradu/rentacar/auth/client/constraint/FieldMatch.java
ciprian-radu/rent-a-car
4bbe5f34e450f813e880bf8507c837d22648689c
[ "Apache-2.0" ]
1
2021-01-15T15:22:02.000Z
2021-01-15T15:57:28.000Z
application/external-interfaces/auth-client/src/main/java/ro/ciprianradu/rentacar/auth/client/constraint/FieldMatch.java
ciprian-radu/rent-a-car
4bbe5f34e450f813e880bf8507c837d22648689c
[ "Apache-2.0" ]
2
2020-05-10T03:09:08.000Z
2020-10-10T09:03:56.000Z
25
63
0.746667
1,003,435
package ro.ciprianradu.rentacar.auth.client.constraint; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target({TYPE, ANNOTATION_TYPE}) @Retention(RUNTIME) @Constraint(validatedBy = FieldMatchValidator.class) @Documented public @interface FieldMatch { String message() default "{constraints.field-match}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; String first(); String second(); @Target({TYPE, ANNOTATION_TYPE}) @Retention(RUNTIME) @Documented @interface List { FieldMatch[] value(); } }
924596068371b0bdd5d4f4f9f4b46c872d720055
22,631
java
Java
src/java/org/apache/cassandra/index/sasi/disk/AbstractTokenTreeBuilder.java
thobbs/cassandra
12f5ca36ffab227a1531a554b00cf83d898f9f28
[ "Apache-2.0" ]
null
null
null
src/java/org/apache/cassandra/index/sasi/disk/AbstractTokenTreeBuilder.java
thobbs/cassandra
12f5ca36ffab227a1531a554b00cf83d898f9f28
[ "Apache-2.0" ]
null
null
null
src/java/org/apache/cassandra/index/sasi/disk/AbstractTokenTreeBuilder.java
thobbs/cassandra
12f5ca36ffab227a1531a554b00cf83d898f9f28
[ "Apache-2.0" ]
1
2019-10-01T10:19:42.000Z
2019-10-01T10:19:42.000Z
31.964689
156
0.527153
1,003,436
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.index.sasi.disk; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import java.util.function.*; import com.carrotsearch.hppc.LongArrayList; import com.carrotsearch.hppc.cursors.LongCursor; import com.carrotsearch.hppc.cursors.LongObjectCursor; import org.apache.cassandra.dht.*; import org.apache.cassandra.io.util.DataOutputPlus; import org.apache.cassandra.utils.AbstractIterator; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.Pair; public abstract class AbstractTokenTreeBuilder implements TokenTreeBuilder { protected int numBlocks; protected Node root; protected InteriorNode rightmostParent; protected Leaf leftmostLeaf; protected Leaf rightmostLeaf; protected long tokenCount = 0; protected long treeMinToken; protected long treeMaxToken; public void add(TokenTreeBuilder other) { add(other.iterator()); } public TokenTreeBuilder finish() { if (root == null) constructTree(); return this; } public long getTokenCount() { return tokenCount; } public int serializedSize() { if (numBlocks == 1) return BLOCK_HEADER_BYTES + ((int) tokenCount * LEAF_ENTRY_BYTES); else return numBlocks * BLOCK_BYTES; } public void write(DataOutputPlus out) throws IOException { ByteBuffer blockBuffer = ByteBuffer.allocate(BLOCK_BYTES); Iterator<Node> levelIterator = root.levelIterator(); long childBlockIndex = 1; while (levelIterator != null) { Node firstChild = null; while (levelIterator.hasNext()) { Node block = levelIterator.next(); if (firstChild == null && !block.isLeaf()) firstChild = ((InteriorNode) block).children.get(0); if (block.isSerializable()) { block.serialize(childBlockIndex, blockBuffer); flushBuffer(blockBuffer, out, numBlocks != 1); } childBlockIndex += block.childCount(); } levelIterator = (firstChild == null) ? null : firstChild.levelIterator(); } } protected abstract void constructTree(); protected void flushBuffer(ByteBuffer buffer, DataOutputPlus o, boolean align) throws IOException { // seek to end of last block before flushing if (align) alignBuffer(buffer, BLOCK_BYTES); buffer.flip(); o.write(buffer); buffer.clear(); } /** * Tree node, * * B+-tree consists of root, interior nodes and leaves. Root can be either a node or a leaf. * * Depending on the concrete implementation of {@code TokenTreeBuilder} * leaf can be partial or static (in case of {@code StaticTokenTreeBuilder} or dynamic in case * of {@code DynamicTokenTreeBuilder} */ protected abstract class Node { protected InteriorNode parent; protected Node next; protected Long nodeMinToken, nodeMaxToken; public Node(Long minToken, Long maxToken) { nodeMinToken = minToken; nodeMaxToken = maxToken; } public abstract boolean isSerializable(); public abstract void serialize(long childBlockIndex, ByteBuffer buf); public abstract int childCount(); public abstract int tokenCount(); public Long smallestToken() { return nodeMinToken; } public Long largestToken() { return nodeMaxToken; } public Iterator<Node> levelIterator() { return new LevelIterator(this); } public boolean isLeaf() { return (this instanceof Leaf); } protected boolean isLastLeaf() { return this == rightmostLeaf; } protected boolean isRoot() { return this == root; } protected void updateTokenRange(long token) { nodeMinToken = nodeMinToken == null ? token : Math.min(nodeMinToken, token); nodeMaxToken = nodeMaxToken == null ? token : Math.max(nodeMaxToken, token); } protected void serializeHeader(ByteBuffer buf) { Header header; if (isRoot()) header = new RootHeader(); else if (!isLeaf()) header = new InteriorNodeHeader(); else header = new LeafHeader(); header.serialize(buf); alignBuffer(buf, BLOCK_HEADER_BYTES); } /** * Shared header part, written for all node types: * [ info byte ] [ token count ] [ min node token ] [ max node token ] * [ 1b ] [ 2b (short) ] [ 8b (long) ] [ 8b (long) ] **/ private abstract class Header { /** * Serializes the shared part of the header */ public void serialize(ByteBuffer buf) { buf.put(infoByte()) .putShort((short) (tokenCount())) .putLong(nodeMinToken) .putLong(nodeMaxToken); } protected abstract byte infoByte(); } /** * In addition to shared header part, root header stores version information, * overall token count and min/max tokens for the whole tree: * [ magic ] [ overall token count ] [ min tree token ] [ max tree token ] * [ 2b (short) ] [ 8b (long) ] [ 8b (long) ] [ 8b (long) ] */ private class RootHeader extends Header { public void serialize(ByteBuffer buf) { super.serialize(buf); writeMagic(buf); buf.putLong(tokenCount) .putLong(treeMinToken) .putLong(treeMaxToken); } protected byte infoByte() { // if leaf, set leaf indicator and last leaf indicator (bits 0 & 1) // if not leaf, clear both bits return isLeaf() ? ENTRY_TYPE_MASK : 0; } protected void writeMagic(ByteBuffer buf) { switch (Descriptor.CURRENT_VERSION) { case ab: buf.putShort(AB_MAGIC); break; case ac: buf.putShort(AC_MAGIC); break; default: throw new RuntimeException("Unsupported version"); } } } private class InteriorNodeHeader extends Header { // bit 0 (leaf indicator) & bit 1 (last leaf indicator) cleared protected byte infoByte() { return 0; } } private class LeafHeader extends Header { // bit 0 set as leaf indicator // bit 1 set if this is last leaf of data protected byte infoByte() { byte infoByte = 1; infoByte |= (isLastLeaf()) ? (1 << LAST_LEAF_SHIFT) : 0; return infoByte; } } } /** * Leaf consists of * - header (format described in {@code Header} ) * - data (format described in {@code LeafEntry}) * - overflow collision entries, that hold {@value OVERFLOW_TRAILER_CAPACITY} of {@code RowOffset}. */ protected abstract class Leaf extends Node { protected LongArrayList overflowCollisions; public Leaf(Long minToken, Long maxToken) { super(minToken, maxToken); } public int childCount() { return 0; } protected void serializeOverflowCollisions(ByteBuffer buf) { if (overflowCollisions != null) for (LongCursor offset : overflowCollisions) buf.putLong(offset.value); } public void serialize(long childBlockIndex, ByteBuffer buf) { serializeHeader(buf); serializeData(buf); serializeOverflowCollisions(buf); } protected abstract void serializeData(ByteBuffer buf); protected LeafEntry createEntry(final long tok, final KeyOffsets offsets) { LongArrayList rawOffsets = new LongArrayList(offsets.size()); offsets.forEach(new Consumer<LongObjectCursor<long[]>>() { public void accept(LongObjectCursor<long[]> cursor) { for (long l : cursor.value) { rawOffsets.add(cursor.key); rawOffsets.add(l); } } }); int offsetCount = rawOffsets.size(); switch (offsetCount) { case 0: throw new AssertionError("no offsets for token " + tok); case 2: return new SimpleLeafEntry(tok, rawOffsets.get(0), rawOffsets.get(1)); default: assert offsetCount % 2 == 0; if (offsetCount == 4) { if (rawOffsets.get(0) < Integer.MAX_VALUE && rawOffsets.get(1) < Integer.MAX_VALUE && rawOffsets.get(2) < Integer.MAX_VALUE && rawOffsets.get(3) < Integer.MAX_VALUE) { return new PackedCollisionLeafEntry(tok, (int)rawOffsets.get(0), (int) rawOffsets.get(1), (int) rawOffsets.get(2), (int) rawOffsets.get(3)); } } return createOverflowEntry(tok, offsetCount, rawOffsets); } } private LeafEntry createOverflowEntry(final long tok, final int offsetCount, final LongArrayList offsets) { if (overflowCollisions == null) overflowCollisions = new LongArrayList(offsetCount); int overflowCount = (overflowCollisions.size() + offsetCount) / 2; if (overflowCount >= OVERFLOW_TRAILER_CAPACITY) throw new AssertionError("cannot have more than " + OVERFLOW_TRAILER_CAPACITY + " overflow collisions per leaf, but had: " + overflowCount); LeafEntry entry = new OverflowCollisionLeafEntry(tok, (short) (overflowCollisions.size() / 2), (short) (offsetCount / 2)); overflowCollisions.addAll(offsets); return entry; } /** * A leaf of the B+-Tree, that holds information about the row offset(s) for * the current token. * * Main 3 types of leaf entries are: * 1) simple leaf entry: holding just a single row offset * 2) packed collision leaf entry: holding two entries that would fit together into 168 bytes * 3) overflow entry: only holds offset in overflow trailer and amount of entries belonging to this leaf */ protected abstract class LeafEntry { protected final long token; abstract public EntryType type(); public LeafEntry(final long tok) { token = tok; } public abstract void serialize(ByteBuffer buf); } /** * Simple leaf, that can store a single row offset, having the following format: * * [ type ] [ token ] [ partition offset ] [ row offset ] * [ 2b (short) ] [ 8b (long) ] [ 8b (long) ] [ 8b (long) ] */ protected class SimpleLeafEntry extends LeafEntry { private final long partitionOffset; private final long rowOffset; public SimpleLeafEntry(final long tok, final long partitionOffset, final long rowOffset) { super(tok); this.partitionOffset = partitionOffset; this.rowOffset = rowOffset; } public EntryType type() { return EntryType.SIMPLE; } @Override public void serialize(ByteBuffer buf) { buf.putShort((short) type().ordinal()) .putLong(token) .putLong(partitionOffset) .putLong(rowOffset); } } /** * Packed collision entry, can store two offsets, if each one of their positions * fit into 4 bytes. * [ type ] [ token ] [ partition offset 1 ] [ row offset 1] [ partition offset 1 ] [ row offset 1] * [ 2b (short) ] [ 8b (long) ] [ 4b (int) ] [ 4b (int) ] [ 4b (int) ] [ 4b (int) ] */ protected class PackedCollisionLeafEntry extends LeafEntry { private final int partitionOffset1; private final int rowOffset1; private final int partitionOffset2; private final int rowOffset2; public PackedCollisionLeafEntry(final long tok, final int partitionOffset1, final int rowOffset1, final int partitionOffset2, final int rowOffset2) { super(tok); this.partitionOffset1 = partitionOffset1; this.rowOffset1 = rowOffset1; this.partitionOffset2 = partitionOffset2; this.rowOffset2 = rowOffset2; } public EntryType type() { return EntryType.PACKED; } @Override public void serialize(ByteBuffer buf) { buf.putShort((short) type().ordinal()) .putLong(token) .putInt(partitionOffset1) .putInt(rowOffset1) .putInt(partitionOffset2) .putInt(rowOffset2); } } /** * Overflow collision entry, holds an entry with three or more offsets, or two offsets * that cannot be packed into 16 bytes. * [ type ] [ token ] [ start index ] [ count ] * [ 2b (short) ] [ 8b (long) ] [ 8b (long) ] [ 8b (long) ] * * - [ start index ] is a position of first item belonging to this leaf entry in the overflow trailer * - [ count ] is the amount of items belonging to this leaf entry that are stored in the overflow trailer */ private class OverflowCollisionLeafEntry extends LeafEntry { private final short startIndex; private final short count; public OverflowCollisionLeafEntry(final long tok, final short collisionStartIndex, final short collisionCount) { super(tok); startIndex = collisionStartIndex; count = collisionCount; } public EntryType type() { return EntryType.OVERFLOW; } @Override public void serialize(ByteBuffer buf) { buf.putShort((short) type().ordinal()) .putLong(token) .putLong(startIndex) .putLong(count); } } } /** * Interior node consists of: * - (interior node) header * - tokens (serialized as longs, with count stored in header) * - child offsets */ protected class InteriorNode extends Node { protected List<Long> tokens = new ArrayList<>(TOKENS_PER_BLOCK); protected List<Node> children = new ArrayList<>(TOKENS_PER_BLOCK + 1); protected int position = 0; public InteriorNode() { super(null, null); } public boolean isSerializable() { return true; } public void serialize(long childBlockIndex, ByteBuffer buf) { serializeHeader(buf); serializeTokens(buf); serializeChildOffsets(childBlockIndex, buf); } public int childCount() { return children.size(); } public int tokenCount() { return tokens.size(); } public Long smallestToken() { return tokens.get(0); } protected void add(Long token, InteriorNode leftChild, InteriorNode rightChild) { int pos = tokens.size(); if (pos == TOKENS_PER_BLOCK) { InteriorNode sibling = split(); sibling.add(token, leftChild, rightChild); } else { if (leftChild != null) children.add(pos, leftChild); if (rightChild != null) { children.add(pos + 1, rightChild); rightChild.parent = this; } updateTokenRange(token); tokens.add(pos, token); } } protected void add(Leaf node) { if (position == (TOKENS_PER_BLOCK + 1)) { rightmostParent = split(); rightmostParent.add(node); } else { node.parent = this; children.add(position, node); position++; // the first child is referenced only during bulk load. we don't take a value // to store into the tree, one is subtracted since position has already been incremented // for the next node to be added if (position - 1 == 0) return; // tokens are inserted one behind the current position, but 2 is subtracted because // position has already been incremented for the next add Long smallestToken = node.smallestToken(); updateTokenRange(smallestToken); tokens.add(position - 2, smallestToken); } } protected InteriorNode split() { Pair<Long, InteriorNode> splitResult = splitBlock(); Long middleValue = splitResult.left; InteriorNode sibling = splitResult.right; InteriorNode leftChild = null; // create a new root if necessary if (parent == null) { parent = new InteriorNode(); root = parent; sibling.parent = parent; leftChild = this; numBlocks++; } parent.add(middleValue, leftChild, sibling); return sibling; } protected Pair<Long, InteriorNode> splitBlock() { final int splitPosition = TOKENS_PER_BLOCK - 2; InteriorNode sibling = new InteriorNode(); sibling.parent = parent; next = sibling; Long middleValue = tokens.get(splitPosition); for (int i = splitPosition; i < TOKENS_PER_BLOCK; i++) { if (i != TOKENS_PER_BLOCK && i != splitPosition) { long token = tokens.get(i); sibling.updateTokenRange(token); sibling.tokens.add(token); } Node child = children.get(i + 1); child.parent = sibling; sibling.children.add(child); sibling.position++; } for (int i = TOKENS_PER_BLOCK; i >= splitPosition; i--) { if (i != TOKENS_PER_BLOCK) tokens.remove(i); if (i != splitPosition) children.remove(i); } nodeMinToken = smallestToken(); nodeMaxToken = tokens.get(tokens.size() - 1); numBlocks++; return Pair.create(middleValue, sibling); } protected boolean isFull() { return (position >= TOKENS_PER_BLOCK + 1); } private void serializeTokens(ByteBuffer buf) { tokens.forEach(buf::putLong); } private void serializeChildOffsets(long childBlockIndex, ByteBuffer buf) { for (int i = 0; i < children.size(); i++) buf.putLong((childBlockIndex + i) * BLOCK_BYTES); } } public static class LevelIterator extends AbstractIterator<Node> { private Node currentNode; LevelIterator(Node first) { currentNode = first; } public Node computeNext() { if (currentNode == null) return endOfData(); Node returnNode = currentNode; currentNode = returnNode.next; return returnNode; } } protected static void alignBuffer(ByteBuffer buffer, int blockSize) { long curPos = buffer.position(); if ((curPos & (blockSize - 1)) != 0) // align on the block boundary if needed buffer.position((int) FBUtilities.align(curPos, blockSize)); } }
924596177c3269bd6df9623ece7da8263f295854
1,883
java
Java
services/dlab-model/src/main/java/com/epam/dlab/dto/exploratory/ExploratoryGitCredsDTO.java
ofuks/DLab
460804a2559843d099936fe40373093f9bf9edcb
[ "Apache-2.0" ]
null
null
null
services/dlab-model/src/main/java/com/epam/dlab/dto/exploratory/ExploratoryGitCredsDTO.java
ofuks/DLab
460804a2559843d099936fe40373093f9bf9edcb
[ "Apache-2.0" ]
null
null
null
services/dlab-model/src/main/java/com/epam/dlab/dto/exploratory/ExploratoryGitCredsDTO.java
ofuks/DLab
460804a2559843d099936fe40373093f9bf9edcb
[ "Apache-2.0" ]
null
null
null
31.383333
126
0.644716
1,003,437
/*************************************************************************** Copyright (c) 2016, EPAM SYSTEMS INC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ package com.epam.dlab.dto.exploratory; import java.util.Collections; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; /** Stores info about the GIT credentials. * */ public class ExploratoryGitCredsDTO { @JsonProperty("git_creds") private List<ExploratoryGitCreds> gitCreds; /** Return the list of GIT credentials. */ public List<ExploratoryGitCreds> getGitCreds() { return gitCreds; } /** Set the list of GIT credentials and check the unique for host names. */ public void setGitCreds(List<ExploratoryGitCreds> gitCreds) { if (gitCreds != null) { Collections.sort(gitCreds); for (int i = 1; i < gitCreds.size(); i++) { if (gitCreds.get(i).equals(gitCreds.get(i - 1))) { throw new IllegalArgumentException("Duplicate found for host name in git credentials: " + gitCreds.get(i).getHostname()); } } } this.gitCreds = gitCreds; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("gitCreds", gitCreds) .toString(); } }
9245968471180f221298089fece801bd7fbb1070
797
java
Java
3D-Game/src/me/aars/GunsAreFun/graphics/Param.java
popcornhair98/ManjpipIPompen
befe6f263dbbae14270dea1143299529f37aec60
[ "Unlicense" ]
null
null
null
3D-Game/src/me/aars/GunsAreFun/graphics/Param.java
popcornhair98/ManjpipIPompen
befe6f263dbbae14270dea1143299529f37aec60
[ "Unlicense" ]
null
null
null
3D-Game/src/me/aars/GunsAreFun/graphics/Param.java
popcornhair98/ManjpipIPompen
befe6f263dbbae14270dea1143299529f37aec60
[ "Unlicense" ]
null
null
null
23.441176
81
0.657465
1,003,438
package me.aars.GunsAreFun.graphics; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; public class Param { public static Render param = loadBitmap("/me/aars/GunsAreFun/ui/unicorn.jpg/"); private static Render loadBitmap(String string) { BufferedImage i; try { i = ImageIO.read(Param.class.getResource(string)); int width = i.getWidth(); int height = i.getHeight(); Render result = new Render(width, height); i.getRGB(0, 0, width, height, result.pixels, 0, width); for(int c = 0; c<result.getPixelArraySize(); c++) { result.pixels[c] = Color.BLUE.getRGB(); } return result; } catch (IOException e) { e.printStackTrace(); return null; } } }
9245979b39ab0dffbb1d5e2f52f68cb1c1016403
638
java
Java
src/main/java/io/github/mariazevedo88/builder/TesteBuilder.java
AlexRogalskiy/artigo-boas-praticas-medium
5a7c350e65901f92a25fc204586965c977f1ea78
[ "MIT" ]
5
2019-02-07T02:16:05.000Z
2021-09-02T18:47:00.000Z
src/main/java/io/github/mariazevedo88/builder/TesteBuilder.java
mariazevedo88/artigo-boas-praticas-medium
5a7c350e65901f92a25fc204586965c977f1ea78
[ "MIT" ]
1
2021-12-04T03:31:48.000Z
2021-12-04T03:32:05.000Z
src/main/java/io/github/mariazevedo88/builder/TesteBuilder.java
AlexRogalskiy/artigo-boas-praticas-medium
5a7c350e65901f92a25fc204586965c977f1ea78
[ "MIT" ]
1
2021-12-04T03:31:39.000Z
2021-12-04T03:31:39.000Z
22.785714
75
0.622257
1,003,439
package io.github.mariazevedo88.builder; import org.apache.log4j.Logger; /** * Classe de teste do Builder * * @author Mariana Azevedo * @since 03/02/2019 * */ public class TesteBuilder { private static final Logger logger = Logger.getLogger(TesteBuilder.class); public static void main(String[] args) { Venda venda = new VendaBuilder().paraComprador("Mariana") .comDocumento("123456789") .comProduto(new Produto("Playstation 4", 1500.0)) .comProduto(new Produto("TV 40'", 1000.0)) .naDataAtual() .constroi(); logger.info(venda); } }
9245979f17ed695ca010cd5e2907f903122e77af
2,187
java
Java
src/main/java/com/lupicus/syp/Main.java
Lupicus/SaveYourPets
3e4482dfa84ded6036ff43d859b6d48f00e85f97
[ "MIT" ]
null
null
null
src/main/java/com/lupicus/syp/Main.java
Lupicus/SaveYourPets
3e4482dfa84ded6036ff43d859b6d48f00e85f97
[ "MIT" ]
5
2021-01-02T01:44:39.000Z
2022-02-16T04:37:01.000Z
src/main/java/com/lupicus/syp/Main.java
Lupicus/SaveYourPets
3e4482dfa84ded6036ff43d859b6d48f00e85f97
[ "MIT" ]
null
null
null
30.375
87
0.743941
1,003,440
package com.lupicus.syp; import com.lupicus.syp.advancements.ModTriggers; import com.lupicus.syp.config.MyConfig; import com.lupicus.syp.item.ModItems; import com.lupicus.syp.item.ModLoot; import net.minecraft.item.Item; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.ColorHandlerEvent; import net.minecraftforge.event.LootTableLoadEvent; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; @Mod(Main.MODID) public class Main { public static final String MODID = "syp"; public Main() { FMLJavaModLoadingContext.get().getModEventBus().register(this); ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, MyConfig.COMMON_SPEC); } @SubscribeEvent public void setupCommon(final FMLCommonSetupEvent event) { ModTriggers.register(); } @OnlyIn(Dist.CLIENT) @SubscribeEvent public void setupClient(final FMLClientSetupEvent event) { } @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD) public static class ModEvents { @SubscribeEvent public static void onItemsRegistry(final RegistryEvent.Register<Item> event) { ModItems.register(event.getRegistry()); } @OnlyIn(Dist.CLIENT) @SubscribeEvent public static void onColorsRegistry(final ColorHandlerEvent.Item event) { ModItems.register(event.getItemColors()); } } @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.FORGE) public static class ForgeEvents { @SubscribeEvent public static void onLoot(final LootTableLoadEvent event) { ModLoot.addLoot(event.getName(), event.getTable(), event.getLootTableManager()); } } }
9245980724ac32b7eb970d61c4bdccf779c50d4f
1,247
java
Java
src/main/java/com/zx/sms/handler/smgp/SMGPExitMessageHandler.java
thinwonton/SMSGate
cefe271ed99ba6557ba6c16af80d7fae673dc0b3
[ "Apache-2.0" ]
537
2018-04-24T13:56:04.000Z
2022-03-31T03:36:46.000Z
src/main/java/com/zx/sms/handler/smgp/SMGPExitMessageHandler.java
thinwonton/SMSGate
cefe271ed99ba6557ba6c16af80d7fae673dc0b3
[ "Apache-2.0" ]
21
2018-05-31T08:12:15.000Z
2022-01-21T08:36:11.000Z
src/main/java/com/zx/sms/handler/smgp/SMGPExitMessageHandler.java
thinwonton/SMSGate
cefe271ed99ba6557ba6c16af80d7fae673dc0b3
[ "Apache-2.0" ]
260
2018-04-28T07:33:41.000Z
2022-03-19T15:12:19.000Z
31.175
102
0.747394
1,003,441
package com.zx.sms.handler.smgp; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.ChannelHandler.Sharable; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import java.util.concurrent.TimeUnit; import com.zx.sms.codec.smgp.msg.SMGPExitMessage; import com.zx.sms.codec.smgp.msg.SMGPExitRespMessage; @Sharable public class SMGPExitMessageHandler extends SimpleChannelInboundHandler<SMGPExitMessage>{ @Override protected void channelRead0(final ChannelHandlerContext ctx, SMGPExitMessage msg) throws Exception { SMGPExitRespMessage resp = new SMGPExitRespMessage(); resp.setSequenceNo(msg.getSequenceNo()); ChannelFuture future = ctx.channel().writeAndFlush(resp); final ChannelHandlerContext finalctx = ctx; future.addListeners(new GenericFutureListener(){ @Override public void operationComplete(Future future) throws Exception { ctx.executor().schedule(new Runnable(){ @Override public void run() { finalctx.channel().close(); } },500,TimeUnit.MILLISECONDS); } }); }}
92459807cacca33454fadd9c4b3eba200702ed9b
6,479
java
Java
src/main/java/com/siming/network/CreateChannel.java
yyyfor/trace-project
c5d77a7dd556510a499edae1433f777827a5fd28
[ "MIT" ]
null
null
null
src/main/java/com/siming/network/CreateChannel.java
yyyfor/trace-project
c5d77a7dd556510a499edae1433f777827a5fd28
[ "MIT" ]
null
null
null
src/main/java/com/siming/network/CreateChannel.java
yyyfor/trace-project
c5d77a7dd556510a499edae1433f777827a5fd28
[ "MIT" ]
null
null
null
53.106557
167
0.673406
1,003,442
package com.siming.network; import com.siming.client.FabricClient; import com.siming.config.Config; import com.siming.user.UserContext; import com.siming.util.LogUtil; import com.siming.util.Util; import org.hyperledger.fabric.sdk.*; import org.hyperledger.fabric.sdk.security.CryptoSuite; import java.io.File; /* start */ public class CreateChannel { public static void main(String[] args) { try { CryptoSuite.Factory.getCryptoSuite(); // Util.cleanUp(); UserContext org1Admin = new UserContext(); File pkFolder1 = new File(Config.ORG1_USR_ADMIN_PK); File [] pkFiles1 = pkFolder1.listFiles(); File certFolder1 = new File(Config.ORG1_USR_ADMIN_CERT); File [] certFiles1 = certFolder1.listFiles(); assert pkFiles1 != null; Enrollment enrollOrg1Admin; enrollOrg1Admin = Util.getEnrollment(Config.ORG1_USR_ADMIN_PK, pkFiles1[0].getName(), Config.ORG1_USR_ADMIN_CERT, certFiles1[0].getName()); org1Admin.setEnrollment(enrollOrg1Admin); org1Admin.setMspId(Config.ORG1_MSP); org1Admin.setName(Config.ADMIN); UserContext org2Admin = new UserContext(); File pkFolder2 = new File(Config.ORG2_USR_ADMIN_PK); File[] pkFiles2 = pkFolder2.listFiles(); File certFolder2 = new File(Config.ORG2_USR_ADMIN_CERT); File[] certFiles2 = certFolder2.listFiles(); assert certFiles2 != null; assert pkFiles2 != null; Enrollment enrollOrg2Admin = Util.getEnrollment(Config.ORG2_USR_ADMIN_PK, pkFiles2[0].getName(), Config.ORG2_USR_ADMIN_CERT, certFiles2[0].getName()); org2Admin.setEnrollment(enrollOrg2Admin); org2Admin.setMspId(Config.ORG2_MSP); org2Admin.setName(Config.ADMIN); UserContext org3Admin = new UserContext(); File pkFolder3 = new File(Config.ORG3_USR_ADMIN_PK); File [] pkFiles3 = pkFolder3.listFiles(); File certFolder3; certFolder3 = new File(Config.ORG3_USR_ADMIN_CERT); File [] certFiles3 = certFolder3.listFiles(); assert certFiles3 != null; assert pkFiles3 != null; Enrollment enrollOrg3Admin = Util.getEnrollment(Config.ORG3_USR_ADMIN_PK, pkFiles3[0].getName(), Config.ORG3_USR_ADMIN_CERT, certFiles3[0].getName()); org3Admin.setEnrollment(enrollOrg3Admin); org3Admin.setMspId(Config.ORG3_MSP); org3Admin.setName(Config.ADMIN); FabricClient fabricClient = new FabricClient(org1Admin); Orderer orderer = fabricClient.getInstance().newOrderer(Config.ORDERER_NAME, Config.ORDERER_URL); ChannelConfiguration channelConfiguration = new ChannelConfiguration(new File(Config.CHANNEL_CONFIG_PATH)); byte [] channelConfigurationSignatures = fabricClient.getInstance().getChannelConfigurationSignature(channelConfiguration, org1Admin); Channel trace_channel = fabricClient.getInstance().newChannel(Config.TRACE_CHANEL, orderer, channelConfiguration, channelConfigurationSignatures); //create 3 channels // Channel producer_channel = fabricClient.getInstance().newChannel(Config.PRODUCER_CHANNEL, orderer, channelConfiguration, channelConfigurationSignatures); // Channel factory_channel = fabricClient.getInstance().newChannel(Config.FACTORY_CHANEL, orderer, channelConfiguration, channelConfigurationSignatures); // Channel sale_channel = fabricClient.getInstance().newChannel(Config.SALE_CHANEL, orderer, channelConfiguration, channelConfigurationSignatures); Peer peer0_org1 = fabricClient.getInstance().newPeer(Config.ORG1_PEER_0, Config.ORG1_PEER_0_URL); Peer peer1_org1 = fabricClient.getInstance().newPeer(Config.ORG1_PEER_1, Config.ORG1_PEER_1_URL); Peer peer0_org2 = fabricClient.getInstance().newPeer(Config.ORG2_PEER_0, Config.ORG2_PEER_0_URL); Peer peer1_org2 = fabricClient.getInstance().newPeer(Config.ORG2_PEER_1, Config.ORG2_PEER_1_URL); Peer peer0_org3 = fabricClient.getInstance().newPeer(Config.ORG3_PEER_0, Config.ORG3_PEER_0_URL); Peer peer1_org3 = fabricClient.getInstance().newPeer(Config.ORG3_PEER_1, Config.ORG3_PEER_1_URL); trace_channel.joinPeer(peer0_org1); trace_channel.joinPeer(peer1_org1); //Join peers and order to the channel // producer_channel.joinPeer(peer0_org1); // producer_channel.joinPeer(peer1_org1); // producer_channel.addOrderer(orderer); // factory_channel.joinPeer(peer0_org1); // factory_channel.joinPeer(peer1_org1); // factory_channel.addOrderer(orderer); // sale_channel.joinPeer(peer0_org1); // sale_channel.joinPeer(peer1_org1); // sale_channel.addOrderer(orderer); // trace_channel.initialize(); fabricClient.getInstance().setUserContext(org2Admin); trace_channel.joinPeer(peer0_org2); trace_channel.joinPeer(peer1_org2); // factory_channel = fabricClient.getInstance().getChannel(Config.FACTORY_CHANEL); // producer_channel.joinPeer(peer0_org2); // producer_channel.joinPeer(peer1_org2); // factory_channel.joinPeer(peer0_org2); // factory_channel.joinPeer(peer1_org2); // sale_channel.joinPeer(peer0_org2); // sale_channel.joinPeer(peer1_org2); fabricClient.getInstance().setUserContext(org3Admin); // sale_channel = fabricClient.getInstance().getChannel(Config.SALE_CHANEL); trace_channel.joinPeer(peer0_org3); trace_channel.joinPeer(peer1_org3); // producer_channel.joinPeer(peer0_org3); // producer_channel.joinPeer(peer1_org3); // factory_channel.joinPeer(peer0_org3); // factory_channel.joinPeer(peer1_org3); // sale_channel.joinPeer(peer0_org3); // sale_channel.joinPeer(peer1_org3); LogUtil.channelLog(trace_channel); // LogUtil.channelLog(producer_channel); // LogUtil.channelLog(factory_channel); // LogUtil.channelLog(sale_channel); } catch (Exception e) { e.printStackTrace(); } } }
924598ce769869e0030bf247ae0104bebb113454
5,348
java
Java
gemfire-examples/src/main/java/quickstart/FixedPartitionPeer1.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
38
2016-01-04T01:31:40.000Z
2020-04-07T06:35:36.000Z
gemfire-examples/src/main/java/quickstart/FixedPartitionPeer1.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
261
2016-01-07T09:14:26.000Z
2019-12-05T10:15:56.000Z
gemfire-examples/src/main/java/quickstart/FixedPartitionPeer1.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
22
2016-03-09T05:47:09.000Z
2020-04-02T17:55:30.000Z
38.753623
127
0.705684
1,003,443
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package quickstart; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.CacheFactory; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.FixedPartitionAttributes; import com.gemstone.gemfire.cache.partition.PartitionRegionHelper; /** * This example shows basic Region operations on a fixed partitioned region, * which has data partitions on two VMs. Fixed partitions "Q1" and "Q2" are * defined on primary and secondary on one VM and vice-versa on other VM. The * region is configured to create one extra copy of each data entry. The copies * are placed on different VMs, so when one VM shuts down, no data is lost. * Operations proceed normally on the other VM. * <p> * Fixed partition "Q1" is associated with data of following months: Jan, Feb, Mar, Apr, May, Jun * <p> * Fixed partition "Q2" is associated with data of following months: Jul, Aug, Sep, Oct, Nov, Dec * <p> * Please refer to the quickstart guide for instructions on how to run this * example. * <p> * * @author GemStone Systems, Inc. */ public class FixedPartitionPeer1 { public static final String EXAMPLE_REGION_NAME = "exampleRegion"; private final BufferedReader stdinReader; public FixedPartitionPeer1() { this.stdinReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) throws Exception { new FixedPartitionPeer1().run(); } public void run() throws Exception { writeToStdout("This Peer defined is a partitioned region having primary partition named \"Q1\" with 6 number of buckets"); writeToStdout("This Peer have the data for the following months: JAN, FEB, MAR, APR, MAY, JUN"); writeNewLine(); writeToStdout("Connecting to the distributed system and creating the cache... "); // Create the cache which causes the cache-xml-file to be parsed Cache cache = new CacheFactory() .set("name", "FixedPartitionPeer1") .set("cache-xml-file", "xml/FixedPartitionPeer1.xml") .create(); writeNewLine(); // Get the exampleRegion Region<Date, String> exampleRegion = cache.getRegion(EXAMPLE_REGION_NAME); writeToStdout("Example region \"" + exampleRegion.getFullPath() + "\" created in cache."); writeNewLine(); writeToStdout("Example region \"" + exampleRegion.getFullPath() + "\" is having following Fixed Partition Attributes :" ); List<FixedPartitionAttributes> fpas = exampleRegion.getAttributes().getPartitionAttributes().getFixedPartitionAttributes(); for (FixedPartitionAttributes fpa : fpas){ writeToStdout(" "+ fpa.toString()); } writeNewLine(); writeToStdout("Please start other peer and then press \"Enter\" to continue."); stdinReader.readLine(); writeToStdout("Checking size of the region, after put from other Peer"); writeToStdout("exampleRegion size = " + exampleRegion.size()); writeToStdout("Please press \"Enter\" to see local primary data"); stdinReader.readLine(); Region<Date, String> localPrimaryData = PartitionRegionHelper.getLocalPrimaryData(exampleRegion); Set<Map.Entry<Date, String>> localPrimaryDataSet = localPrimaryData.entrySet(); writeToStdout("Key Value"); for(Map.Entry<Date, String> entry : localPrimaryDataSet){ writeToStdout(entry.getKey() + " " + entry.getValue()); } writeToStdout("Local Primary Data size = " + localPrimaryData.size()); writeToStdout("Please press \"Enter\" to see local(primary as well as secondary) data"); stdinReader.readLine(); Region<Date,String> localData = PartitionRegionHelper.getLocalData(exampleRegion); Set<Map.Entry<Date, String>> localdataSet = localData.entrySet(); writeToStdout("Key Value"); for (Map.Entry<Date, String> entry : localdataSet) { writeToStdout(entry.getKey() + " " + entry.getValue()); } writeToStdout("Local Primary as well as Secondary Data size = " + localData.size()); writeToStdout("Please check the data on other peer"); stdinReader.readLine(); writeToStdout("Please press \"Enter\" to close cache for this peer"); stdinReader.readLine(); System.out.println("Closing the cache and disconnecting."); cache.close(); } private static void writeToStdout(String msg) { System.out.println(msg); } private static void writeNewLine() { System.out.println(); } }
924598e845e67b7542c663e51d8104d42c949b20
201
java
Java
dev/scape/src/treeton/scape/ScapeUniLabel.java
IlyaGusev/Treeton
fb1b85c138fd7aa31f4a78703b31cde364952b69
[ "Apache-2.0" ]
null
null
null
dev/scape/src/treeton/scape/ScapeUniLabel.java
IlyaGusev/Treeton
fb1b85c138fd7aa31f4a78703b31cde364952b69
[ "Apache-2.0" ]
null
null
null
dev/scape/src/treeton/scape/ScapeUniLabel.java
IlyaGusev/Treeton
fb1b85c138fd7aa31f4a78703b31cde364952b69
[ "Apache-2.0" ]
2
2017-09-26T11:37:45.000Z
2017-09-26T11:55:07.000Z
14.357143
40
0.626866
1,003,444
/* * Copyright Anatoly Starostin (c) 2017. */ package treeton.scape; public class ScapeUniLabel { private static long label = 0; public static long get() { return label++; } }
924599891bc37dab92cea503329128d705ea03ef
13,416
java
Java
Calculadora/app/src/main/java/com/mmb/calculadora/Principal.java
MMB7/CalculadoraAndroid
7d53f25874d1e4c037c6a224ad46c50e41ed5091
[ "MIT" ]
1
2018-10-17T12:39:17.000Z
2018-10-17T12:39:17.000Z
Calculadora/app/src/main/java/com/mmb/calculadora/Principal.java
MMB7/CalculadoraAndroid
7d53f25874d1e4c037c6a224ad46c50e41ed5091
[ "MIT" ]
null
null
null
Calculadora/app/src/main/java/com/mmb/calculadora/Principal.java
MMB7/CalculadoraAndroid
7d53f25874d1e4c037c6a224ad46c50e41ed5091
[ "MIT" ]
null
null
null
36.161725
116
0.569171
1,003,445
package com.mmb.calculadora; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Principal extends AppCompatActivity { Button btn0,btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btnDivision,btnMultiplicar,btnBorrarTodo,btnDEL,btnOFF; Button btnSuma,btnResta,btnRaiz, btnPorciento,btnParentesis,btnResultado,btnPunto,btnExponente,btnFactorial; Button btnSeno,btnCoseno,btnTangente,btnCosecante,btnSecante,btnCotangente; EditText etOperacion; int contadorParentesis,parentesisUsados; private boolean contenerAngulos=false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_principal); //Botones numeros btn0=findViewById(R.id.btn0); btn1=findViewById(R.id.btn1); btn2=findViewById(R.id.btn2); btn3=findViewById(R.id.btn3); btn4=findViewById(R.id.btn4); btn5=findViewById(R.id.btn5); btn6=findViewById(R.id.btn6); btn7=findViewById(R.id.btn7); btn8=findViewById(R.id.btn8); btn9=findViewById(R.id.btn9); //Botones operaciones btnSuma=findViewById(R.id.btnSuma); btnResta=findViewById(R.id.btnRestar); btnMultiplicar=findViewById(R.id.btnMultiplicar); btnDivision=findViewById(R.id.btnDivision); btnRaiz=findViewById(R.id.btnRaiz); btnPorciento=findViewById(R.id.btnPorcentaje); btnParentesis=findViewById(R.id.btnParentesis); btnPunto=findViewById(R.id.btnPunto); btnFactorial=findViewById(R.id.btnFactorial); btnExponente=findViewById(R.id.btnExponente); btnSeno=findViewById(R.id.btnSeno); btnCoseno=findViewById(R.id.btnCoseno); btnTangente=findViewById(R.id.btnTangente); btnCotangente=findViewById(R.id.btnCotangente); btnSecante=findViewById(R.id.btnSecante); btnCosecante=findViewById(R.id.btnCosecante); //Botones funciones btnBorrarTodo=findViewById(R.id.btnBorrarTodo); btnDEL=findViewById(R.id.btnDel); btnResultado=findViewById(R.id.btnResultado); btnOFF=findViewById(R.id.btnOFF); //Mostrar etOperacion=findViewById(R.id.etOperacion); etOperacion.setInputType(InputType.TYPE_NULL); //Añadir numeros pulsados btn0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btn0.getText().toString()); } }); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btn1.getText().toString()); } }); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btn2.getText().toString()); } }); btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btn3.getText().toString()); } }); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btn4.getText().toString()); } }); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btn5.getText().toString()); } }); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btn6.getText().toString()); } }); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btn7.getText().toString()); } }); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btn8.getText().toString()); } }); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btn9.getText().toString()); } }); //Añadir operadores pulsados btnSuma.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btnSuma.getText().toString()); } }); btnResta.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btnResta.getText().toString()); } }); btnMultiplicar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btnMultiplicar.getText().toString()); } }); btnDivision.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btnDivision.getText().toString()); } }); btnRaiz.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btnRaiz.getText().toString()); } }); btnPorciento.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btnPorciento.getText().toString()); } }); btnPunto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append(btnPunto.getText().toString()); } }); btnCoseno.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append("cos("); contadorParentesis=1; contenerAngulos=true; } }); btnSeno.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append("sin("); contadorParentesis=1; contenerAngulos=true; } }); btnTangente.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append("tan("); contadorParentesis=1; contenerAngulos=true; } }); btnCosecante.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append("csc("); contadorParentesis=1; contenerAngulos=true; } }); btnSecante.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append("sec("); contadorParentesis=1; contenerAngulos=true; } }); btnCotangente.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append("ctg("); contadorParentesis=1; contenerAngulos=true; } }); btnFactorial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append("!"); } }); btnExponente.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.append("^("); contadorParentesis=1; } }); //Añadir parentesis btnParentesis.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(contadorParentesis==0) { contadorParentesis = 1; etOperacion.append("("); }else if(contadorParentesis==1) { etOperacion.append(")"); contadorParentesis=0; parentesisUsados+=1; } } }); //Borrar btnBorrarTodo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etOperacion.setText(""); contadorParentesis=0; parentesisUsados=0; } }); btnDEL.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int longitudOperacion=etOperacion.length(); String nuevo=etOperacion.getText().toString().substring(0,(longitudOperacion-1)); etOperacion.setText(nuevo); } }); btnOFF.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.exit(0); } }); //Resultado btnResultado.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(contenerAngulos==true){ etOperacion.setText(angulos()); }else if(etOperacion.getText().toString().contains("!")){ etOperacion.setText(factorial(etOperacion.getText().toString())); }else if(etOperacion.getText().toString().contains("√")) { etOperacion.setText(raiz(etOperacion.getText().toString())); }else if(etOperacion.getText().toString().contains("^(")){ etOperacion.setText(exponente(etOperacion.getText().toString())); }else{etOperacion.setText(numeros());} } }); } public String numeros() { String devolver=null; try { ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino"); Object resultado = engine.eval(etOperacion.getText().toString()); devolver=String.valueOf(resultado); } catch (ScriptException e) { devolver="Error"; } return devolver; } public String angulos(){ String resultado = null; try{ String texto=etOperacion.getText().toString(); int posPrimParentesis=texto.indexOf("("); int posSecParentesis=texto.indexOf(")"); Double numero=Double.parseDouble(texto.substring(posPrimParentesis+1,posSecParentesis-1)); if(texto.contains("sin")){resultado=String.valueOf(Math.sin(numero));} if(texto.contains("cos")){resultado=String.valueOf(Math.cos(numero));} if(texto.contains("tan")){resultado=String.valueOf(Math.tan(numero));} if(texto.contains("csc")){resultado=String.valueOf(1/Math.sin(numero));} if(texto.contains("sec")){resultado=String.valueOf(1/Math.cos(numero));} if(texto.contains("ctg")){resultado=String.valueOf(1/Math.tan(numero));} contadorParentesis=0; contenerAngulos=false; }catch (Exception ex){ resultado="Error"; } return resultado; } public String factorial(String texto){ String devolver=null; try { int posFact = texto.indexOf("!"); Double numero = Double.parseDouble(texto.substring(0, posFact)); Double resultado = 1.0; for (int i = 1; i <= numero; i++) { resultado *= i; } devolver=String.valueOf(resultado); }catch(Exception ex){ devolver="Error"; } return devolver; } public String raiz(String texto){ String resultado; try { Double numero = Double.parseDouble(texto.substring(1, texto.length())); resultado = String.valueOf(Math.sqrt(numero)); }catch (Exception ex){ resultado="Error"; } return resultado; } public String exponente(String texto){ String devolver=null; try { int posExp = texto.indexOf("^"); contadorParentesis = 0; Double numero1 = Double.parseDouble(texto.substring(0, posExp - 1)); Double numero2 = Double.parseDouble(texto.substring(posExp + 2, texto.length())); Double resultado = Math.pow(numero1, numero2); devolver=String.valueOf(resultado); }catch (Exception ex){ devolver="Error"; } return devolver; } }
92459a4dc3cb3b5d19d36a576548ecd08a98fa76
8,444
java
Java
export/utils/org/eclipse/cdt/utils/xcoff/parser/XCOFFBinaryObject.java
seemoo-lab/polypyus_pdom
c08d06d3268578566978697d0560c34f3b224b55
[ "Apache-2.0" ]
null
null
null
export/utils/org/eclipse/cdt/utils/xcoff/parser/XCOFFBinaryObject.java
seemoo-lab/polypyus_pdom
c08d06d3268578566978697d0560c34f3b224b55
[ "Apache-2.0" ]
null
null
null
export/utils/org/eclipse/cdt/utils/xcoff/parser/XCOFFBinaryObject.java
seemoo-lab/polypyus_pdom
c08d06d3268578566978697d0560c34f3b224b55
[ "Apache-2.0" ]
null
null
null
25.82263
104
0.66118
1,003,446
/******************************************************************************* * Copyright (c) 2004, 2015 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.cdt.utils.xcoff.parser; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.cdt.core.IAddress; import org.eclipse.cdt.core.IAddressFactory; import org.eclipse.cdt.core.IBinaryParser; import org.eclipse.cdt.core.IBinaryParser.IBinaryFile; import org.eclipse.cdt.core.IBinaryParser.ISymbol; import org.eclipse.cdt.utils.Addr2line; import org.eclipse.cdt.utils.Addr32; import org.eclipse.cdt.utils.Addr32Factory; import org.eclipse.cdt.utils.BinaryObjectAdapter; import org.eclipse.cdt.utils.CPPFilt; import org.eclipse.cdt.utils.IGnuToolFactory; import org.eclipse.cdt.utils.Objdump; import org.eclipse.cdt.utils.xcoff.AR; import org.eclipse.cdt.utils.xcoff.XCoff32; import org.eclipse.cdt.utils.xcoff.XCoff32.Symbol; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; /** * Binary file in AIX XCOFF32 format * * @author vhirsl */ public class XCOFFBinaryObject extends BinaryObjectAdapter { Addr2line addr2line; BinaryObjectInfo info; ISymbol[] symbols; long starttime; private AR.MemberHeader header; private IAddressFactory addressFactory; /** * @param parser * @param path * @param type */ public XCOFFBinaryObject(IBinaryParser parser, IPath path, int type) { super(parser, path, type); } /** * @param parser * @param path * @param header */ public XCOFFBinaryObject(IBinaryParser parser, IPath path, AR.MemberHeader header) { super(parser, path, IBinaryFile.OBJECT); this.header = header; } /* * (non-Javadoc) * * @see org.eclipse.cdt.core.IBinaryParser.IBinaryObject#getSymbols() */ @Override public ISymbol[] getSymbols() { if (hasChanged() || symbols == null) { try { loadAll(); } catch (IOException e) { symbols = NO_SYMBOLS; } } return symbols; } /* * (non-Javadoc) * * @see org.eclipse.cdt.utils.BinaryObjectAdapter#getBinaryObjectInfo() */ @Override protected BinaryObjectInfo getBinaryObjectInfo() { if (hasChanged() || info == null) { try { loadInfo(); } catch (IOException e) { info = new BinaryObjectInfo(); } } return info; } /* (non-Javadoc) * @see org.eclipse.cdt.utils.BinaryObjectAdapter#getName() */ @Override public String getName() { if (header != null) { return header.getObjectName(); } return super.getName(); } /** * @throws IOException * @see org.eclipse.cdt.core.IBinaryParser.IBinaryFile#getContents() */ @Override public InputStream getContents() throws IOException { InputStream stream = null; if (getPath() != null && header != null) { return new ByteArrayInputStream(header.getObjectData()); } Objdump objdump = getObjdump(); if (objdump != null) { byte[] contents = objdump.getOutput(); stream = new ByteArrayInputStream(contents); } if (stream == null) { stream = super.getContents(); } return stream; } protected XCoff32 getXCoff32() throws IOException { if (header != null) { return new XCoff32(getPath().toOSString(), header.getObjectDataOffset()); } return new XCoff32(getPath().toOSString()); } protected void loadAll() throws IOException { XCoff32 xcoff = null; try { xcoff = getXCoff32(); loadInfo(xcoff); loadSymbols(xcoff); } finally { if (xcoff != null) { xcoff.dispose(); } } } protected void loadInfo() throws IOException { XCoff32 xcoff = null; try { xcoff = getXCoff32(); loadInfo(xcoff); } finally { if (xcoff != null) { xcoff.dispose(); } } } protected void loadInfo(XCoff32 xcoff) throws IOException { info = new BinaryObjectInfo(); XCoff32.Attribute attribute = xcoff.getAttributes(); info.isLittleEndian = attribute.isLittleEndian(); info.hasDebug = attribute.hasDebug(); info.cpu = attribute.getCPU(); } protected void loadSymbols(XCoff32 xcoff) throws IOException { ArrayList<XCoffSymbol> list = new ArrayList<XCoffSymbol>(); XCoff32.Symbol[] peSyms = xcoff.getSymbols(); byte[] table = xcoff.getStringTable(); addSymbols(peSyms, table, list); symbols = list.toArray(NO_SYMBOLS); Arrays.sort(symbols); list.clear(); } protected void addSymbols(XCoff32.Symbol[] peSyms, byte[] table, List<XCoffSymbol> list) { CPPFilt cppfilt = getCPPFilt(); Addr2line addr2line = getAddr2line(false); for (Symbol peSym : peSyms) { if (peSym.isFunction() || peSym.isVariable() ) { String name = peSym.getName(table); if (name == null || name.trim().length() == 0 || !Character.isJavaIdentifierStart(name.charAt(0))) { continue; } int type = peSym.isFunction() ? ISymbol.FUNCTION : ISymbol.VARIABLE; IAddress addr = new Addr32(peSym.n_value); int size = 4; if (cppfilt != null) { try { name = cppfilt.getFunction(name); } catch (IOException e1) { cppfilt = null; } } if (addr2line != null) { try { String filename = addr2line.getFileName(addr); // Addr2line returns the funny "??" when it can not find // the file. if (filename != null && filename.equals("??")) { //$NON-NLS-1$ filename = null; } IPath file = filename != null ? new Path(filename) : Path.EMPTY; int startLine = addr2line.getLineNumber(addr); int endLine = addr2line.getLineNumber(addr.add(size - 1)); list.add(new XCoffSymbol(this, name, type, addr, size, file, startLine, endLine)); } catch (IOException e) { addr2line = null; // the symbol still needs to be added list.add(new XCoffSymbol(this, name, type, addr, size)); } } else { list.add(new XCoffSymbol(this, name, type, addr, size)); } } } if (cppfilt != null) { cppfilt.dispose(); } if (addr2line != null) { addr2line.dispose(); } } public Addr2line getAddr2line(boolean autodisposing) { if (!autodisposing) { return getAddr2line(); } if (addr2line == null) { addr2line = getAddr2line(); if (addr2line != null) { starttime = System.currentTimeMillis(); Runnable worker = new Runnable() { @Override public void run() { long diff = System.currentTimeMillis() - starttime; while (diff < 10000) { try { Thread.sleep(10000); } catch (InterruptedException e) { break; } diff = System.currentTimeMillis() - starttime; } stopAddr2Line(); } }; new Thread(worker, "Addr2line Reaper").start(); //$NON-NLS-1$ } } else { starttime = System.currentTimeMillis(); } return addr2line; } synchronized void stopAddr2Line() { if (addr2line != null) { addr2line.dispose(); } addr2line = null; } /** * @return */ private Addr2line getAddr2line() { IGnuToolFactory factory = getBinaryParser().getAdapter(IGnuToolFactory.class); if (factory != null) { return factory.getAddr2line(getPath()); } return null; } private CPPFilt getCPPFilt() { IGnuToolFactory factory = getBinaryParser().getAdapter(IGnuToolFactory.class); if (factory != null) { return factory.getCPPFilt(); } return null; } private Objdump getObjdump() { IGnuToolFactory factory = getBinaryParser().getAdapter(IGnuToolFactory.class); if (factory != null) { return factory.getObjdump(getPath()); } return null; } @Override @SuppressWarnings("unchecked") public <T> T getAdapter(Class<T> adapter) { if (adapter == Addr2line.class) { return (T) getAddr2line(); } else if (adapter == CPPFilt.class) { return (T) getCPPFilt(); } return super.getAdapter(adapter); } /* (non-Javadoc) * @see org.eclipse.cdt.utils.BinaryObjectAdapter#getAddressFactory() */ @Override public IAddressFactory getAddressFactory() { if (addressFactory == null) { addressFactory = new Addr32Factory(); } return addressFactory; } }
92459ad02356bec81a26b460dd671537e8e9cea2
693
java
Java
src/main/java/com/rocko/test/MongoData.java
rockotseng/mongo-data-annotation
ffbade4a0713f35f310639ef0a230406e560fe9d
[ "MIT" ]
null
null
null
src/main/java/com/rocko/test/MongoData.java
rockotseng/mongo-data-annotation
ffbade4a0713f35f310639ef0a230406e560fe9d
[ "MIT" ]
null
null
null
src/main/java/com/rocko/test/MongoData.java
rockotseng/mongo-data-annotation
ffbade4a0713f35f310639ef0a230406e560fe9d
[ "MIT" ]
null
null
null
23.896552
52
0.76912
1,003,447
package com.rocko.test; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Repeatable(MongoDataGroup.class) public @interface MongoData { @AliasFor("locations") String[] value() default {}; @AliasFor("value") String[] locations() default {}; String mapper() default ""; }
92459af755ad3669d032c0361063187228c55e12
15,065
java
Java
src/main/java/xyz/issc/daca/Aconn.java
lingfliu/daca-core
2e25d5d9b2b0e640ee68121068dd878f23ef99fe
[ "Apache-2.0" ]
null
null
null
src/main/java/xyz/issc/daca/Aconn.java
lingfliu/daca-core
2e25d5d9b2b0e640ee68121068dd878f23ef99fe
[ "Apache-2.0" ]
null
null
null
src/main/java/xyz/issc/daca/Aconn.java
lingfliu/daca-core
2e25d5d9b2b0e640ee68121068dd878f23ef99fe
[ "Apache-2.0" ]
null
null
null
33.477778
101
0.468238
1,003,448
package xyz.issc.daca; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xyz.issc.daca.spec.CodeBook; import xyz.issc.daca.spec.FlowSpec; import xyz.issc.daca.spec.Routine; import xyz.issc.daca.spec.RoutineBook; import xyz.issc.daca.utils.ArrayHelper; import xyz.issc.daca.utils.ByteParser; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * connectivity state entity to indicate the */ @Data public class Aconn { Logger log = LoggerFactory.getLogger("appconn"); QosAdapter qosAdapter; public interface AppConnListener { void onFeed(Procedure proc, Flow flow, FlowSpec flowSpec); void onFinish(Procedure proc); void onTimeout(Procedure proc); void onStateChanged(int state); } public static final int STATE_DISCONNECTED = 1; public static final int STATE_CONNECTED = 2; int state; CodeBook codeBook; RoutineBook routineBook; Coder coder; NioChannel channel; AppConnListener appConnListener; long lastReceivedAt; int filterMode; Map<String, Svo> creds; List<String> filtered; Lock lck = new ReentrantLock(); ConcurrentLinkedQueue<FullMessage> sendMessageQueue; public void send(FullMessage txMsg) { try { byte[] encoded = coder.encode(txMsg); if (encoded != null) { channel.send(encoded); } } catch (ByteParser.ByteArrayOverflowException e) { e.printStackTrace(); } } Map<String, Procedure> activeProcedures;//<id, pro> Map<String, Procedure> filters; //<id, pro> Map<String, Procedure> retained; //<id, pro> //load autostart flows inited by downlinks (from host to client) public void loadAutostartFlows() { for (String key : routineBook.getRoutines().keySet()) { Routine routine = routineBook.getRoutines().get(key); if (routine.isAutostart()) { Procedure procedure = new Procedure(routine, this); activeProcedures.put(procedure.getId(), procedure); if(procedure.filterMode == Routine.MODE_FILTER) { filters.put(procedure.getId(), procedure); } } } } public void update(Flow flow) { FullMessage msg = flow.getMessage(); if (routineBook.isShot(msg)) { //shot messages (no routine) lastReceivedAt = System.currentTimeMillis(); qosAdapter.restore(null); } else { //1. active procedures Procedure proc = matchAndForward(flow); if (proc != null) { if (proc.state == Procedure.STATE_FINISHED) { if (appConnListener != null) { appConnListener.onFinish(proc); } if (proc.retainMode == Routine.RETAIN_MODE_REPLACE) { retained.put(proc.getId(), proc); } else if (proc.retainMode == Routine.RETAIN_MODE_ALWAYS) { //lift creds from procedure to appconn for (String name : proc.creds.keySet()) { creds.put(name, proc.creds.get(name)); } } } else if (proc.state == Procedure.STATE_TIMEOUT) { if (appConnListener != null) { appConnListener.onTimeout(proc); } } else if (proc.state == Procedure.STATE_PENDING) { //skip } else if (proc.state == Procedure.STATE_FLOWING) { //check timeout if (proc.isTimeout()) { qosAdapter.damage(proc); } FlowSpec flowSpec = proc.feedFlowSpec; if (appConnListener != null) { appConnListener.onFeed(proc, flow, flowSpec); } } else { //skip } } else { Routine routine = routineBook.matchRoutineInitial(msg, flow.getDirection()); Procedure proc2 = new Procedure(routine, this); //3. recycle procedures of branching proc = recycle(flow, proc2); FlowSpec spec2 = proc2.forward(flow); if (proc != null) { //previous procedures are recycled addActives(proc2); lastReceivedAt = System.currentTimeMillis(); if (appConnListener != null) { appConnListener.onFeed(proc, flow, spec2); } } else { //4. filtering flow = filter(flow); if (flow != null) { //5. new procedures Procedure proc3 = new Procedure(routine, this); FlowSpec spec3 = proc3.forward(flow); addActives(proc3); lastReceivedAt = System.currentTimeMillis(); if (spec3 == null) { if (proc3.state == Procedure.STATE_FINISHED) { if (appConnListener != null) { appConnListener.onFinish(proc3); } } else if (proc3.state == Procedure.STATE_TIMEOUT) { if (appConnListener != null) { appConnListener.onTimeout(proc3); } } } else { if (appConnListener != null) { appConnListener.onFeed(proc3, flow, spec3); } } } else { log.info("flow blocked: " + flow.getMessage().getName()); } } } } } Flow composeFlow(FullMessage msg, int direction) { Flow flow = new Flow(); flow.setFormedAt(System.currentTimeMillis()); flow.setDirection(direction); flow.setMessage(msg); return flow; } /** * uplink (from remote to host) * @param bytes */ public void feedUplink(byte[] bytes) { coder.put(bytes); while (true) { FullMessage msg = coder.decode(); if (msg == null) { break; } else { Flow flow = composeFlow(msg, Flow.UPLINK); //uplink update(flow); } } } /** * feed conn for downlink (host to remote) * @param msg */ public void feedDownlink(FullMessage msg) { Flow flow = composeFlow(msg, Flow.DOWNLINK); send(msg); update(flow); } Procedure matchAndForward(Flow flow) { //1. match active procedures for (String id : activeProcedures.keySet()) { Procedure proc = activeProcedures.get(id); if (proc.feedFlowSpec.check(flow) ) { proc.forward(flow); return proc; } else { FlowSpec flowSpec = proc.skip(flow); if (flowSpec != null) { return proc; } } } return null; } Procedure recycle(Flow flow, Procedure proc) { for (String id : retained.keySet()) { Procedure retainedProc = retained.get(id); if (ArrayHelper.contain(retainedProc.routine.getRecyclables(), proc.routine.getName())) { //transfer creds from retained to new proc for (String name : retainedProc.creds.keySet()) { proc.creds.put(name, retainedProc.creds.get(name)); } return retainedProc; } } return null; } Flow filter(Flow flow) { //global filtering if (routineBook.getFilterMode() == Routine.FILTER_BLOCK) { if (ArrayHelper.contain(filtered, flow.message.name)) { boolean hasCreds = true; for (String name : creds.keySet()) { if (!flow.contain(name, creds.get(name))) { hasCreds = false; break; } } if (!hasCreds) { return null; } else { List<Procedure> matchFilters = matchFilter(filters, flow); if (matchFilters == null || matchFilters.size() == 0) { return null; } else { boolean gHasCreds = true; for (Procedure proc : matchFilters) { boolean hasCreds2 = true; for (String name : proc.creds.keySet()) { Svo ref = proc.creds.get(name); if (!flow.contain(name, ref)) { hasCreds2 = false; break; } } if (!hasCreds2) { gHasCreds = false; break; } } if (!gHasCreds) { return null; } else { return flow; } } } } else { return null; } } else if (routineBook.getFilterMode() == Routine.FILTER_PASS) { if (ArrayHelper.contain(filtered, flow.message.name)) { boolean hasCreds = true; for (String name : creds.keySet()) { if (!flow.contain(name, creds.get(name))) { hasCreds = false; break; } } if (!hasCreds) { return null; } } //pass the flow to procedure filters List<Procedure> matchFilters = matchFilter(filters, flow); if (matchFilters == null || matchFilters.size() == 0) { return flow; } else { boolean gHasCreds = true; for (Procedure proc : matchFilters) { boolean hasCreds = true; for (String name : proc.creds.keySet()) { Svo ref = proc.creds.get(name); if (!flow.contain(name, ref)) { hasCreds = false; break; } } if (!hasCreds) { gHasCreds = false; break; } } if (!gHasCreds) { return null; } else { return flow; } } } else { return flow; } } public List<Procedure> matchFilter(Map<String, Procedure> filters, Flow flow) { if (filters == null || filters.size() == 0) { return null; } List<Procedure> matched = new ArrayList<>(); for (String id : filters.keySet()) { Procedure proc = filters.get(id); Routine routine = routineBook.getRoutines().get(id); if (routine.getFilterMode() == Routine.FILTER_NONE) { continue; } String flowName = flow.message.name; if (ArrayHelper.contain(routine.getFiltered(), flowName)) { matched.add(proc); } } return matched; } public void addActives(Procedure procedure) { activeProcedures.put(procedure.id, procedure); } public void refreshProcedures() { for (String id : activeProcedures.keySet()) { Procedure pro = activeProcedures.get(id); if (pro.getState() == Procedure.STATE_FINISHED) { activeProcedures.remove(pro.id); } else if (pro.getState() == Procedure.STATE_TIMEOUT) { activeProcedures.remove(pro.id); } else { //for pending & flowing states, update timeout determining here if (pro.isTimeout()) { pro.setState(Procedure.STATE_TIMEOUT); activeProcedures.remove(pro.id); } } } if (qosAdapter.getMetric() < 0) { log.info("qos low, closing conn: " + channel.getAddr()); close(); } } public void forwardDownlink() { for (String key : activeProcedures.keySet()) { Procedure proc = activeProcedures.get(key); //using state flags to prevent re-forwarding if (proc.state == Procedure.STATE_PENDING) { // log.info("state pending"); continue; } FlowSpec flowSpec = proc.getFeedFlowSpec(); if (flowSpec.getDirection() == Flow.DOWNLINK) { // log.info("state flowing to downlink"); if (appConnListener != null) { appConnListener.onFeed(proc, proc.getPrevFlow(), flowSpec); } } } } /** * when closed, the conn will not be used again */ public void close() { channel.close(); if (state != STATE_DISCONNECTED) { state = STATE_DISCONNECTED; if (appConnListener != null) { appConnListener.onStateChanged(state); } } } public Aconn(CodeBook codeBook, RoutineBook routineBook, QosAdapter qosAdapter) { this.codeBook = codeBook; this.routineBook = routineBook; coder = new Coder(codeBook, codeBook.suggestBuffLen()); this.qosAdapter = qosAdapter; sendMessageQueue = new ConcurrentLinkedQueue<>(); activeProcedures = new ConcurrentHashMap<>(); filters = new ConcurrentHashMap<>(); retained = new ConcurrentHashMap<>(); } }
92459b2ee78e693616bf37ecddcc960d8ec99f3f
858
java
Java
solution/src/test/java/chisw/appmanager/ResultPageHelper.java
Tarrest/five_wiki
c2a49b527325c8d3bcbbd58f3abcbdfa1993accd
[ "Apache-2.0" ]
null
null
null
solution/src/test/java/chisw/appmanager/ResultPageHelper.java
Tarrest/five_wiki
c2a49b527325c8d3bcbbd58f3abcbdfa1993accd
[ "Apache-2.0" ]
null
null
null
solution/src/test/java/chisw/appmanager/ResultPageHelper.java
Tarrest/five_wiki
c2a49b527325c8d3bcbbd58f3abcbdfa1993accd
[ "Apache-2.0" ]
null
null
null
26.8125
50
0.68648
1,003,449
package chisw.appmanager; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import java.util.ArrayList; import java.util.List; public class ResultPageHelper extends BaseHelper { public ResultPageHelper(WebDriver driver) { super(driver); PageFactory.initElements(driver, this); } @FindBy(how = How.CSS, using = "cite.iUh30") private List<WebElement> resultLinks; public List<String> getSearchResultsList() { List<String> results = new ArrayList<>(); List<WebElement> links = resultLinks; for (WebElement link : links) { String text = link.getText(); results.add(text); } return results; } }
92459bb150d80829a6b49b4e90cfee3a58273f30
1,905
java
Java
src/main/java/com/esfm/modules/survey/controller/SurveyShceduleController.java
sturgeons/esfm-server
5bd32f2134b0d3a2c07430c763b646c4cf5f76df
[ "MulanPSL-1.0" ]
null
null
null
src/main/java/com/esfm/modules/survey/controller/SurveyShceduleController.java
sturgeons/esfm-server
5bd32f2134b0d3a2c07430c763b646c4cf5f76df
[ "MulanPSL-1.0" ]
null
null
null
src/main/java/com/esfm/modules/survey/controller/SurveyShceduleController.java
sturgeons/esfm-server
5bd32f2134b0d3a2c07430c763b646c4cf5f76df
[ "MulanPSL-1.0" ]
null
null
null
26.830986
98
0.696588
1,003,450
package com.esfm.modules.survey.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.esfm.extension.api.ApiController; import com.esfm.extension.api.R; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.esfm.modules.survey.entity.SurveyShcedule; import com.esfm.modules.survey.service.SurveyShceduleService; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.io.Serializable; import java.util.List; /** * 问卷调查计划(SurveyShcedule)表控制层 * * @author makejava * @since 2021-10-31 22:49:45 */ @RestController @RequestMapping("surveyShcedule") public class SurveyShceduleController extends ApiController { /** * 服务对象 */ @Resource private SurveyShceduleService surveyShceduleService; /** * 分页查询所有数据 */ @GetMapping(value = "list") public R<?> selectAll(Page<SurveyShcedule> page, SurveyShcedule surveyShcedule) { return success(this.surveyShceduleService.page(page, new QueryWrapper<>(surveyShcedule))); } /** * 通过主键查询单条数据 */ @GetMapping("id/{id}") public R<?> selectOne(@PathVariable Serializable id) { return success(this.surveyShceduleService.getById(id)); } /** * 新增数据 */ @PostMapping(value = "insert") public R<?> insert(@RequestBody SurveyShcedule surveyShcedule) { return success(this.surveyShceduleService.save(surveyShcedule)); } /** * 修改数据 */ @PutMapping(value = "update") public R<?> update(@RequestBody SurveyShcedule surveyShcedule) { return success(this.surveyShceduleService.updateById(surveyShcedule)); } /** * 删除数据 */ @DeleteMapping(value = "delete") public R<?> delete(@RequestParam("idList") List<Long> idList) { return success(this.surveyShceduleService.removeByIds(idList)); } }
92459c1ce78a4ff86fda2d1b4e6af8f3edf26ba9
407
java
Java
leetcode-java/src/classify/math/MaximumProductOfThreeNumbers.java
Gnatnaituy/leetcode
4f42c6a0206b43da38e24cc6c554f98403bc7521
[ "MIT" ]
null
null
null
leetcode-java/src/classify/math/MaximumProductOfThreeNumbers.java
Gnatnaituy/leetcode
4f42c6a0206b43da38e24cc6c554f98403bc7521
[ "MIT" ]
null
null
null
leetcode-java/src/classify/math/MaximumProductOfThreeNumbers.java
Gnatnaituy/leetcode
4f42c6a0206b43da38e24cc6c554f98403bc7521
[ "MIT" ]
null
null
null
19.380952
62
0.528256
1,003,451
package classify.math; import java.util.Arrays; public class MaximumProductOfThreeNumbers { /** * 14ms 52.36% * 37.9MB 99.37% */ public int maximumProduct(int[] nums) { Arrays.sort(nums); int len = nums.length; int a = nums[len - 1] * nums[len - 2] * nums[len - 3]; int b = nums[0] * nums[1] * nums[len - 1]; return a > b ? a : b; } }
92459c9be0caa3940718be6a5ecdd774ddc29727
935
java
Java
network/src/test/java/nl/jft/network/nio/NioConstantsTest.java
Just-Foosball-Things/Just-Foosball-Things
698c05fdcf409387a4e5846db97f5b628eeb5d70
[ "MIT" ]
2
2017-01-19T22:40:08.000Z
2017-01-27T22:53:15.000Z
network/src/test/java/nl/jft/network/nio/NioConstantsTest.java
Just-Foosball-Things/Just-Foosball-Things
698c05fdcf409387a4e5846db97f5b628eeb5d70
[ "MIT" ]
24
2017-01-19T16:50:16.000Z
2017-03-24T08:21:28.000Z
network/src/test/java/nl/jft/network/nio/NioConstantsTest.java
Just-Foosball-Things/Just-Foosball-Things
698c05fdcf409387a4e5846db97f5b628eeb5d70
[ "MIT" ]
null
null
null
27.5
96
0.706952
1,003,452
package nl.jft.network.nio; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * @author Lesley */ public class NioConstantsTest { @Rule public final ExpectedException expectedException = ExpectedException.none(); @Test public void construct_whenCalled_throwsException() throws Throwable { expectedException.expect(UnsupportedOperationException.class); try { Constructor<NioConstants> constructor = NioConstants.class.getDeclaredConstructor(); constructor.setAccessible(true); constructor.newInstance(); } catch (InstantiationException | NoSuchMethodException | IllegalAccessException e) { throw e; } catch (InvocationTargetException e) { throw e.getTargetException(); } } }
92459d4793130cede7ef5a2dda5e00a54cc581ba
1,249
java
Java
ContactManager/app/src/main/java/com/example/contactmanager/data/ContactRepositoryRoom.java
GeeTansher/AndroidDevelopmentAllApps
9705c57a470db69581b01bdd7d10ce7f8b5adfbd
[ "MIT" ]
null
null
null
ContactManager/app/src/main/java/com/example/contactmanager/data/ContactRepositoryRoom.java
GeeTansher/AndroidDevelopmentAllApps
9705c57a470db69581b01bdd7d10ce7f8b5adfbd
[ "MIT" ]
null
null
null
ContactManager/app/src/main/java/com/example/contactmanager/data/ContactRepositoryRoom.java
GeeTansher/AndroidDevelopmentAllApps
9705c57a470db69581b01bdd7d10ce7f8b5adfbd
[ "MIT" ]
null
null
null
28.386364
96
0.739792
1,003,453
package com.example.contactmanager.data; import android.app.Application; import androidx.lifecycle.LiveData; import com.example.contactmanager.model.ContactRoom; import com.example.contactmanager.util.ContactRoomDatabase; import java.util.List; public class ContactRepositoryRoom { private ContactDAO contactDAO; private LiveData<List<ContactRoom>> allContacts; public ContactRepositoryRoom(Application application) { ContactRoomDatabase db = ContactRoomDatabase.getDatabase(application); contactDAO = db.contactDAO(); allContacts = contactDAO.getAllContacts(); } public LiveData<List<ContactRoom>> getAllData(){ return allContacts; } public void insert(ContactRoom contactRoom){ ContactRoomDatabase.databaseWriteExecutor.execute(() -> contactDAO.insert(contactRoom)); } public LiveData<ContactRoom> get(int id){ return contactDAO.get(id); } public void update(ContactRoom contactRoom){ ContactRoomDatabase.databaseWriteExecutor.execute(() -> contactDAO.update(contactRoom)); } public void delete(ContactRoom contactRoom){ ContactRoomDatabase.databaseWriteExecutor.execute(() -> contactDAO.delete(contactRoom)); } }
92459d93c9810db7652045c5beee33c7cfdf0304
1,738
java
Java
app/src/main/java/com/shentu/paper/mvp/ui/widget/behavior/NavigationBehavior.java
walkthehorizon/MicroWallPager
47828dbae0e04331c46bee6773efbec331f3f167
[ "Apache-2.0" ]
3
2018-08-21T07:35:21.000Z
2021-03-29T08:48:03.000Z
app/src/main/java/com/shentu/paper/mvp/ui/widget/behavior/NavigationBehavior.java
walkthehorizon/MicroWallPager
47828dbae0e04331c46bee6773efbec331f3f167
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/shentu/paper/mvp/ui/widget/behavior/NavigationBehavior.java
walkthehorizon/MicroWallPager
47828dbae0e04331c46bee6773efbec331f3f167
[ "Apache-2.0" ]
1
2021-03-29T08:48:06.000Z
2021-03-29T08:48:06.000Z
39.5
201
0.749712
1,003,454
package com.shentu.paper.mvp.ui.widget.behavior; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.view.ViewCompat; public class NavigationBehavior extends CoordinatorLayout.Behavior<View> { public NavigationBehavior() { } public NavigationBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) { return dependency instanceof TextView; } // @Override // public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) { // return axes == ViewCompat.SCROLL_AXIS_VERTICAL && super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type); // } // // @Override // public void onNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) { // super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type); // child.offsetTopAndBottom(dyConsumed); // } @Override public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) { int offest = dependency.getTop() - child.getTop(); ViewCompat.offsetTopAndBottom(child,offest); return true; } }
92459dc0bd49da077b2142dfde2f570c51bc19a4
700
java
Java
src/test/java/seedu/expensela/ui/DateLabelMakerTest.java
BenFheng/main
81b84f70cf6f5332136a42987ba243dcf2129346
[ "MIT" ]
null
null
null
src/test/java/seedu/expensela/ui/DateLabelMakerTest.java
BenFheng/main
81b84f70cf6f5332136a42987ba243dcf2129346
[ "MIT" ]
84
2020-02-19T16:29:21.000Z
2020-04-15T16:16:25.000Z
src/test/java/seedu/expensela/ui/DateLabelMakerTest.java
BenFheng/main
81b84f70cf6f5332136a42987ba243dcf2129346
[ "MIT" ]
4
2020-02-17T13:50:07.000Z
2020-02-17T13:51:15.000Z
35
90
0.76
1,003,455
package seedu.expensela.ui; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static seedu.expensela.ui.DateLabelMaker.getColouredDateLabel; import org.junit.jupiter.api.Test; class DateLabelMakerTest { @Test public static void equals() { assertEquals(getColouredDateLabel("2020-01"), getColouredDateLabel("2020-01")); assertNotEquals(getColouredDateLabel("2020-01"), getColouredDateLabel("2020-02")); assertNotEquals(getColouredDateLabel("2020-01"), getColouredDateLabel("2021-01")); assertNotEquals(getColouredDateLabel("2020-01"), getColouredDateLabel("FOOD")); } }
92459dc5ab814d0a5a7c409656f96f569bb7f6f1
10,859
java
Java
spring-boot2-multi-redis-cache/src/main/java/com/zy/config/RedisConfig.java
njustwh2014/spring-boot-redis-guava-caffeine-cache
86b127b0441492758896d3cc9984774c209a5c53
[ "Apache-2.0" ]
136
2017-10-17T08:03:00.000Z
2022-02-21T18:35:52.000Z
spring-boot2-multi-redis-cache/src/main/java/com/zy/config/RedisConfig.java
njustwh2014/spring-boot-redis-guava-caffeine-cache
86b127b0441492758896d3cc9984774c209a5c53
[ "Apache-2.0" ]
2
2018-10-15T12:49:51.000Z
2020-07-22T09:17:04.000Z
spring-boot2-multi-redis-cache/src/main/java/com/zy/config/RedisConfig.java
njustwh2014/spring-boot-redis-guava-caffeine-cache
86b127b0441492758896d3cc9984774c209a5c53
[ "Apache-2.0" ]
61
2017-11-02T09:15:36.000Z
2022-03-12T14:20:12.000Z
49.816514
159
0.751013
1,003,456
package com.zy.config; import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Scope; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.time.Duration; /** * <p></p> * Created by @author [email protected] on 2019/3/29. */ @Configuration @EnableCaching @Slf4j public class RedisConfig extends CachingConfigurerSupport { @Value("${spring.application.name:unknown}") private String appName; @Value("${spring.redis.timeToLive:15}") private Long timeToLive; @Bean @ConfigurationProperties(prefix = "spring.redis.lettuce.pool") @Scope(value = "prototype") public GenericObjectPoolConfig redisPool() { return new GenericObjectPoolConfig(); } @Bean @ConfigurationProperties(prefix = "spring.redis.redis-a") public RedisStandaloneConfiguration redisConfigA() { return new RedisStandaloneConfiguration(); } @Bean @ConfigurationProperties(prefix = "spring.redis.redis-b") public RedisStandaloneConfiguration redisConfigB() { return new RedisStandaloneConfiguration(); } @Bean @Primary public LettuceConnectionFactory factoryA(GenericObjectPoolConfig config, RedisStandaloneConfiguration redisConfigA) { LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder() .poolConfig(config).commandTimeout(Duration.ofMillis(config.getMaxWaitMillis())).build(); return new LettuceConnectionFactory(redisConfigA, clientConfiguration); } @Bean public LettuceConnectionFactory factoryB(GenericObjectPoolConfig config, RedisStandaloneConfiguration redisConfigB) { LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder() .poolConfig(config).commandTimeout(Duration.ofMillis(config.getMaxWaitMillis())).build(); return new LettuceConnectionFactory(redisConfigB, clientConfiguration); } @Bean(name = "redisTemplateA") public StringRedisTemplate redisTemplateA(LettuceConnectionFactory factoryA) { StringRedisTemplate template = new StringRedisTemplate(factoryA); RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setKeySerializer(redisSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); return template; } @Bean(name = "redisTemplateB") public StringRedisTemplate redisTemplateB(@Autowired @Qualifier("factoryB") LettuceConnectionFactory factoryB) { StringRedisTemplate template = new StringRedisTemplate(factoryB); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 将类名称序列化到json串中 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 将类名称序列化到json串中 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(timeToLive)) .prefixKeysWith(appName + ":"); RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(redisCacheConfiguration) .build(); return cacheManager; } // RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); // configuration.prefixKeysWith("bda"); // configuration = configuration.entryTtl(Duration.ofMinutes(30)); // Set<String> cacheNames = new HashSet<>(); // cacheNames.add("test1"); // cacheNames.add("test2"); // Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>(10); // configurationMap.put("test1", configuration); // configurationMap.put("test2", configuration.entryTtl(Duration.ofMinutes(60))); // RedisCacheManager manager = RedisCacheManager.builder(factory) // .initialCacheNames(cacheNames) // .withInitialCacheConfigurations(configurationMap) // .build(); // return manager; private StringRedisTemplate getRedisTemplate() { StringRedisTemplate template = new StringRedisTemplate(); template.setValueSerializer(new GenericFastJsonRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); return template; } // @Bean // public CacheManager cacheManager(RedisConnectionFactory factory) { // RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); // configuration.prefixKeysWith("bda"); // configuration = configuration.entryTtl(Duration.ofMinutes(30)); // Set<String> cacheNames = new HashSet<>(); // cacheNames.add("test1"); // cacheNames.add("test2"); // Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>(10); // configurationMap.put("test1", configuration); // configurationMap.put("test2", configuration.entryTtl(Duration.ofMinutes(60))); // RedisCacheManager manager = RedisCacheManager.builder(factory) // .initialCacheNames(cacheNames) // .withInitialCacheConfigurations(configurationMap) // .build(); // return manager; // } // @Bean // public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { // StringRedisTemplate template = new StringRedisTemplate(factory); // Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); // ObjectMapper om = new ObjectMapper(); // om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // jackson2JsonRedisSerializer.setObjectMapper(om); // template.setValueSerializer(jackson2JsonRedisSerializer); // template.afterPropertiesSet(); // return template; // } // // @Autowired // private RedisProperties redisProperties; // // // @Bean // @ConfigurationProperties(prefix = "spring.redis3") // public RedisStandaloneConfiguration redis3(){ // return new RedisStandaloneConfiguration(); // } // // // @Bean(name = "db3redisTemplate") // public RedisTemplate<String, String> db3RedisTemplate() { // log.info("redisProperties:{}", JSON.toJSONString(redisProperties)); // RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(); // configuration.setDatabase(3); // configuration.setHostName(redisProperties.getHost()); // configuration.setPort(redisProperties.getPort()); // LettuceClientConfiguration.LettuceClientConfigurationBuilder lettuceClientConfigurationBuilder = LettuceClientConfiguration.builder(); // LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration, lettuceClientConfigurationBuilder.build()); // // StringRedisTemplate template = new StringRedisTemplate(factory); // Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); // ObjectMapper om = new ObjectMapper(); // om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // jackson2JsonRedisSerializer.setObjectMapper(om); // template.setValueSerializer(jackson2JsonRedisSerializer); // template.afterPropertiesSet(); // return template; // } }
92459dd4057a4e64743e94c7910f80935ab48f0f
354
java
Java
gmall-pms/src/main/java/com/atguigu/gmall/pms/mapper/SkuMapper.java
lihan520/gmall
369984984aab89b996028879a0eab9daae63e685
[ "Apache-2.0" ]
null
null
null
gmall-pms/src/main/java/com/atguigu/gmall/pms/mapper/SkuMapper.java
lihan520/gmall
369984984aab89b996028879a0eab9daae63e685
[ "Apache-2.0" ]
null
null
null
gmall-pms/src/main/java/com/atguigu/gmall/pms/mapper/SkuMapper.java
lihan520/gmall
369984984aab89b996028879a0eab9daae63e685
[ "Apache-2.0" ]
null
null
null
19.388889
58
0.747851
1,003,457
package com.atguigu.gmall.pms.mapper; import com.atguigu.gmall.pms.entity.SkuEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * sku信息 * * @author lihan * @email [email protected] * @date 2020-10-28 10:17:26 */ @Mapper public interface SkuMapper extends BaseMapper<SkuEntity> { }
92459f5a5edd312968b3ca41e0cbcd278a099e3a
1,503
java
Java
src/main/java/com/github/hcsp/News.java
giantpetter/xiedaimale-crawler
c58d646ef7abd6ddf1c6aee5b3c7cd212f8ec87d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/hcsp/News.java
giantpetter/xiedaimale-crawler
c58d646ef7abd6ddf1c6aee5b3c7cd212f8ec87d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/hcsp/News.java
giantpetter/xiedaimale-crawler
c58d646ef7abd6ddf1c6aee5b3c7cd212f8ec87d
[ "Apache-2.0" ]
null
null
null
18.7875
59
0.580838
1,003,458
package com.github.hcsp; import java.time.Instant; public class News { private int id; private String title; private String url; private String content; private Instant createdAt; private Instant modifiedAt; public News(String title, String url, String content) { this.title = title; this.url = url; this.content = content; } public News(){ } public News(News old) { this.id = old.id; this.title = old.title; this.url = old.url; this.content = old.content; this.createdAt = old.createdAt; this.modifiedAt = old.modifiedAt; } public Instant getCreatedAt() { return createdAt; } public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } public Instant getModifiedAt() { return modifiedAt; } public void setModifiedAt(Instant modifiedAt) { this.modifiedAt = modifiedAt; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
9245a0483d42cddef9a392885c174886efe086e1
705
java
Java
algorithms/src/main/java/com/wildbeeslabs/jentle/algorithms/utils/TemplateProvider.java
AlexRogalskiy/jentle
5d6f9feee02902cb0a330c7359c0c268feed2015
[ "MIT" ]
null
null
null
algorithms/src/main/java/com/wildbeeslabs/jentle/algorithms/utils/TemplateProvider.java
AlexRogalskiy/jentle
5d6f9feee02902cb0a330c7359c0c268feed2015
[ "MIT" ]
12
2019-11-13T09:35:37.000Z
2021-12-09T20:59:29.000Z
algorithms/src/main/java/com/wildbeeslabs/jentle/algorithms/utils/TemplateProvider.java
AlexRogalskiy/jentle
5d6f9feee02902cb0a330c7359c0c268feed2015
[ "MIT" ]
null
null
null
32.045455
91
0.702128
1,003,459
package com.wildbeeslabs.jentle.algorithms.utils; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Scanner; public interface TemplateProvider { default String provideTemplateContent(String templatePath) { InputStream inputStream = TemplateProvider.class.getResourceAsStream(templatePath); String template; try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) { template = scanner.useDelimiter("\\A").next(); } return template.replaceAll("\r\n", "\n"); } default String extractTemplateReplacementValue(String value) { return "%<".concat(value).concat(">"); } }
9245a079d5cf12b3005bc1e8f6f267b5c5cd6a53
4,022
java
Java
tools/maven-repo-generator/src/main/java/org/wildfly/galleon/maven/repo/generator/Main.java
ochaloup/wildfly-s2i
1f8c8fc33157ae14aba799188b21737a206f65e2
[ "Apache-2.0" ]
1
2020-01-25T11:37:52.000Z
2020-01-25T11:37:52.000Z
tools/maven-repo-generator/src/main/java/org/wildfly/galleon/maven/repo/generator/Main.java
ochaloup/wildfly-s2i
1f8c8fc33157ae14aba799188b21737a206f65e2
[ "Apache-2.0" ]
null
null
null
tools/maven-repo-generator/src/main/java/org/wildfly/galleon/maven/repo/generator/Main.java
ochaloup/wildfly-s2i
1f8c8fc33157ae14aba799188b21737a206f65e2
[ "Apache-2.0" ]
1
2020-01-25T11:37:39.000Z
2020-01-25T11:37:39.000Z
38.304762
141
0.610144
1,003,460
package org.wildfly.galleon.maven.repo.generator; import static io.undertow.Handlers.resource; import io.undertow.Undertow; import io.undertow.server.handlers.resource.PathResourceManager; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * * @author jdenise */ public class Main { public static void main(String[] args) throws Exception { if (args.length != 1) { throw new Exception("Offliner file path is missing"); } Path offlinerFile = Paths.get(args[0]); if (!Files.exists(offlinerFile)) { throw new Exception("Offliner file doesn't exist"); } Path zipFile = Paths.get("maven-repo.zip"); if (Files.exists(zipFile)) { Files.delete(zipFile); } String localRepo = System.getProperty("maven.local.repo", Paths.get(System.getProperty("user.home")).resolve(".m2/repository").toString()); Undertow server = Undertow.builder() .addHttpListener(7777, "127.0.0.1") .setHandler(resource(new PathResourceManager(Paths.get(localRepo), 100)) .setDirectoryListingEnabled(true)) .build(); server.start(); Path tmpPath = Files.createTempDirectory("wf-zipped-repo"); try { Path repoPath = tmpPath.resolve("wildfly-snapshot-image-builder-maven-repository"); Files.createDirectory(repoPath); repoPath = repoPath.resolve("maven-repository"); String[] offlinerArgs = {"--url", "http://127.0.0.1:7777", offlinerFile.toString(), "--dir", repoPath.toString()}; com.redhat.red.offliner.Main.main(offlinerArgs); System.out.println("\nZipping repo..."); zipRepo(tmpPath, zipFile); } finally { deleteDir(tmpPath); server.stop(); } System.out.println("Maven repo zipped in " + zipFile); } private static void deleteDir(Path path) throws IOException { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } private static void zipRepo(Path repo, Path zipFile) throws Exception { try ( FileOutputStream fileWriter = new FileOutputStream(zipFile.toFile()); ZipOutputStream zip = new ZipOutputStream(fileWriter)) { zipDir(repo, repo, zip); } } private static void zipDir(Path rootPath, Path dir, ZipOutputStream zip) throws Exception { for (File file : dir.toFile().listFiles()) { zipFile(rootPath, file.toPath(), zip); } } private static void zipFile(Path rootPath, Path srcFile, ZipOutputStream zip) throws Exception { if (Files.isDirectory(srcFile)) { zipDir(rootPath, srcFile, zip); } else { byte[] buf = new byte[1024]; int len; try ( FileInputStream in = new FileInputStream(srcFile.toFile())) { Path filePath = rootPath.relativize(srcFile); zip.putNextEntry(new ZipEntry(filePath.toString())); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } } } } }
9245a0d455c97e7a2949a89fddc2f434b7bee7f5
2,018
java
Java
Algorithm/java/src/main/java/wx/algorithm/op/dp/string/LevenshteinDistance.java
negativelo/Coder-Essentials
029ce067d3ec178a4ec9c1f9670f0cc422fd9f05
[ "MIT" ]
1
2018-07-07T04:35:29.000Z
2018-07-07T04:35:29.000Z
Algorithm/java/src/main/java/wx/algorithm/op/dp/string/LevenshteinDistance.java
WcombL/Coder-Essentials
029ce067d3ec178a4ec9c1f9670f0cc422fd9f05
[ "MIT" ]
null
null
null
Algorithm/java/src/main/java/wx/algorithm/op/dp/string/LevenshteinDistance.java
WcombL/Coder-Essentials
029ce067d3ec178a4ec9c1f9670f0cc422fd9f05
[ "MIT" ]
1
2018-05-31T07:55:06.000Z
2018-05-31T07:55:06.000Z
27.27027
159
0.533697
1,003,461
package wx.algorithm.op.dp.string; import java.util.Scanner; /** * @function Levenshtein 距离,又称编辑距离,指的是两个字符串之间,由一个转换成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符,插入一个字符,删除一个字符。编辑距离的算法是首先由俄国科学家Levenshtein提出的,故又叫Levenshtein Distance。 * @OJ http://www.nowcoder.com/practice/3959837097c7413a961a135d7104c314?tpId=37&tqId=21275&rp=&ru=/ta/huawei&qru=/ta/huawei/question-ranking */ public class LevenshteinDistance { public static int calStringDistance(String firstStr, String secondStr) { int firstStrLength = firstStr.length(); int secondStrLength = secondStr.length(); //初始化记录矩阵,注意,这里不同于LCS,需要设置为length+1的尺寸 //这里的 0 0表示啥都没有,而不是字符串中的第一个字符 int[][] dp = new int[firstStrLength + 1][secondStrLength + 1]; //初始化记录矩阵 int i, j; for (i = 1; i < firstStrLength + 1; i++) { dp[i][0] = i; } for (j = 1; j < secondStrLength + 1; j++) { dp[0][j] = j; } for (i = 1; i < firstStrLength + 1; i++) { for (j = 1; j < secondStrLength + 1; j++) { //判断当前字符是否相等 if (firstStr.charAt(i - 1) == secondStr.charAt(j - 1)) { //如果相等,则不需要修改 dp[i][j] = dp[i - 1][j - 1]; } else { //不相等 dp[i][j] = dp[i - 1][j - 1] + 1; } //设置其他可能的情况 dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1); dp[i][j] = Math.min(dp[i][j], dp[i][j - 1] + 1); } } return dp[firstStrLength][secondStrLength]; } public static void main(String[] args) { // System.out.println(calStringDistance("abcdefg","abcdef")); Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String firstStr = scanner.nextLine(); String secondStr = scanner.nextLine(); System.out.println(calStringDistance(firstStr, secondStr)); } } }
9245a0ef89efeba25700f4f8fdc4f99c47b4bcb4
966
java
Java
bookstore-service/src/main/java/be/gestatech/bookstore/service/api/UserService.java
gestatech/dukes-bookstore
9826738d611f4484600732629896dad2f25d49b7
[ "MIT" ]
null
null
null
bookstore-service/src/main/java/be/gestatech/bookstore/service/api/UserService.java
gestatech/dukes-bookstore
9826738d611f4484600732629896dad2f25d49b7
[ "MIT" ]
null
null
null
bookstore-service/src/main/java/be/gestatech/bookstore/service/api/UserService.java
gestatech/dukes-bookstore
9826738d611f4484600732629896dad2f25d49b7
[ "MIT" ]
null
null
null
26.108108
89
0.776398
1,003,462
package be.gestatech.bookstore.service.api; import be.gestatech.bookstore.domain.auth.entity.TokenType; import be.gestatech.bookstore.domain.auth.entity.User; import javax.ejb.Local; import java.util.Optional; import java.util.concurrent.TimeUnit; @Local public interface UserService { int DEFAULT_SALT_LENGTH = 40; long DEFAULT_PASSWORD_RESET_EXPIRATION_TIME_IN_MINUTES = TimeUnit.HOURS.toMinutes(1); String MESSAGE_DIGEST_ALGORITHM = "SHA-256"; void registerUser(User user, String password); User update(User user); void updatePassword(User user, String password); void updatePassword(String loginToken, String password); void requestResetPassword(String email, String ipAddress, String callbackUrlFormat); Optional<User> findByEmail(String email); Optional<User> findByLoginToken(String loginToken, TokenType type); User findByEmailAndPassword(String email, String password); User getActiveUser(); }
9245a285107a00c09a741e7d70a7fa10abb812dc
2,238
java
Java
xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/NamespaceHelper.java
codehaus/xbean
8df3bc28bfe8f4b7064c9de14310753416be4021
[ "Apache-2.0" ]
null
null
null
xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/NamespaceHelper.java
codehaus/xbean
8df3bc28bfe8f4b7064c9de14310753416be4021
[ "Apache-2.0" ]
null
null
null
xbean-spring/src/main/java/org/apache/xbean/spring/context/impl/NamespaceHelper.java
codehaus/xbean
8df3bc28bfe8f4b7064c9de14310753416be4021
[ "Apache-2.0" ]
null
null
null
34.96875
100
0.668007
1,003,463
/** * * Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable. * * 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.apache.xbean.spring.context.impl; /** * A helper class for turning namespaces into META-INF/services URIs * * @version $Revision: 1.1 $ */ public class NamespaceHelper { public static final String META_INF_PREFIX = "META-INF/services/org/apache/xbean/spring/"; public static final String OLD_META_INF_PREFIX = "META-INF/services/org/xbean/spring/"; /** * Converts the namespace and localName into a valid path name we can use on * the classpath to discover a text file */ public static String createDiscoveryPathName(String uri, String localName) { if (isEmpty(uri)) { return localName; } return createDiscoveryPathName(uri) + "/" + localName; } /** * Converts the namespace and localName into a valid path name we can use on * the classpath to discover a text file */ public static String createDiscoveryPathName(String uri) { // TODO proper encoding required // lets replace any dodgy characters return META_INF_PREFIX + uri.replaceAll("://", "/").replace(':', '/').replace(' ', '_'); } /** * Creates the old URI for backwards compatibility */ public static String createDiscoveryOldPathName(String uri) { // TODO proper encoding required // lets replace any dodgy characters return OLD_META_INF_PREFIX + uri.replaceAll("://", "/").replace(':', '/').replace(' ', '_'); } public static boolean isEmpty(String uri) { return uri == null || uri.length() == 0; } }
9245a3dbaa20ed4883d2de78b92c2109ceeddd95
177
java
Java
src/factory/abstractFactory/Rectangle.java
wasys1314/JavaDesignPattern
07c21f9eb12bf07a97e65206d9ed5f87e1c49491
[ "Apache-2.0" ]
null
null
null
src/factory/abstractFactory/Rectangle.java
wasys1314/JavaDesignPattern
07c21f9eb12bf07a97e65206d9ed5f87e1c49491
[ "Apache-2.0" ]
null
null
null
src/factory/abstractFactory/Rectangle.java
wasys1314/JavaDesignPattern
07c21f9eb12bf07a97e65206d9ed5f87e1c49491
[ "Apache-2.0" ]
null
null
null
17.7
53
0.655367
1,003,464
package factory.abstractFactory; public class Rectangle implements Shape{ @Override public void draw() { System.out.println("draw a Rectangle......"); } }
9245a4b89a8e7c7dd0b8f57e4a3c8d95f61b40a1
2,516
java
Java
src/com/interface21/aop/framework/AopContext.java
Jacshon/spring-framework-i21
ed27de6d3e2246b2e6d7538e1fe7f7226d11ec3d
[ "Apache-1.1" ]
44
2017-09-06T02:19:36.000Z
2022-03-15T13:43:22.000Z
src/com/interface21/aop/framework/AopContext.java
Jacshon/spring-framework-i21
ed27de6d3e2246b2e6d7538e1fe7f7226d11ec3d
[ "Apache-1.1" ]
null
null
null
src/com/interface21/aop/framework/AopContext.java
Jacshon/spring-framework-i21
ed27de6d3e2246b2e6d7538e1fe7f7226d11ec3d
[ "Apache-1.1" ]
45
2017-07-20T02:50:47.000Z
2022-01-21T02:27:45.000Z
38.707692
121
0.761924
1,003,465
/* * The Spring Framework is published under the terms * of the Apache Software License. */ package com.interface21.aop.framework; import org.aopalliance.intercept.AspectException; import org.aopalliance.intercept.MethodInvocation; /** * Class containing static methods used to obtain information about the * current AOP invocation. The currentInvocation() method--the only public * method in this class--is usable only if the AOP framework is configured * to expose invocations. The framework does not expose invocation contexts * by default, as there is a performance cost in doing so. * * <p>The functionality in this class might be used by a target object * that needed access to resources on the invocation. However, this * approach should not be used when there is a reasonable alternative, * as it makes application code dependent on usage under AOP and * --specifically--the Spring AOP framework. * * @author Rod Johnson * @since 13-Mar-2003 * @version $Id$ */ public abstract class AopContext { /** * Invocation associated with this thread. Will be null unless the * exposeInvocation property on the controlling proxy has been set to true. * The default value for this property is false, for performance reasons. */ private static ThreadLocal currentInvocation = new ThreadLocal(); /** * Internal method that the AOP framework uses to set the current * AOP context if it is configured to expose call contexts. * @param invocation the current AOP invocation context */ static void setCurrentInvocation(MethodInvocation invocation) { currentInvocation.set(invocation); } /** * Try to return the current AOP invocation. This method is usable * only if the calling method has been invoked via AOP, and the * AOP framework has been set to expose invocations. Otherwise, * this method will throw an AspectException. * @return MethodInvocation the current AOP invocation * (never returns null) * @throws AspectException if the invocation cannot be found, * because the method was invoked outside an AOP invocation * context or because the AOP framework has not been configured * to expose the invocation context */ public static MethodInvocation currentInvocation() throws AspectException { if (currentInvocation == null || currentInvocation.get() == null) throw new AspectException("Cannot find invocation: set 'exposeInvocation' property on AopProxy to make it available"); return (MethodInvocation) currentInvocation.get(); } }
9245a5c7ec6a247ff28be49c3041856c08302f58
11,312
java
Java
richwysiwygeditor/src/main/java/com/gee12/htmlwysiwygeditor/Dialogs.java
gee12/Android-HTML-WYSIWYG-Editor
60d7ed9dc07b346a3e9e1f6359de16ed7c151963
[ "Apache-2.0" ]
null
null
null
richwysiwygeditor/src/main/java/com/gee12/htmlwysiwygeditor/Dialogs.java
gee12/Android-HTML-WYSIWYG-Editor
60d7ed9dc07b346a3e9e1f6359de16ed7c151963
[ "Apache-2.0" ]
null
null
null
richwysiwygeditor/src/main/java/com/gee12/htmlwysiwygeditor/Dialogs.java
gee12/Android-HTML-WYSIWYG-Editor
60d7ed9dc07b346a3e9e1f6359de16ed7c151963
[ "Apache-2.0" ]
null
null
null
39.830986
121
0.629508
1,003,466
package com.gee12.htmlwysiwygeditor; import android.content.Context; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import com.lumyjuwon.richwysiwygeditor.R; import com.lumyjuwon.richwysiwygeditor.RichEditor.Utils; import java.util.Locale; public class Dialogs { public interface IApplyResult { void onApply(); } public interface IApplyCancelResult extends IApplyResult { void onCancel(); } public interface IApplyCancelDismissResult extends IApplyCancelResult { void onDismiss(); } public interface ITextSizeResult { void onApply(int size); } public interface IInsertLinkResult { void onApply(String link, String title); } public interface IImageDimensResult { void onApply(int width, int height, boolean setSimilar); } /** * Диалог ввода размера текста. * Значение должно быть в диапазоне 1-7. * @param context * @param callback */ public static void createTextSizeDialog(Context context, int curSize, ITextSizeResult callback) { AskDialogBuilder builder = AskDialogBuilder.create(context, R.layout.dialog_text_size); EditText etSize = builder.getView().findViewById(R.id.edit_text_size); if (curSize >= 1 && curSize <= 7) { etSize.setText(String.format(Locale.getDefault(), "%d", curSize)); } builder.setPositiveButton(R.string.answer_ok, (dialog1, which) -> { // int size = Integer.parseInt(etSize.getText().toString()); String s = etSize.getText().toString(); Integer size = Utils.parseInt(s); if (size != null) { callback.onApply(size); } else { Toast.makeText(context, context.getString(R.string.invalid_number) + s, Toast.LENGTH_SHORT).show(); } }).setNegativeButton(R.string.answer_cancel, null); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(dialog12 -> { // получаем okButton уже после вызова show() final Button okButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); if (TextUtils.isEmpty(etSize.getText().toString())) { okButton.setEnabled(false); } etSize.setSelection(etSize.getText().length()); // Keyboard.showKeyboard(etSize); }); dialog.show(); // получаем okButton тут отдельно после вызова show() final Button okButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); etSize.addTextChangedListener(new ViewUtils.TextChangedListener(newText -> { // if (TextUtils.isEmpty(newText)) { // okButton.setEnabled(false); // } else { // int size = Integer.parseInt(etSize.getText().toString()); // okButton.setEnabled(size >= 1 && size <= 7); Integer size = Utils.parseInt(etSize.getText().toString()); okButton.setEnabled(size != null && size >= 1 && size <= 7); // } })); } /** * Диалог ввода размера изображения. * Значение должно быть > 0. * @param context * @param callback */ public static void createImageDimensDialog(Context context, int curWidth, int curHeight, boolean isSeveral, IImageDimensResult callback) { AskDialogBuilder builder = AskDialogBuilder.create(context, R.layout.dialog_edit_image); EditText etWidth = builder.getView().findViewById(R.id.edit_text_width); if (curWidth > 0) { etWidth.setText(String.format(Locale.getDefault(), "%d", curWidth)); } EditText etHeight = builder.getView().findViewById(R.id.edit_text_height); if (curHeight > 0) { etHeight.setText(String.format(Locale.getDefault(), "%d", curHeight)); } CheckBox checkBox = builder.getView().findViewById(R.id.check_box_similar); checkBox.setVisibility((isSeveral) ? View.VISIBLE : View.GONE); builder.setPositiveButton(R.string.answer_ok, (dialog1, which) -> { String s = etWidth.getText().toString(); Integer width = Utils.parseInt(s); if (width != null) { s = etHeight.getText().toString(); Integer height = Utils.parseInt(s); if (height != null) { boolean setSimilarParams = checkBox.isChecked(); callback.onApply(width, height, setSimilarParams); } else { Toast.makeText(context, context.getString(R.string.invalid_number) + s, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(context, context.getString(R.string.invalid_number) + s, Toast.LENGTH_SHORT).show(); } }).setNegativeButton(R.string.answer_cancel, null); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(dialog12 -> { // получаем okButton уже после вызова show() final Button okButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); if (TextUtils.isEmpty(etWidth.getText().toString()) || TextUtils.isEmpty(etHeight.getText().toString())) { okButton.setEnabled(false); } etWidth.setSelection(etWidth.getText().length()); // Keyboard.showKeyboard(etWidth); }); dialog.show(); // получаем okButton тут отдельно после вызова show() final Button okButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); ViewUtils.TextChangedListener textWatcher = new ViewUtils.TextChangedListener(newText -> { // if (TextUtils.isEmpty(newText)) { // okButton.setEnabled(false); // } else { // int dimen = Integer.parseInt(newText); // okButton.setEnabled(dimen > 0); // } Integer size = Utils.parseInt(newText); okButton.setEnabled(size != null && size > 0); }); etWidth.addTextChangedListener(textWatcher); etHeight.addTextChangedListener(textWatcher); } /** * Диалог ввода url ссылки. * @param context * @param onlyLink * @param callback */ public static void createInsertLinkDialog(Context context, boolean onlyLink, IInsertLinkResult callback) { AskDialogBuilder builder = AskDialogBuilder.create(context, R.layout.dialog_insert_link); EditText etLink = builder.getView().findViewById(R.id.edit_text_link); EditText etTitle = builder.getView().findViewById(R.id.edit_text_title); if (onlyLink) { etTitle.setVisibility(View.GONE); } builder.setPositiveButton(R.string.answer_ok, (dialog1, which) -> callback.onApply(etLink.getText().toString(), etTitle.getText().toString())) .setNegativeButton(R.string.answer_cancel, null) .create().show(); } /** * AlertDialog с методом getView(). */ public static class AskDialogBuilder extends AlertDialog.Builder { private View mView; public AskDialogBuilder(@NonNull Context context) { super(context); } public AskDialogBuilder(@NonNull Context context, int themeResId) { super(context, themeResId); } @Override public AlertDialog.Builder setView(View view) { this.mView = view; return super.setView(view); } public View getView() { return mView; } public static AskDialogBuilder create(Context context, int layoutResId) { // LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE ); LayoutInflater inflater = LayoutInflater.from(context); AskDialogBuilder dialogBuilder = new AskDialogBuilder(context); View dialogView = inflater.inflate(layoutResId, null); dialogBuilder.setView(dialogView); dialogBuilder.setCancelable(true); return dialogBuilder; } } public static void showAlertDialog(Context context, int messageRes, IApplyResult callback) { showAlertDialog(context, context.getString(messageRes), true, true, callback); } public static void showAlertDialog(Context context, CharSequence message, IApplyResult callback) { showAlertDialog(context, message, true, true, callback); } public static void showAlertDialog(Context context, int messageRes, boolean isNeedCancel, boolean isCancelable, IApplyResult callback) { showAlertDialog(context, context.getString(messageRes), isNeedCancel, isCancelable, callback); } public static void showAlertDialog(Context context, CharSequence message, boolean isNeedCancel, boolean isCancelable, IApplyResult callback) { showAlertDialog(context, message, isNeedCancel, isCancelable, new IApplyCancelResult() { @Override public void onApply() { callback.onApply(); } @Override public void onCancel() { } }); } public static void showAlertDialog(Context context, int messageRes, IApplyCancelResult callback) { showAlertDialog(context, context.getString(messageRes), callback); } public static void showAlertDialog(Context context, CharSequence message, IApplyCancelResult callback) { showAlertDialog(context, message, true, true, callback); } public static void showAlertDialog(Context context, int messageRes, boolean isNeedCancel, boolean isCancelable, IApplyCancelResult callback) { showAlertDialog(context, context.getString(messageRes), isNeedCancel, isCancelable, callback); } public static void showAlertDialog(Context context, CharSequence message, boolean isNeedCancel, boolean isCancelable, IApplyCancelResult callback) { /*android.app.*/AlertDialog.Builder builder = new /*android.app.*/AlertDialog.Builder(context); builder.setMessage(message); builder.setCancelable(isCancelable); builder.setPositiveButton(R.string.answer_yes, (dialog, which) -> callback.onApply()); if (isNeedCancel) { builder.setNegativeButton(R.string.answer_no, (dialog, which) -> callback.onCancel()); } final /*android.app.*/AlertDialog dialog = builder.create(); // dialog.setCanceledOnTouchOutside(); if (/*Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 &&*/ callback instanceof IApplyCancelDismissResult) { dialog.setOnDismissListener(dialog1 -> ((IApplyCancelDismissResult)callback).onDismiss()); } dialog.show(); } }
9245a690b940a8fc0b812d8acca306bc15021558
2,771
java
Java
src/main/java/com/nduowang/ymind/context/AppContext.java
wuneiii/YMind
85c61f0e8731fd9ec2de847e165c2068c9b2b4b2
[ "MIT" ]
1
2020-11-18T13:09:29.000Z
2020-11-18T13:09:29.000Z
src/main/java/com/nduowang/ymind/context/AppContext.java
wuneiii/YMind
85c61f0e8731fd9ec2de847e165c2068c9b2b4b2
[ "MIT" ]
null
null
null
src/main/java/com/nduowang/ymind/context/AppContext.java
wuneiii/YMind
85c61f0e8731fd9ec2de847e165c2068c9b2b4b2
[ "MIT" ]
null
null
null
26.141509
85
0.610249
1,003,467
package com.nduowang.ymind.context; import com.nduowang.ymind.common.Constant; import com.nduowang.ymind.common.Lang; import com.nduowang.ymind.ui.DocTabPane; import com.nduowang.ymind.ui.MainBorderPane; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.paint.Color; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; public class AppContext { public boolean isDebug = false; private final Logger log = LoggerFactory.getLogger(this.getClass()); // appContext private static AppContext appContext = new AppContext(); public static AppContext getInstance() { return appContext; } // docManager private DocManager docManager = new DocManager(); public DocManager getDocManager() { return docManager; } // rightBox public StringProperty rightBoxContentProperty = new SimpleStringProperty(); // main stage public Stage stage; // skin private String skin = "default"; public void start(Stage primaryStage) { this.stage = primaryStage; BorderPane borderPane = new MainBorderPane(); //center tabPane DocTabPane tabPane = new DocTabPane(); borderPane.setCenter(tabPane); // scene Scene scene = new Scene(borderPane, 800, 600, Color.WHITE); loadStyle(scene); primaryStage.setScene(scene); primaryStage.setTitle(Lang.get("string.title")); //primaryStage.setMaximized(true); primaryStage.show(); //bind docManager.bindDocList(tabPane); docManager.newDoc(); } private void loadStyle(Scene scene) { File skinPath = new File(getClass().getResource("/style/" + skin).getFile()); if (!skinPath.exists() || !skinPath.isDirectory()) { return; } String[] cssFiles = skinPath.list((dir, name) -> { if (name != null && name.endsWith(".css")) { return true; } return false; }); log.info("load css dir:" + skinPath.getAbsoluteFile()); if (cssFiles == null || cssFiles.length == 0) { return; } for (String css : cssFiles) { log.info("load css:" + css); scene.getStylesheets().add( getClass().getResource("/style/" + skin + "/" + css) .toExternalForm() ); } scene.getStylesheets().add( getClass().getResource("/style/node/y-node-label-level.css") .toExternalForm() ); } }
9245a763c3f4de92e375e141c68ee6b6e016a05d
10,134
java
Java
released/MyBox/src/main/java/mara/mybox/MyBox.java
qb345801622/MyBox
174fbab83d1a29867aa7972110a9849e9e4ec81a
[ "Apache-2.0" ]
76
2018-06-12T09:02:49.000Z
2022-03-31T03:43:39.000Z
released/MyBox/src/main/java/mara/mybox/MyBox.java
qb345801622/MyBox
174fbab83d1a29867aa7972110a9849e9e4ec81a
[ "Apache-2.0" ]
1,377
2018-06-16T23:16:41.000Z
2022-03-29T03:01:43.000Z
released/MyBox/src/main/java/mara/mybox/MyBox.java
qb345801622/MyBox
174fbab83d1a29867aa7972110a9849e9e4ec81a
[ "Apache-2.0" ]
18
2018-11-18T04:33:06.000Z
2022-03-08T07:47:09.000Z
38.679389
116
0.549734
1,003,468
package mara.mybox; import java.io.File; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.List; import javafx.application.Application; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.ConfigTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.tools.FileTools; import mara.mybox.tools.SecurityTools; import mara.mybox.tools.SystemTools; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; /** * @Author Mara * @CreateDate 2019-1-22 14:35:50 * @License Apache License Version 2.0 */ public class MyBox { public static String InternalRestartFlag = "MyBoxInternalRestarting"; // To pass arguments to JavaFx GUI // https://stackoverflow.com/questions/33549820/javafx-not-calling-mainstring-args-method/33549932#33549932 public static void main(String[] args) { if (args == null) { AppVariables.appArgs = null; } else { AppVariables.appArgs = new String[args.length]; System.arraycopy(args, 0, AppVariables.appArgs, 0, args.length); } initBaseValues(); launchApp(); } public static boolean initBaseValues() { MyBoxLog.console("Checking configuration parameters..."); if (AppVariables.appArgs != null) { for (String arg : AppVariables.appArgs) { if (arg.startsWith("config=")) { String config = arg.substring("config=".length()); File configFile = new File(config); String dataPath = ConfigTools.readValue(configFile, "MyBoxDataPath"); if (dataPath != null) { try { File dataPathFile = new File(dataPath); if (!dataPathFile.exists()) { dataPathFile.mkdirs(); } else if (!dataPathFile.isDirectory()) { FileDeleteTools.delete(dataPathFile); dataPathFile.mkdirs(); } if (dataPathFile.exists() && dataPathFile.isDirectory()) { AppVariables.MyboxConfigFile = configFile; AppVariables.MyboxDataPath = dataPathFile.getAbsolutePath(); return true; } } catch (Exception e) { } } } } } AppVariables.MyboxConfigFile = ConfigTools.defaultConfigFile(); MyBoxLog.console("MyBox Config file:" + AppVariables.MyboxConfigFile); String dataPath = ConfigTools.readValue("MyBoxDataPath"); if (dataPath != null) { try { File dataPathFile = new File(dataPath); if (!dataPathFile.exists()) { dataPathFile.mkdirs(); } else if (!dataPathFile.isDirectory()) { FileDeleteTools.delete(dataPathFile); dataPathFile.mkdirs(); } if (dataPathFile.exists() && dataPathFile.isDirectory()) { AppVariables.MyboxDataPath = dataPathFile.getAbsolutePath(); MyBoxLog.console("MyBox Data Path:" + AppVariables.MyboxDataPath); return true; } } catch (Exception e) { } } return true; } public static void launchApp() { MyBoxLog.console("Starting Mybox..."); MyBoxLog.console("JVM path: " + System.getProperty("java.home")); if (AppVariables.MyboxDataPath != null && setJVMmemory() && !internalRestart()) { restart(); } else { initEnv(); Application.launch(MainApp.class, AppVariables.appArgs); } } public static boolean internalRestart() { return AppVariables.appArgs != null && AppVariables.appArgs.length > 0 && InternalRestartFlag.equals(AppVariables.appArgs[0]); } public static boolean setJVMmemory() { String JVMmemory = ConfigTools.readValue("JVMmemory"); if (JVMmemory == null) { return false; } long jvmM = Runtime.getRuntime().maxMemory() / (1024 * 1024); if (JVMmemory.equals("-Xms" + jvmM + "m")) { return false; } if (AppVariables.appArgs == null || AppVariables.appArgs.length == 0) { return true; } for (String s : AppVariables.appArgs) { if (s.startsWith("-Xms")) { return false; } } return true; } // Set properties before JavaFx starting to make sure they take effect against JavaFX public static void initEnv() { try { // https://pdfbox.apache.org/2.0/getting-started.html // System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider"); System.setProperty("org.apache.pdfbox.rendering.UsePureJavaCMYKConversion", "true"); // https://blog.csdn.net/iteye_3493/article/details/82060349 // https://stackoverflow.com/questions/1004327/getting-rid-of-derby-log/1933310#1933310 if (AppVariables.MyboxDataPath != null) { System.setProperty("javax.net.ssl.keyStore", SecurityTools.keystore()); System.setProperty("javax.net.ssl.keyStorePassword", SecurityTools.keystorePassword()); System.setProperty("javax.net.ssl.trustStore", SecurityTools.keystore()); System.setProperty("javax.net.ssl.trustStorePassword", SecurityTools.keystorePassword()); MyBoxLog.console(System.getProperty("javax.net.ssl.keyStore")); } // System.setProperty("derby.language.logQueryPlan", "true"); System.setProperty("jdk.tls.client.protocols", "TLSv1.1,TLSv1.2"); System.setProperty("jdk.tls.server.protocols", "TLSv1,TLSv1.1,TLSv1.2,TLSv1.3"); // System.setProperty("https.protocol", "TLSv1"); // System.setProperty("com.sun.security.enableAIAcaIssuers", "true"); // System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); // System.setProperty("javax.net.debug", "ssl,record, plaintext, handshake,session,trustmanager,sslctx"); // System.setProperty("javax.net.debug", "ssl,handshake,session,trustmanager,sslctx"); } catch (Exception e) { MyBoxLog.error(e.toString()); } } // Restart with parameters. Use "ProcessBuilder", instead of "Runtime.getRuntime().exec" which is not safe // https://stackoverflow.com/questions/4159802/how-can-i-restart-a-java-application?r=SearchResults public static void restart() { try { String javaHome = System.getProperty("java.home"); File boundlesJar; if (SystemTools.isMac()) { boundlesJar = new File(javaHome.substring(0, javaHome.length() - "runtime/Contents/Home".length()) + "Java" + File.separator + "MyBox-" + AppValues.AppVersion + ".jar"); } else { boundlesJar = new File(javaHome.substring(0, javaHome.length() - "runtime".length()) + "app" + File.separator + "MyBox-" + AppValues.AppVersion + ".jar"); } if (boundlesJar.exists()) { restartBundles(boundlesJar); } else { restartJar(); } } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static void restartBundles(File jar) { try { MyBoxLog.console("Restarting Mybox bundles..."); List<String> commands = new ArrayList<>(); commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"); String JVMmemory = ConfigTools.readValue("JVMmemory"); if (JVMmemory != null) { commands.add(JVMmemory); } commands.add("-jar"); commands.add(jar.getAbsolutePath()); commands.add(InternalRestartFlag); if (AppVariables.appArgs != null) { for (String arg : AppVariables.appArgs) { if (arg != null) { commands.add(arg); } } } ProcessBuilder pb = new ProcessBuilder(commands); pb.start(); System.exit(0); } catch (Exception e) { MyBoxLog.error(e.toString()); } } public static void restartJar() { try { MyBoxLog.console("Restarting Mybox Jar package..."); List<String> commands = new ArrayList<>(); commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"); List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments(); for (String jvmArg : jvmArgs) { if (jvmArg != null) { commands.add(jvmArg); } } commands.add("-cp"); commands.add(ManagementFactory.getRuntimeMXBean().getClassPath()); String JVMmemory = ConfigTools.readValue("JVMmemory"); if (JVMmemory != null) { commands.add(JVMmemory); } commands.add(MyBox.class.getName()); commands.add(InternalRestartFlag); if (AppVariables.appArgs != null) { for (String arg : AppVariables.appArgs) { if (arg != null) { commands.add(arg); } } } ProcessBuilder pb = new ProcessBuilder(commands); pb.start(); System.exit(0); } catch (Exception e) { MyBoxLog.error(e.toString()); } } }
9245a808a7b3afdbb3f7cdc22ccb7bba9efdc0e0
3,375
java
Java
src/plugin/urlfilter-regex/src/java/org/apache/nutch/urlfilter/regex/RegexURLFilter.java
dhkdn9192/nutch
1c2e4110ca4f4d739c6f9cde42d7a54ab52fa860
[ "Apache-2.0" ]
2,482
2015-01-03T02:54:01.000Z
2022-03-30T19:32:15.000Z
src/plugin/urlfilter-regex/src/java/org/apache/nutch/urlfilter/regex/RegexURLFilter.java
dhkdn9192/nutch
1c2e4110ca4f4d739c6f9cde42d7a54ab52fa860
[ "Apache-2.0" ]
324
2015-02-20T01:15:50.000Z
2022-01-18T14:59:20.000Z
src/plugin/urlfilter-regex/src/java/org/apache/nutch/urlfilter/regex/RegexURLFilter.java
dhkdn9192/nutch
1c2e4110ca4f4d739c6f9cde42d7a54ab52fa860
[ "Apache-2.0" ]
1,454
2015-01-02T00:46:04.000Z
2022-03-29T03:59:28.000Z
30.405405
83
0.695704
1,003,469
/* * 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.nutch.urlfilter.regex; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.hadoop.conf.Configuration; import org.apache.nutch.urlfilter.api.RegexRule; import org.apache.nutch.urlfilter.api.RegexURLFilterBase; import org.apache.nutch.util.NutchConfiguration; /** * Filters URLs based on a file of regular expressions using the * {@link java.util.regex Java Regex implementation}. */ public class RegexURLFilter extends RegexURLFilterBase { public static final String URLFILTER_REGEX_FILE = "urlfilter.regex.file"; public static final String URLFILTER_REGEX_RULES = "urlfilter.regex.rules"; public RegexURLFilter() { super(); } public RegexURLFilter(String filename) throws IOException, PatternSyntaxException { super(filename); } RegexURLFilter(Reader reader) throws IOException, IllegalArgumentException { super(reader); } /* * ----------------------------------- * <implementation:RegexURLFilterBase> * * ----------------------------------- */ /** * Rules specified as a config property will override rules specified as a * config file. */ protected Reader getRulesReader(Configuration conf) throws IOException { String stringRules = conf.get(URLFILTER_REGEX_RULES); if (stringRules != null) { return new StringReader(stringRules); } String fileRules = conf.get(URLFILTER_REGEX_FILE); return conf.getConfResourceAsReader(fileRules); } // Inherited Javadoc protected RegexRule createRule(boolean sign, String regex) { return new Rule(sign, regex); } protected RegexRule createRule(boolean sign, String regex, String hostOrDomain) { return new Rule(sign, regex, hostOrDomain); } /* * ------------------------------------ * </implementation:RegexURLFilterBase> * * ------------------------------------ */ public static void main(String args[]) throws IOException { RegexURLFilter filter = new RegexURLFilter(); filter.setConf(NutchConfiguration.create()); main(filter, args); } private class Rule extends RegexRule { private Pattern pattern; Rule(boolean sign, String regex) { this(sign, regex, null); } Rule(boolean sign, String regex, String hostOrDomain) { super(sign, regex, hostOrDomain); pattern = Pattern.compile(regex); } protected boolean match(String url) { return pattern.matcher(url).find(); } } }
9245a85cca3a5f176757f4089d0b16b085d12c64
2,258
java
Java
ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/vm/AbstractOperation.java
Matthalp/pantheon
8c37c46d63bba96f40a0584a359e0bd2057a7b0f
[ "Apache-2.0" ]
2
2018-10-26T04:00:56.000Z
2018-10-26T04:02:21.000Z
ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/vm/AbstractOperation.java
Matthalp/pantheon
8c37c46d63bba96f40a0584a359e0bd2057a7b0f
[ "Apache-2.0" ]
1
2019-07-23T23:43:13.000Z
2019-07-23T23:43:13.000Z
ethereum/core/src/main/java/tech/pegasys/pantheon/ethereum/vm/AbstractOperation.java
Matthalp/pantheon
8c37c46d63bba96f40a0584a359e0bd2057a7b0f
[ "Apache-2.0" ]
1
2019-04-03T20:55:04.000Z
2019-04-03T20:55:04.000Z
26.880952
118
0.733835
1,003,470
/* * Copyright 2018 ConsenSys AG. * * 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 tech.pegasys.pantheon.ethereum.vm; /** * All {@link Operation} implementations should inherit from this class to get the setting of some * members for free. */ public abstract class AbstractOperation implements Operation { private final int opcode; private final String name; private final int stackItemsConsumed; private final int stackItemsProduced; private final boolean updatesProgramCounter; private final int opSize; private final GasCalculator gasCalculator; public AbstractOperation( final int opcode, final String name, final int stackItemsConsumed, final int stackItemsProduced, final boolean updatesProgramCounter, final int opSize, final GasCalculator gasCalculator) { this.opcode = opcode & 0xff; this.name = name; this.stackItemsConsumed = stackItemsConsumed; this.stackItemsProduced = stackItemsProduced; this.updatesProgramCounter = updatesProgramCounter; this.opSize = opSize; this.gasCalculator = gasCalculator; } protected GasCalculator gasCalculator() { return gasCalculator; } @Override public int getOpcode() { return opcode; } @Override public String getName() { return name; } @Override public int getStackItemsConsumed() { return stackItemsConsumed; } @Override public int getStackItemsProduced() { return stackItemsProduced; } @Override public int getStackSizeChange() { return stackItemsProduced - stackItemsConsumed; } @Override public boolean getUpdatesProgramCounter() { return updatesProgramCounter; } @Override public int getOpSize() { return opSize; } }
9245a8964a8d48a2feb71ca13caf3691fff111fd
2,023
java
Java
src/main/java/com/macro/mall/tiny/security/component/DynamicSecurityMetadataSource.java
18604510128/auth-manage
d62afcc9c434f1156740ecb6a430a26cee0c7777
[ "Apache-2.0" ]
1
2021-11-24T02:00:28.000Z
2021-11-24T02:00:28.000Z
src/main/java/com/macro/mall/tiny/security/component/DynamicSecurityMetadataSource.java
dong-jianbin/auth-manage
d62afcc9c434f1156740ecb6a430a26cee0c7777
[ "Apache-2.0" ]
null
null
null
src/main/java/com/macro/mall/tiny/security/component/DynamicSecurityMetadataSource.java
dong-jianbin/auth-manage
d62afcc9c434f1156740ecb6a430a26cee0c7777
[ "Apache-2.0" ]
1
2020-11-24T04:11:47.000Z
2020-11-24T04:11:47.000Z
30.19403
96
0.706871
1,003,471
package com.macro.mall.tiny.security.component; import cn.hutool.core.util.URLUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.util.AntPathMatcher; import org.springframework.util.PathMatcher; import javax.annotation.PostConstruct; import java.util.*; /** * 动态权限数据源,用于获取动态权限规则 * * @author dongjb * @date 2020/11/19 */ public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { private static Map<String, ConfigAttribute> configAttributeMap = null; @Autowired private DynamicSecurityService dynamicSecurityService; @PostConstruct public void loadDataSource() { configAttributeMap = dynamicSecurityService.loadDataSource(); } public void clearDataSource() { configAttributeMap.clear(); configAttributeMap = null; } @Override public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException { if (configAttributeMap == null) { this.loadDataSource(); } List<ConfigAttribute> configAttributes = new ArrayList<>(); //获取当前访问的路径 String url = ((FilterInvocation) o).getRequestUrl(); String path = URLUtil.getPath(url); PathMatcher pathMatcher = new AntPathMatcher(); //获取访问该路径所需资源 for (String pattern : configAttributeMap.keySet()) { if (pathMatcher.match(pattern, path)) { configAttributes.add(configAttributeMap.get(pattern)); } } // 未设置操作请求权限,返回空集合 return configAttributes; } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } @Override public boolean supports(Class<?> aClass) { return true; } }
9245a8972a6924b292b2e6cae8e1f4622836a3e5
3,622
java
Java
src/main/java/com/groupdocs/signature/sample/TestRunner.java
liosha2007/groupdocs-signature-java-sample
84008e4970fa6e20a2a44f72f5045e6e296cd2aa
[ "Apache-2.0" ]
null
null
null
src/main/java/com/groupdocs/signature/sample/TestRunner.java
liosha2007/groupdocs-signature-java-sample
84008e4970fa6e20a2a44f72f5045e6e296cd2aa
[ "Apache-2.0" ]
null
null
null
src/main/java/com/groupdocs/signature/sample/TestRunner.java
liosha2007/groupdocs-signature-java-sample
84008e4970fa6e20a2a44f72f5045e6e296cd2aa
[ "Apache-2.0" ]
null
null
null
36.959184
160
0.649089
1,003,472
package com.groupdocs.signature.sample; import com.groupdocs.signature.licensing.License; import com.groupdocs.signature.sample.operations.*; import com.groupdocs.signature.sample.tasks.CommonIssuesTests; import org.apache.commons.io.FileUtils; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import java.io.File; import java.io.IOException; /** * @author Aleksey Permyakov (01.02.2017) */ public class TestRunner { public static String PROJECT_PATH = new File("Data").getAbsolutePath(); public static String STORAGE_PATH = PROJECT_PATH + "\\Storage"; public static String OUTPUT_PATH = PROJECT_PATH + "\\Output"; public static String IMAGES_PATH = PROJECT_PATH + "\\Images"; public static String CERTIFICATES_PATH = PROJECT_PATH + "\\Certificates"; public static String LICENSE_PATH = STORAGE_PATH + "\\GroupDocs.Total.Java.lic"; /** * Main class to run tests * * @param args params */ public static void main(String[] args) throws IOException { applyLicense(); cleanOutput(); Result result = JUnitCore.runClasses( // CommonOperationsTests.class, // TextOperationsTests.class, // ImageOperationsTests.class, // DigitalOperationsTests.class, // OtherOperationsTests.class, CommonIssuesTests.class ); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); failure.getException().printStackTrace(); } System.out.println(String.format("=== SUCCESS: %d, FAIL: %d, IGNORE: %d ===", result.getRunCount(), result.getFailureCount(), result.getIgnoreCount())); } public static void applyLicense() { License lic = new License(); if (LICENSE_PATH != null && new File(LICENSE_PATH).exists()) { lic.setLicense(LICENSE_PATH); } } private static void cleanOutput() throws IOException { FileUtils.cleanDirectory(new File(OUTPUT_PATH)); } public static String getStoragePath(String fileName, String... subDirectories) { StringBuilder builder = new StringBuilder(STORAGE_PATH); for (String part : subDirectories) { builder.append(File.separator).append(part); } return builder.append(File.separator).append(fileName).toString(); } public static String getOutputPath(String fileName) { return OUTPUT_PATH + File.separator + fileName; } public static String getImagesPath(String fileName) { return IMAGES_PATH + File.separator + fileName; } public static String getCertificatePath(String fileName) { return CERTIFICATES_PATH + File.separator + fileName; } static { final java.io.File sp = new java.io.File(STORAGE_PATH); final java.io.File op = new java.io.File(OUTPUT_PATH); final java.io.File ip = new java.io.File(OUTPUT_PATH); final java.io.File cp = new java.io.File(CERTIFICATES_PATH); final java.io.File lcp = new java.io.File(LICENSE_PATH); if (!lcp.exists()) { LICENSE_PATH = System.getenv("GROUPDOCS_SIGNATURE"); System.out.println("License file does not exists! Using license from %GROUPDOCS_SIGNATURE% ..."); } if ((!sp.exists() && !sp.mkdirs()) || (!op.exists() && !op.mkdirs()) || (!ip.exists() && !ip.mkdirs()) || (!cp.exists() && !cp.mkdirs())) { System.err.println("Can't create data directories!!!"); } } }
9245a99e76acd84a4c7aaf7325c172b66594d115
373
java
Java
Dataset/Leetcode/valid/94/454.java
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/valid/94/454.java
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/valid/94/454.java
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
23.3125
46
0.541555
1,003,473
class Solution { public List<Integer> XXX(TreeNode root) { List<Integer> list=new LinkedList<>(); if(root==null){ return list; } List<Integer> list1=XXX(root.left); list.addAll(list1); list.add(root.val); List<Integer> list2=XXX(root.right); list.addAll(list2); return list; } }
9245a9aa9118b4a8a1657accada7644e36700545
7,826
java
Java
cdm-test/src/test/java/ucar/nc2/grid/TestTdsOtherGribCollections.java
AMateos91/netcdf-java
3fa552ede5b133ee1d6610f70473fbc00351d570
[ "BSD-3-Clause" ]
1
2021-11-23T15:40:34.000Z
2021-11-23T15:40:34.000Z
cdm-test/src/test/java/ucar/nc2/grid/TestTdsOtherGribCollections.java
AMateos91/netcdf-java
3fa552ede5b133ee1d6610f70473fbc00351d570
[ "BSD-3-Clause" ]
null
null
null
cdm-test/src/test/java/ucar/nc2/grid/TestTdsOtherGribCollections.java
AMateos91/netcdf-java
3fa552ede5b133ee1d6610f70473fbc00351d570
[ "BSD-3-Clause" ]
null
null
null
41.62766
120
0.668413
1,003,474
/* * Copyright (c) 1998-2020 John Caron and University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2.grid; import com.google.common.collect.Iterables; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import ucar.nc2.dataset.CoordinateAxis; import ucar.nc2.dt.GridDatatype; import ucar.unidata.util.StringUtil2; import ucar.unidata.util.test.TestDir; import ucar.unidata.util.test.category.NeedsCdmUnitTest; import java.io.FileFilter; import java.util.*; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; /** Compare reading TDS Grib Collections with old and new GridDataset. */ @RunWith(Parameterized.class) @Category(NeedsCdmUnitTest.class) public class TestTdsOtherGribCollections { private static final String topDir = TestDir.cdmUnitTestDir + "tds_index/"; @Parameterized.Parameters(name = "{0}") public static List<Object[]> getTestParameters() { FileFilter ff = TestDir.FileFilterSkipSuffix(".gbx9"); List<Object[]> result = new ArrayList<>(500); try { /// CMC /* * There are two separate grids here, with disjunct variables. These should possibly be separated into two * datasets, perhaps in the LDM feed? * PolarStereographic 190X245 -56,-99 * PolarStereographic 399X493- 60,-90 * Unidata TDS separated these into “Derived Fields” and “Model Fields”, see * https://thredds.ucar.edu/thredds/catalog/grib/CMC/RDPS/NA_15km/catalog.html */ result.add(new Object[] {topDir + "CMC/RDPS/NA_15km/CMC_RDPS_ps15km_20201027_0000.grib2.ncx4", 58, 17, 24}); // fnmoc result.add(new Object[] {topDir + "FNMOC/WW3/Global_1p0deg/FNMOC_WW3_Global_1p0deg.ncx4", 15, 1, 4}); result.add(new Object[] {topDir + "FNMOC/WW3/Europe/FNMOC_WW3_Europe.ncx4", 15, 2, 5}); result.add( new Object[] {topDir + "FNMOC/COAMPS/Southern_California/FNMOC_COAMPS_Southern_California.ncx4", 19, 5, 9}); result .add(new Object[] {topDir + "FNMOC/COAMPS/Northeast_Pacific/FNMOC_COAMPS_Northeast_Pacific.ncx4", 20, 5, 9}); result.add( new Object[] {topDir + "FNMOC/COAMPS/Equatorial_America/FNMOC_COAMPS_Equatorial_America.ncx4", 19, 5, 9}); result.add(new Object[] {topDir + "FNMOC/COAMPS/Europe/FNMOC_COAMPS_Europe.ncx4", 18, 5, 8}); result.add(new Object[] {topDir + "FNMOC/COAMPS/Western_Atlantic/FNMOC_COAMPS_Western_Atlantic.ncx4", 18, 7, 11}); result.add(new Object[] {topDir + "FNMOC/NAVGEM/Global_0p5deg/FNMOC_NAVGEM_Global_0p5deg.ncx4", 103, 37, 49}); // The HRRR/CONUS_3km/wrfprs is a mess with huge missing. validtime1 looks wrong // result.add(new Object[] {topDir + "NOAA_GSD/HRRR/CONUS_3km/wrfprs/GSD_HRRR_CONUS_3km_wrfprs.ncx4", 15, 1, 5}); result.add(new Object[] { topDir + "NOAA_GSD/HRRR/CONUS_3km/surface/HRRR_CONUS_3km_surface_202011230000.grib2.ncx4", 129, 36, 39}); result .add(new Object[] {topDir + "NOAA_GSD/HRRR/CONUS_3km/surface/GSD_HRRR_CONUS_3km_surface.ncx4", 129, 36, 38}); // TestDir.actOnAllParameterized(TestDir.cdmUnitTestDir + "ft/grid/", ff, result); } catch (Exception e) { e.printStackTrace(); } return result; } ///////////////////////////////////////////////////////////// @Parameterized.Parameter(0) public String filename; @Parameterized.Parameter(1) public int ngrids; @Parameterized.Parameter(2) public int ncoordSys; @Parameterized.Parameter(3) public int nAxes; @Test public void checkGridDataset() throws Exception { Formatter errlog = new Formatter(); try (GridDataset gridDataset = GridDatasetFactory.openGridDataset(filename, errlog)) { if (gridDataset == null) { System.out.printf("Cant open as GridDataset: %s%n", filename); return; } System.out.printf("%ncheckGridDataset: %s%n", gridDataset.getLocation()); assertThat(gridDataset.getGridCoordinateSystems()).hasSize(ncoordSys); assertThat(gridDataset.getGridAxes()).hasSize(nAxes); assertThat(gridDataset.getGrids()).hasSize(ngrids); HashSet<GridCoordinateSystem> csysSet = new HashSet<>(); HashSet<GridAxis> axisSet = new HashSet<>(); for (Grid grid : gridDataset.getGrids()) { csysSet.add(grid.getCoordinateSystem()); for (GridAxis axis : grid.getCoordinateSystem().getGridAxes()) { axisSet.add(axis); } } assertThat(csysSet).hasSize(ncoordSys); assertThat(axisSet).hasSize(nAxes); } } @Test public void compareGridDataset() throws Exception { boolean ok = true; Formatter errlog = new Formatter(); try (GridDataset newDataset = GridDatasetFactory.openGridDataset(filename, errlog); ucar.nc2.dt.grid.GridDataset dataset = ucar.nc2.dt.grid.GridDataset.open(filename)) { if (newDataset == null) { System.out.printf("Cant open as GridDataset: %s%n", filename); fail(); } System.out.printf(" NewGrid: %d %d %d %n", newDataset.getGrids().size(), newDataset.getGridCoordinateSystems().size(), newDataset.getGridAxes().size()); System.out.printf(" OldGrid: %d %d %n", dataset.getGrids().size(), dataset.getGridsets().size()); // assertThat(dataset.getGrids()).hasSize(2 * ngrids); // assertThat(dataset.getGridsets()).hasSize(2 * ncoordSys); for (Grid grid : newDataset.getGrids()) { GridDatatype geogrid = findInOld(grid.getName(), dataset); if (geogrid == null) { System.out.printf(" GeoGrid %s not in OldGrid%n", grid.getName()); ok = false; } else { if (!compareCoordinateNames(grid.getCoordinateSystem().getName(), geogrid.getCoordinateSystem().getName())) { System.out.printf(" Grid %s: %s%n", grid.getName(), grid.getCoordinateSystem().getName()); System.out.printf(" GeoGrid %s: %s%n%n", geogrid.getName(), geogrid.getCoordinateSystem().getName()); } } } for (GridDatatype geogrid : dataset.getGrids()) { if (geogrid.getName().startsWith("Best")) { continue; } String name = removeGroup(geogrid.getName()); if (!newDataset.findGrid(name).isPresent()) { CoordinateAxis timeAxis = geogrid.getCoordinateSystem().getTimeAxis(); System.out.printf(" GeoGrid %s not in NewGrid time=%s%n", name, timeAxis.getNameAndDimensions()); } } } assertThat(ok).isTrue(); } private GridDatatype findInOld(String want, ucar.nc2.dt.grid.GridDataset dataset) { for (GridDatatype geogrid : dataset.getGrids()) { if (removeGroup(geogrid.getName()).equals(want)) { return geogrid; } } return null; } private String removeGroup(String name) { int pos = name.indexOf("/"); return (pos < 0) ? name : name.substring(pos + 1); } private boolean compareCoordinateNames(String newName, String oldName) { boolean result = true; Iterable<String> oldNames = StringUtil2.split(oldName); Iterable<String> newNames = StringUtil2.split(newName); if (Iterables.size(oldNames) != Iterables.size(newNames)) { System.out.printf(" Old size = %d != %d%n", Iterables.size(oldNames), Iterables.size(newNames)); result = false; } Iterator<String> oldIter = oldNames.iterator(); Iterator<String> newIter = newNames.iterator(); while (oldIter.hasNext() && newIter.hasNext()) { String old = StringUtil2.remove(oldIter.next(), "TwoD/"); String nnn = StringUtil2.remove(newIter.next(), "Offset"); if (!old.equals(nnn)) { result = false; } } return result; } }
9245aa54e9ee4500db63747b53d01c43b6ab1a20
8,419
java
Java
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/assignment/GroovyAssignmentCanBeOperatorAssignmentInspection.java
liveqmock/platform-tools-idea
1c4b76108add6110898a7e3f8f70b970e352d3d4
[ "Apache-2.0" ]
2
2015-05-08T15:07:10.000Z
2022-03-09T05:47:53.000Z
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/assignment/GroovyAssignmentCanBeOperatorAssignmentInspection.java
lshain-android-source/tools-idea
b37108d841684bcc2af45a2539b75dd62c4e283c
[ "Apache-2.0" ]
null
null
null
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/assignment/GroovyAssignmentCanBeOperatorAssignmentInspection.java
lshain-android-source/tools-idea
b37108d841684bcc2af45a2539b75dd62c4e283c
[ "Apache-2.0" ]
2
2017-04-24T15:48:40.000Z
2022-03-09T05:48:05.000Z
33.541833
122
0.704122
1,003,475
/* * Copyright 2007-2008 Dave Griffith * * 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.jetbrains.plugins.groovy.codeInspection.assignment; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel; import com.intellij.openapi.project.Project; import com.intellij.psi.JavaTokenType; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.codeInspection.BaseInspection; import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor; import org.jetbrains.plugins.groovy.codeInspection.GroovyFix; import org.jetbrains.plugins.groovy.codeInspection.utils.EquivalenceChecker; import org.jetbrains.plugins.groovy.codeInspection.utils.SideEffectChecker; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrBinaryExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; import javax.swing.*; public class GroovyAssignmentCanBeOperatorAssignmentInspection extends BaseInspection { /** * @noinspection PublicField,WeakerAccess */ public boolean ignoreLazyOperators = true; /** * @noinspection PublicField,WeakerAccess */ public boolean ignoreObscureOperators = false; @Nls @NotNull public String getGroupDisplayName() { return ASSIGNMENT_ISSUES; } @NotNull public String getDisplayName() { return "Assignment replaceable with operator assignment"; } @NotNull public String buildErrorString(Object... infos) { final GrAssignmentExpression assignmentExpression = (GrAssignmentExpression) infos[0]; return "<code>#ref</code> could be simplified to '" + calculateReplacementExpression(assignmentExpression) + "' #loc"; } @Nullable public JComponent createOptionsPanel() { final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this); optionsPanel.addCheckbox("Ignore conditional operators", "ignoreLazyOperators"); optionsPanel.addCheckbox("Ignore obscure operators", "ignoreObscureOperators"); return optionsPanel; } static String calculateReplacementExpression( GrAssignmentExpression expression) { final GrExpression rhs = expression.getRValue(); final GrBinaryExpression binaryExpression = (GrBinaryExpression)PsiUtil.skipParentheses(rhs, false); final GrExpression lhs = expression.getLValue(); assert binaryExpression != null; final IElementType sign = binaryExpression.getOperationTokenType(); final GrExpression rhsRhs = binaryExpression.getRightOperand(); assert rhsRhs != null; String signText = getTextForOperator(sign); if ("&&".equals(signText)) { signText = "&"; } else if ("||".equals(signText)) { signText = "|"; } return lhs.getText() + ' ' + signText + "= " + rhsRhs.getText(); } public BaseInspectionVisitor buildVisitor() { return new ReplaceAssignmentWithOperatorAssignmentVisitor(); } public GroovyFix buildFix(PsiElement location) { return new ReplaceAssignmentWithOperatorAssignmentFix( (GrAssignmentExpression) location); } private static class ReplaceAssignmentWithOperatorAssignmentFix extends GroovyFix { private final String m_name; private ReplaceAssignmentWithOperatorAssignmentFix( GrAssignmentExpression expression) { super(); final GrExpression rhs = expression.getRValue(); final GrBinaryExpression binaryExpression = (GrBinaryExpression)PsiUtil.skipParentheses(rhs, false); assert binaryExpression != null; final IElementType sign = binaryExpression.getOperationTokenType(); String signText = getTextForOperator(sign); if ("&&".equals(signText)) { signText = "&"; } else if ("||".equals(signText)) { signText = "|"; } m_name = "Replace '=' with '" + signText + "='"; } @NotNull public String getName() { return m_name; } public void doFix(@NotNull Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiElement element = descriptor.getPsiElement(); if (!(element instanceof GrAssignmentExpression)) { return; } final GrAssignmentExpression expression = (GrAssignmentExpression) element; final String newExpression = calculateReplacementExpression(expression); replaceExpression(expression, newExpression); } } private class ReplaceAssignmentWithOperatorAssignmentVisitor extends BaseInspectionVisitor { public void visitAssignmentExpression(@NotNull GrAssignmentExpression assignment) { super.visitAssignmentExpression(assignment); final IElementType assignmentTokenType = assignment.getOperationTokenType(); if (!assignmentTokenType.equals(GroovyTokenTypes.mASSIGN)) { return; } final GrExpression lhs = assignment.getLValue(); final GrExpression rhs = (GrExpression)PsiUtil.skipParentheses(assignment.getRValue(), false); if (!(rhs instanceof GrBinaryExpression)) { return; } final GrBinaryExpression binaryRhs = (GrBinaryExpression) rhs; if (binaryRhs.getRightOperand() == null) { return; } final IElementType expressionTokenType = binaryRhs.getOperationTokenType(); if (getTextForOperator(expressionTokenType) == null) { return; } if (JavaTokenType.EQEQ.equals(expressionTokenType)) { return; } if (ignoreLazyOperators) { if (GroovyTokenTypes.mLAND.equals(expressionTokenType) || GroovyTokenTypes.mLOR.equals(expressionTokenType)) { return; } } if (ignoreObscureOperators) { if (GroovyTokenTypes.mBXOR.equals(expressionTokenType) || GroovyTokenTypes.mMOD.equals(expressionTokenType)) { return; } } final GrExpression lOperand = binaryRhs.getLeftOperand(); if (SideEffectChecker.mayHaveSideEffects(lhs)) { return; } if (!EquivalenceChecker.expressionsAreEquivalent(lhs, lOperand)) { return; } registerError(assignment, assignment); } } @Nullable @NonNls private static String getTextForOperator(IElementType operator) { if (operator == null) { return null; } if (operator.equals(GroovyTokenTypes.mPLUS)) { return "+"; } if (operator.equals(GroovyTokenTypes.mMINUS)) { return "-"; } if (operator.equals(GroovyTokenTypes.mSTAR)) { return "*"; } if (operator.equals(GroovyTokenTypes.mDIV)) { return "/"; } if (operator.equals(GroovyTokenTypes.mMOD)) { return "%"; } if (operator.equals(GroovyTokenTypes.mBXOR)) { return "^"; } if (operator.equals(GroovyTokenTypes.mLAND)) { return "&&"; } if (operator.equals(GroovyTokenTypes.mLOR)) { return "||"; } if (operator.equals(GroovyTokenTypes.mBAND)) { return "&"; } if (operator.equals(GroovyTokenTypes.mBOR)) { return "|"; } /* if (operator.equals(GroovyTokenTypes.mSR)) { return "<<"; } if (operator.equals(GroovyTokenTypes.GTGT)) { return ">>"; } if (operator.equals(GroovyTokenTypes.GTGTGT)) { return ">>>"; } */ return null; } }
9245aa60d9def435bb348a18fd034557fd714709
1,345
java
Java
src/main/java/nl/vu/datalayer/hbase/coprocessor/MapOnlyLoader.java
pgroth/hbase-rdf
fed610248dff4e5f70d50f6c1ded06b638580434
[ "Apache-2.0" ]
5
2015-05-10T03:56:38.000Z
2021-01-19T00:41:42.000Z
src/main/java/nl/vu/datalayer/hbase/coprocessor/MapOnlyLoader.java
pgroth/hbase-rdf
fed610248dff4e5f70d50f6c1ded06b638580434
[ "Apache-2.0" ]
null
null
null
src/main/java/nl/vu/datalayer/hbase/coprocessor/MapOnlyLoader.java
pgroth/hbase-rdf
fed610248dff4e5f70d50f6c1ded06b638580434
[ "Apache-2.0" ]
8
2015-01-05T07:00:05.000Z
2019-07-13T14:36:08.000Z
30.568182
128
0.783643
1,003,476
package nl.vu.datalayer.hbase.coprocessor; import java.io.IOException; import nl.vu.datalayer.hbase.schema.HBPrefixMatchSchema; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.io.NullWritable; public class MapOnlyLoader { public static class Mapper extends org.apache.hadoop.mapreduce.Mapper<NullWritable, ImmutableBytesWritable, NullWritable, NullWritable> { private HTable spocTable; @Override protected void cleanup(Context context) throws IOException, InterruptedException { spocTable.close(); } @Override protected void setup(Context context) throws IOException, InterruptedException { String suffix = context.getConfiguration().get("SUFFIX"); spocTable = new HTable(HBaseConfiguration.create(), HBPrefixMatchSchema.TABLE_NAMES[HBPrefixMatchSchema.SPOC]+suffix); spocTable.setAutoFlush(false); } @Override protected void map(NullWritable key, ImmutableBytesWritable value, Context context) throws IOException, InterruptedException { Put outValue = new Put(value.get()); outValue.add(HBPrefixMatchSchema.COLUMN_FAMILY, HBPrefixMatchSchema.COLUMN_NAME, null); spocTable.put(outValue); } } }
9245aab6b3d9a76ad271fe98e463e5410909c04b
1,269
java
Java
library/src/main/java/com/meisolsson/githubsdk/service/checks/ChecksService.java
Unpublished/GitHubSdk
4b4e0db62a0fb638a0eb60d6dcf43ea4954a8eec
[ "Apache-2.0" ]
1
2018-09-13T15:30:21.000Z
2018-09-13T15:30:21.000Z
library/src/main/java/com/meisolsson/githubsdk/service/checks/ChecksService.java
Unpublished/GitHubSdk
4b4e0db62a0fb638a0eb60d6dcf43ea4954a8eec
[ "Apache-2.0" ]
null
null
null
library/src/main/java/com/meisolsson/githubsdk/service/checks/ChecksService.java
Unpublished/GitHubSdk
4b4e0db62a0fb638a0eb60d6dcf43ea4954a8eec
[ "Apache-2.0" ]
null
null
null
37.323529
140
0.743105
1,003,477
/* * Copyright 2015 Henrik Olsson * * 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.meisolsson.githubsdk.service.checks; import com.meisolsson.githubsdk.model.CheckRun; import com.meisolsson.githubsdk.model.CheckRunsResponse; import io.reactivex.Single; import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Path; public interface ChecksService { @GET("repos/{owner}/{repo}/check-runs/{id}") Single<Response<CheckRun>> getCheckRun(@Path("owner") String owner, @Path("repo") String repo, @Path("id") long id); @GET("repos/{owner}/{repo}/commits/{ref}/check-runs") Single<Response<CheckRunsResponse>> getCheckRunsForRef(@Path("owner") String owner, @Path("repo") String repo, @Path("ref") String ref); }
9245ab4063a270e484c6a3a92c218f8ec63b535a
709
java
Java
app/src/main/java/com/fishweather/android/db/Province.java
JasonJunjian/FishWeather
05517cdfd327d938d8b8e86ae3c3342c22f17855
[ "Apache-2.0" ]
1
2017-08-24T09:20:07.000Z
2017-08-24T09:20:07.000Z
app/src/main/java/com/fishweather/android/db/Province.java
JasonJunjian/FishWeather
05517cdfd327d938d8b8e86ae3c3342c22f17855
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/fishweather/android/db/Province.java
JasonJunjian/FishWeather
05517cdfd327d938d8b8e86ae3c3342c22f17855
[ "Apache-2.0" ]
null
null
null
18.179487
54
0.641749
1,003,478
package com.fishweather.android.db; import org.litepal.crud.DataSupport; /** * Created by yujj on 2017/8/16. */ public class Province extends DataSupport { public int getId() { return id; } public void setId(int id) { this.id = id; } public String getProvinceName() { return provinceName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName; } public int getProvinceCode() { return provinceCode; } public void setProvinceCode(int provinceCode) { this.provinceCode = provinceCode; } private int id; private String provinceName; private int provinceCode; }
9245ab5870cecc93ae0cc163970b2f4c1de0d91a
64,497
java
Java
src/java/us/paulevans/basicxslt/BasicXSLTFrame.java
evanspa/Basic-XSLT
edc7e099e98efb42f36b57fcb217de7435b49e73
[ "Apache-2.0" ]
null
null
null
src/java/us/paulevans/basicxslt/BasicXSLTFrame.java
evanspa/Basic-XSLT
edc7e099e98efb42f36b57fcb217de7435b49e73
[ "Apache-2.0" ]
null
null
null
src/java/us/paulevans/basicxslt/BasicXSLTFrame.java
evanspa/Basic-XSLT
edc7e099e98efb42f36b57fcb217de7435b49e73
[ "Apache-2.0" ]
null
null
null
36.687713
83
0.688001
1,003,479
/* Copyright 2006 Paul Evans 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 us.paulevans.basicxslt; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.SocketException; import java.net.UnknownHostException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.border.BevelBorder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import net.blueslate.commons.gui.GUIUtils; import net.blueslate.commons.io.IOUtils; import net.blueslate.commons.xml.TransformOutputProperties; import net.blueslate.commons.xml.TransformParameters; import net.blueslate.commons.xml.XMLUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.vfs.FileContent; import org.apache.commons.vfs.FileSystemManager; import org.apache.commons.vfs.VFS; import org.apache.log4j.Logger; import org.xml.sax.SAXException; /** * Defines the main application window. * @author pevans * */ public class BasicXSLTFrame extends JFrame implements ActionListener, Runnable { // static members... private static UserPreferences userPrefs; private static String lastFileChosen; private static FileSystemManager fsManager; // get the i18n factory singleton instance... private static final LabelStringFactory stringFactory = LabelStringFactory.getInstance(); // constants used by Runnable... private static final int THREADMODE_DO_TRANSFORM = 0; private static final int THREADMODE_DO_VALIDATE = 1; private static final int THREADMODE_DO_XML_IDENTITY_TRANSFORM = 2; // constants... private static final int XML_VALIDATE_ACTION_INDEX = 2; private static final int XML_VIEW_EDIT_OUTPUT_PROPS_INDEX = 3; private static final int XML_CLEAR_OUTPUT_PROPS_INDEX = 4; private static final int XML_DO_IDENTITY_TRANSFORM_ACTION_INDEX = 5; // default frame width and height - these values are used if // a height and width are not found in the user's preferences... private static final String DEFAULT_FRAME_WIDTH = "930"; private static final String DEFAULT_FRAME_HEIGHT = "415"; // XML action labels... private static final String XML_ACTIONS[] = { stringFactory.getString(LabelStringFactory.XML_ACTION_TAKE_ACTION), AppConstants.SEPARATOR, stringFactory.getString(LabelStringFactory.XML_ACTION_VALIDATE), stringFactory.getString( LabelStringFactory.XML_ACTION_IT_OUTPUT_PROPERITES), stringFactory.getString( LabelStringFactory.XML_ACTION_CLEAR_IT_PROPERTIES), stringFactory.getString(LabelStringFactory.XML_ACTION_PERFORM_IT) }; // logger object... private static final Logger logger = Logger.getLogger(BasicXSLTFrame.class); // instance members... private int threadMode; private String label, identityTransformMessage; private String identityTransformSourceXmlFile, identityTransformResultXmlFile; private JTextField textField; private boolean suppressSuccessDialog; private List<Component> components; private JTextField sourceXmlTf, autosavePathTf; private List<XSLRow> xslRows; private JPanel xslPanel; private GridBagLayout xslPanelLayout; private GridBagConstraints xslPanelConstraints; private JLabel transformTimeLabel, currentConfigLabel, outputAsTextIfXmlLabel, xmlIndicatorLabel; private JButton exitBtn, transformBtn, addXslBtn, removeCheckedBtn, validateAutosaveBtn; private JComboBox xmlAction; private JButton browseXmlBtn, browseAutosavePathBtn; private JCheckBoxMenuItem checkSaxWarning, checkSaxError, checkSaxFatalError; private JCheckBox autosaveCb, suppressOutputWindowCb, outputAsTextIfXml; private JMenuItem exit, about, resetForm, transformTimings, saveConfiguration, saveAsConfiguration, loadConfiguration; private long lastTotalTransformTime; private TransformOutputProperties xmlIdentityTransformOutputProps; private boolean areXmlOutputPropertiesSet; /** * private class constructor */ private BasicXSLTFrame() throws IOException { int width, height; fsManager = VFS.getManager(); userPrefs = Utils.getUserPrefs(); userPrefs.loadDefaultConfiguration(); lastFileChosen = userPrefs.getProperty(AppConstants.LAST_FILE_CHOSEN_PROP); components = new ArrayList<Component>(); buildGui(); setTitle(stringFactory.getString( LabelStringFactory.MAIN_FRAME_TITLE_BAR)); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { destroy(); } }); width = Integer.parseInt(userPrefs.getProperty( AppConstants.FRAME_WIDTH_PROP, DEFAULT_FRAME_WIDTH)); height = Integer.parseInt(userPrefs.getProperty( AppConstants.FRAME_HEIGHT_PROP, DEFAULT_FRAME_HEIGHT)); setSize(width, height); initializeControls(); setToolTips(); setVisible(true); } /** * Set the various tool-tips on the GUI components. * */ private void setToolTips() { transformTimings.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_TRANSFORM_TIMINGS)); xmlAction.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_XML_ACTION)); transformBtn.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_TRANSFORM_BTN)); exitBtn.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_EXIT_BTN)); addXslBtn.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_ADD_XSL_BTN)); removeCheckedBtn.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_REMOVE_CHECKED_BTN)); validateAutosaveBtn.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_VALIDATE_AUTOSAVE_BTN)); autosavePathTf.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_AUTOSAVE_TEXTFIELD)); sourceXmlTf.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_SOURCE_XML_TEXTFIELD)); browseAutosavePathBtn.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_BROWSE_AUTOSAVE_PATH_BTN)); browseXmlBtn.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_BROWSE_XML_BTN)); suppressOutputWindowCb.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_SUPPRESS_OUTPUT_WINDOW_CB)); autosaveCb.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_AUTOSAVE_CB)); outputAsTextIfXml.setToolTipText(stringFactory.getString( LabelStringFactory.TOOL_TIP_OUTPUT_AS_TEXT_IF_XML_CB)); } private static void loadParameters(XSLRow aXSLRow) { // local declarations... TransformParameters parameters; Enumeration propertyNames; String propName, propValue, prefix; int index; parameters = aXSLRow.getTransformParameters(); propertyNames = userPrefs.propertyNames(); prefix = userPrefs.getConfiguration() + ".xsl_" + aXSLRow.getIndex() + "_params_"; while (propertyNames.hasMoreElements()) { propName = (String)propertyNames.nextElement(); if (propName.startsWith(prefix)) { propValue = userPrefs.getPropertyNoPrefix(propName); index = propName.indexOf('{'); if (index != -1) { propName = propName.substring(index); } else { index = propName.indexOf("_", prefix.length()); propName = propName.substring(index + 1); } parameters.setParameter( TransformParameters.getNamespaceURI(propName), TransformParameters.getParameterName(propName), propValue); } } } /** * Load the output properties on the aOutputProperties object from the * user's preferences. * @param aOutputProperties * @param aPropertyNamePrefix */ private void loadOutputProperties( TransformOutputProperties aOutputProperties, String aPropertyNamePrefix) { aOutputProperties.setCDATA_SECTION_ELEMENTS( StringUtils.defaultString(userPrefs.getProperty( aPropertyNamePrefix + AppConstants.CDATA_SECTION_ELEMENTS))); aOutputProperties.setDOCTYPE_PUBLIC( StringUtils.defaultString(userPrefs.getProperty( aPropertyNamePrefix + AppConstants.DOCTYPE_PUBLIC))); aOutputProperties.setDOCTYPE_SYSTEM( StringUtils.defaultString(userPrefs.getProperty( aPropertyNamePrefix + AppConstants.DOCTYPE_SYSTEM))); aOutputProperties.setENCODING( StringUtils.defaultString(userPrefs.getProperty( aPropertyNamePrefix + AppConstants.ENCODING))); aOutputProperties.setINDENT(BooleanUtils.toBoolean( userPrefs.getProperty(aPropertyNamePrefix + AppConstants.INDENT))); aOutputProperties.setMEDIA_TYPE( StringUtils.defaultString(userPrefs.getProperty( aPropertyNamePrefix + AppConstants.MEDIA_TYPE))); aOutputProperties.setMETHOD( StringUtils.defaultString(userPrefs.getProperty( aPropertyNamePrefix + AppConstants.METHOD))); aOutputProperties.setOMIT_XML_DECLARATION( BooleanUtils.toBoolean(userPrefs.getProperty( aPropertyNamePrefix + AppConstants.OMIT_XML_DECLARATION))); aOutputProperties.setSTANDALONE( BooleanUtils.toBoolean(userPrefs.getProperty( aPropertyNamePrefix + AppConstants.STANDALONE))); aOutputProperties.setVERSION( StringUtils.defaultString(userPrefs.getProperty( aPropertyNamePrefix + AppConstants.VERSION))); } /** * Initialize the gui * */ private void initializeControls() { String val, xCoord, yCoord, propertyNamePrefix; boolean areGoodCoordinates; int loop; XSLRow xslRow; loop = 0; val = userPrefs.getProperty(AppConstants.CHK_WARNINGS_PROP); checkSaxWarning.setSelected(val != null ? Boolean.valueOf(val).booleanValue() : false); val = userPrefs.getProperty(AppConstants.CHK_ERRORS_PROP); checkSaxError.setSelected(val != null ? Boolean.valueOf(val).booleanValue() : false); val = userPrefs.getProperty(AppConstants.CHK_FATAL_ERRORS_PROP); checkSaxFatalError.setSelected(val != null ? Boolean.valueOf(val).booleanValue() : false); xCoord = userPrefs.getProperty(AppConstants.X_COORD_PROP); yCoord = userPrefs.getProperty(AppConstants.Y_COORD_PROP); areGoodCoordinates = false; if (xCoord != null && yCoord != null) { this.setLocation(Integer.parseInt(xCoord), Integer.parseInt(yCoord)); areGoodCoordinates = true; } if (!areGoodCoordinates) { GUIUtils.center(this, null); } sourceXmlTf.setText(userPrefs.getProperty( AppConstants.LAST_XML_FILE_PROP)); val = userPrefs.getProperty(AppConstants.SUPPRESS_OUTPUT_WINDOW_PROP); suppressOutputWindowCb.setSelected(BooleanUtils.toBoolean(val)); val = userPrefs.getProperty(AppConstants.OUTPUT_AS_TEXT_IF_XML_PROP); outputAsTextIfXml.setSelected(BooleanUtils.toBoolean(val)); outputAsTextIfXmlLabel.setEnabled(!suppressOutputWindowCb.isSelected()); outputAsTextIfXml.setEnabled(!suppressOutputWindowCb.isSelected()); val = userPrefs.getProperty(AppConstants.AUTOSAVE_RESULT_PROP); autosaveCb.setSelected(BooleanUtils.toBoolean(val)); autosavePathTf.setText(userPrefs.getProperty( AppConstants.AUTOSAVE_FILE_PROP)); autosavePathTf.setEnabled(autosaveCb.isSelected()); browseAutosavePathBtn.setEnabled(autosaveCb.isSelected()); removeCheckedBtn.setEnabled(false); xmlIdentityTransformOutputProps = new TransformOutputProperties(); // load xml output props from user prefs val = userPrefs.getProperty("xml_identity_transform_opInd"); setAreOutputPropertiesSet(BooleanUtils.toBoolean(val)); loadOutputProperties(xmlIdentityTransformOutputProps, "xml_identity_transform_outputproperties_"); refreshXmlIndicatorLabel(); do { propertyNamePrefix = "xsl_" + loop + "_outputproperties_"; val = userPrefs.getProperty("xsl_" + loop + "_file"); if (val != null) { xslRow = xslRows.get(loop); loadParameters(xslRow); xslRow.getTextField().setText(val); val = userPrefs.getProperty("xsl_" + loop + "_onoff"); xslRow.setOn(BooleanUtils.toBoolean(val)); val = userPrefs.getProperty("xsl_" + loop + "_opInd"); xslRow.setAreOutputPropertiesSet(BooleanUtils.toBoolean(val)); loadOutputProperties(xslRow.getTransformOutputProperties(), propertyNamePrefix); loop++; } } while (val != null); } public static void setLastFileChosen(String aLastFileChosen) { lastFileChosen = aLastFileChosen; userPrefs.setProperty(AppConstants.LAST_FILE_CHOSEN_PROP, lastFileChosen); } /** * Create the menubar. * */ private void buildMenuBar() { // local declarations... JMenuBar menuBar; JMenu help, file, validation, view; // build the file menu and associated menu items... file = new JMenu(stringFactory.getString(LabelStringFactory.MF_FILE_MENU)); file.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_FILE_MENU)); resetForm = new JMenuItem(stringFactory.getString( LabelStringFactory.MF_FILE_RESET_FORM_MI)); resetForm.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_FILE_RESET_FORM_MI)); resetForm.addActionListener(this); file.add(resetForm); file.add(new JSeparator()); file.add(loadConfiguration = new JMenuItem(stringFactory.getString( LabelStringFactory.MF_FILE_LOAD_CONFIGURATION_MI))); loadConfiguration.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_FILE_LOAD_CONFIGURATION_MI)); file.add(saveConfiguration = new JMenuItem(stringFactory.getString( LabelStringFactory.MF_FILE_SAVE_CONFIGURATION_MI))); saveConfiguration.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_FILE_SAVE_CONFIGURATION_MI)); file.add(saveAsConfiguration = new JMenuItem(stringFactory.getString( LabelStringFactory.MF_FILE_SAVE_CONFIGURATION_AS_MI))); saveAsConfiguration.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_FILE_SAVE_CONFIGURATION_AS_MI)); loadConfiguration.addActionListener(this); saveConfiguration.addActionListener(this); saveAsConfiguration.addActionListener(this); file.add(new JSeparator()); exit = new JMenuItem(stringFactory.getString( LabelStringFactory.MF_FILE_EXIT_MI)); exit.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_FILE_EXIT_MI)); exit.addActionListener(this); file.add(exit); // build the validation menu and associated menu items... validation = new JMenu(stringFactory.getString( LabelStringFactory.MF_VALIDATION_MENU)); validation.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_VALIDATION_MENU)); validation.add(checkSaxWarning = new JCheckBoxMenuItem( stringFactory.getString( LabelStringFactory.MF_VALIDATION_CHECK_SAX_WARNINGS_MI))); checkSaxWarning.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_VALIDATION_CHECK_SAX_WARNINGS_MI)); validation.add(checkSaxError = new JCheckBoxMenuItem( stringFactory.getString( LabelStringFactory.MF_VALIDATION_CHECK_SAX_ERRORS_MI))); checkSaxError.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_VALIDATION_CHECK_SAX_ERRORS_MI)); validation.add(checkSaxFatalError = new JCheckBoxMenuItem( stringFactory.getString( LabelStringFactory.MF_VALIDATION_CHECK_SAX_FATAL_MI))); checkSaxFatalError.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_VALIDATION_CHECK_SAX_FATAL_MI)); // build the view menu and associate menu items... view = new JMenu(stringFactory.getString(LabelStringFactory.MF_VIEW_MENU)); view.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_VIEW_MENU)); view.add(transformTimings = new JMenuItem(stringFactory.getString( LabelStringFactory.MF_VIEW_LAST_TIMINGS_MI))); transformTimings.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_VIEW_LAST_TIMINGS_MI)); transformTimings.setEnabled(false); transformTimings.addActionListener(this); // build the help menu and associated menu items... help = new JMenu(stringFactory.getString(LabelStringFactory.MF_HELP_MENU)); help.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_HELP_MENU)); about = new JMenuItem(stringFactory.getString( LabelStringFactory.MF_HELP_ABOUT_MI)); about.setMnemonic(stringFactory.getMnemonic( LabelStringFactory.MF_HELP_ABOUT_MI)); about.addActionListener(this); help.add(about); // build the menubar... menuBar = new JMenuBar(); menuBar.add(file); menuBar.add(validation); menuBar.add(view); menuBar.add(help); setJMenuBar(menuBar); } /** * Rebuilds the XSL panel; first it removes all of the components; and then * it loops over the xslRows object and re-adds the components. * */ private void rebuildXSLPanel() { int loop, size; int col, xslPanelRow; JTextField xslTf; JButton browseXslBtn, insertBtn; JComboBox action; JLabel xslLabel, indicatorLabel; JCheckBox removeCb; XSLRow xslRow; xslPanel.removeAll(); xslPanelRow = 0; GUIUtils.add(xslPanel, new JLabel(""), xslPanelLayout, xslPanelConstraints, xslPanelRow, col=0, 1, 1, GridBagConstraints.EAST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, new JLabel(stringFactory.getString( LabelStringFactory.MAIN_FRAME_XML_FILE_WITH_COLON)), xslPanelLayout, xslPanelConstraints, xslPanelRow, ++col, 1, 1, GridBagConstraints.EAST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, sourceXmlTf, xslPanelLayout, xslPanelConstraints, xslPanelRow, ++col, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, new JLabel(""), xslPanelLayout, xslPanelConstraints, xslPanelRow, ++col, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, browseXmlBtn, xslPanelLayout, xslPanelConstraints, xslPanelRow, ++col, 1, 1, GridBagConstraints.EAST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, xmlAction, xslPanelLayout, xslPanelConstraints, xslPanelRow, ++col, 1, 1, GridBagConstraints.EAST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, xmlIndicatorLabel, xslPanelLayout, xslPanelConstraints, xslPanelRow++, ++col, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); size = xslRows.size(); for (loop = 0; loop < size; loop++) { xslRow = xslRows.get(loop); xslLabel = xslRow.getLabel(); xslTf = xslRow.getTextField(); removeCb = xslRow.getRemoveCb(); browseXslBtn = xslRow.getBrowseBtn(); insertBtn = xslRow.getInsertBtn(); indicatorLabel = xslRow.getIndicatorLabel(); action = xslRow.getAction(); GUIUtils.add(xslPanel, insertBtn, xslPanelLayout, xslPanelConstraints, xslPanelRow, col=0, 1, 1, GridBagConstraints.EAST, GridBagConstraints.EAST, GUIUtils.NO_INSETS); GUIUtils.add(xslPanel, xslLabel, xslPanelLayout, xslPanelConstraints, xslPanelRow, ++col, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, xslTf, xslPanelLayout, xslPanelConstraints, xslPanelRow, ++col, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, removeCb, xslPanelLayout, xslPanelConstraints, xslPanelRow, ++col, 1, 1, GridBagConstraints.EAST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, browseXslBtn, xslPanelLayout, xslPanelConstraints, xslPanelRow, ++col, 1, 1, GridBagConstraints.EAST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, action, xslPanelLayout, xslPanelConstraints, xslPanelRow, ++col, 1, 1, GridBagConstraints.EAST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); GUIUtils.add(xslPanel, indicatorLabel, xslPanelLayout, xslPanelConstraints, xslPanelRow++, ++col, 1, 1, GridBagConstraints.EAST, GridBagConstraints.BOTH, GUIUtils.SMALL_INSETS); } } /** * Refreshes the stylesheets panel * */ private void refreshStylesheets() { int loop; int numStylesheets; numStylesheets = Integer.parseInt(userPrefs.getProperty( AppConstants.NUM_STYLESHEETS_PROP, AppConstants.DEFAULT_NUM_STYLESHEETS)); xslRows.clear(); for (loop = 0; loop < numStylesheets; loop++) { addXSLRow(); } rebuildXSLPanel(); } /** * Setter * @param aAreOutputPropertiesSet */ public void setAreOutputPropertiesSet(boolean aAreOutputPropertiesSet) { areXmlOutputPropertiesSet = aAreOutputPropertiesSet; refreshXmlIndicatorLabel(); } /** * Refreshes the XML indicator label and tool-tip * */ private void refreshXmlIndicatorLabel() { StringBuffer labelText; StringBuffer toolTip; labelText = new StringBuffer(); toolTip = new StringBuffer(); if (areXmlOutputPropertiesSet) { labelText.append(stringFactory.getString( LabelStringFactory.MAIN_FRAME_XML_INDICATOR_ITOPSPECIFIED)); toolTip.append(stringFactory.getString( LabelStringFactory. MAIN_FRAME_XML_INDICATOR_ITOPSPECIFIED_TOOL_TIP)); } xmlIndicatorLabel.setText(labelText.toString()); xmlIndicatorLabel.setToolTipText(toolTip.toString()); } /** * Method to build the GUI */ private void buildGui() { JPanel centerPanel; buildMenuBar(); JScrollPane stylesheetsPane; xslPanelLayout = new GridBagLayout(); xslPanelConstraints = new GridBagConstraints(); centerPanel = new JPanel(); xslPanel = new JPanel(xslPanelLayout); stylesheetsPane = new JScrollPane(xslPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); sourceXmlTf = new JTextField(AppConstants.TF_LENGTH); browseXmlBtn = new JButton(stringFactory.getString( LabelStringFactory.MAIN_FRAME_BROWSE_BTN)); xmlAction = new JComboBox(XML_ACTIONS); browseXmlBtn.addActionListener(this); xmlIndicatorLabel = new JLabel(""); xmlIndicatorLabel.setFont(new Font("arial", Font.PLAIN, 10)); xmlAction.addActionListener(this); xslRows = new ArrayList<XSLRow>(); refreshStylesheets(); centerPanel.setLayout(new BorderLayout()); centerPanel.add(stylesheetsPane, BorderLayout.CENTER); centerPanel.add(new JScrollPane(buildAutosavePanel(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.SOUTH); browseAutosavePathBtn.addActionListener(this); getContentPane().setLayout(new BorderLayout()); getContentPane().add(buildNorthPanel(), BorderLayout.NORTH); getContentPane().add(centerPanel, BorderLayout.CENTER); getContentPane().add(buildSouthPanel(), BorderLayout.SOUTH); } /** * Builds the north/top-most panel and returns it. * @return */ private JPanel buildNorthPanel() { JPanel northPanel; JLabel title; northPanel = new JPanel(new FlowLayout()); title = new JLabel(stringFactory.getString( LabelStringFactory.MAIN_FRAME_TITLE)); title.setFont(new Font("helvetica", Font.BOLD, 18)); northPanel.add(title); return northPanel; } /** * Builds the auto-save panel * @return */ private JPanel buildAutosavePanel() { int row; JPanel buttons; JPanel autosavePanel; row = 0; buttons = new JPanel(new FlowLayout(FlowLayout.LEFT)); buttons.add(addXslBtn = new JButton(stringFactory.getString( LabelStringFactory.MAIN_FRAME_ADD_XSL_BTN))); buttons.add(removeCheckedBtn = new JButton( stringFactory.getString( LabelStringFactory.MAIN_FRAME_REMOVE_CHECKED_BTN))); addXslBtn.addActionListener(this); removeCheckedBtn.addActionListener(this); autosavePanel = new JPanel(xslPanelLayout); GUIUtils.add(autosavePanel, buttons, xslPanelLayout, xslPanelConstraints, row++, 0, 1, 3, GridBagConstraints.WEST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); GUIUtils.add(autosavePanel, new JLabel(stringFactory.getString( LabelStringFactory.MAIN_FRAME_AUTOSAVERESULT)), xslPanelLayout, xslPanelConstraints, row, 0, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); GUIUtils.add(autosavePanel, autosaveCb = new JCheckBox(), xslPanelLayout, xslPanelConstraints, row, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); autosaveCb.addActionListener(this); GUIUtils.add(autosavePanel, autosavePathTf = new JTextField( AppConstants.TF_LENGTH-4), xslPanelLayout, xslPanelConstraints, row, 2, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); GUIUtils.add(autosavePanel, browseAutosavePathBtn = new JButton( stringFactory.getString( LabelStringFactory.MAIN_FRAME_BROWSE_BTN)), xslPanelLayout, xslPanelConstraints, row, 3, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); GUIUtils.add(autosavePanel, validateAutosaveBtn = new JButton( stringFactory.getString( LabelStringFactory.MAIN_FRAME_VALIDATE_BTN)), xslPanelLayout, xslPanelConstraints, row++, 4, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); validateAutosaveBtn.addActionListener(this); GUIUtils.add(autosavePanel, new JLabel(stringFactory.getString( LabelStringFactory.MAIN_FRAME_SUPRESS_OUTPUT_WINDOW)), xslPanelLayout, xslPanelConstraints, row, 0, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); GUIUtils.add(autosavePanel, suppressOutputWindowCb = new JCheckBox(), xslPanelLayout, xslPanelConstraints, row++, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); GUIUtils.add(autosavePanel, outputAsTextIfXmlLabel = new JLabel( stringFactory.getString( LabelStringFactory. MAIN_FRAME_DISPLAY_OUTPUT_AS_TEXT_IF_XML)), xslPanelLayout, xslPanelConstraints, row, 0, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); GUIUtils.add(autosavePanel, outputAsTextIfXml = new JCheckBox(), xslPanelLayout, xslPanelConstraints, row++, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, GUIUtils.SMALL_INSETS); suppressOutputWindowCb.addActionListener(this); return autosavePanel; } /** * Builds the south panel * @return */ private JPanel buildSouthPanel() { JPanel transformBtnPanel; JPanel footerPanel; JPanel southPanel; JPanel panel; JLabel label; Font footerPanelFont; Font footerPanelFontBold; transformBtnPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); transformBtnPanel.add(transformBtn = new JButton( stringFactory.getString( LabelStringFactory.MAIN_FRAME_TRANSFORM_BTN))); transformBtnPanel.add(exitBtn = new JButton(stringFactory.getString( LabelStringFactory.MAIN_FRAME_EXIT_BTN))); footerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); southPanel = new JPanel(new BorderLayout()); southPanel.add(transformBtnPanel, BorderLayout.CENTER); southPanel.add(footerPanel, BorderLayout.SOUTH); footerPanelFont = new Font("arial", Font.PLAIN, 12); footerPanelFontBold = new Font("arial", Font.BOLD, 12); footerPanel.setBorder(BorderFactory.createBevelBorder( BevelBorder.LOWERED)); panel = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel.add(label = new JLabel(stringFactory.getString( LabelStringFactory.MAIN_FRAME_CURRENT_CONFIGURATION))); label.setFont(footerPanelFontBold); label.setForeground(Color.BLUE); panel.add(currentConfigLabel = new JLabel( userPrefs.getConfiguration())); currentConfigLabel.setFont(footerPanelFont); footerPanel.add(panel); panel = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel.add(label = new JLabel(stringFactory.getString( LabelStringFactory.MAIN_FRAME_TOTAL_TRANSFORM_TIME))); label.setFont(footerPanelFontBold); label.setForeground(Color.BLUE); panel.add(transformTimeLabel = new JLabel(lastTotalTransformTime + " " + stringFactory.getString(LabelStringFactory. MAIN_FRAME_MILLISECONDS_ABBREVIATION))); transformTimeLabel.setFont(footerPanelFont); footerPanel.add(panel); transformTimeLabel.setFont(footerPanelFont); footerPanel.add(new JLabel("")); footerPanel.add(new JLabel("")); transformBtn.addActionListener(this); exitBtn.addActionListener(this); return southPanel; } /** * Displays the 'about' dialog * */ private void about() { StringBuffer aboutMsg; aboutMsg = new StringBuffer(); aboutMsg.append(stringFactory.getString( LabelStringFactory.TOOL_ABOUTDIALOG_TOOLTITLE) + "\n\n"); aboutMsg.append(stringFactory.getString( LabelStringFactory.TOOL_ABOUTDIALOG_VERSION)).append( AppConstants.APP_VERSION).append("\n\n"); aboutMsg.append(stringFactory.getString( LabelStringFactory.TOOL_DESCRIPTION)).append("\n\n"); aboutMsg.append(stringFactory.getString( LabelStringFactory.TOOL_DEVELOPED_BY) + "\n\n"); aboutMsg.append(stringFactory.getString( LabelStringFactory.TOOL_LICENSE)); Utils.showDialog(this, aboutMsg.toString(), stringFactory.getString( LabelStringFactory.TOOL_ABOUTDIALOG_TITLE), JOptionPane.INFORMATION_MESSAGE); } /** * Returns if aTextField is empty or not * @param aTextField * @return */ private static boolean isEmpty(JTextField aTextField) { return StringUtils.isBlank(aTextField.getText()); } /** * Returns if the path specified in aFileTextField points to a valid * file or not. * @param aFileTextField * @return */ private static boolean isValidFile(JTextField aFileTextField) { try { fsManager.resolveFile(aFileTextField.getText()); return true; } catch (Throwable any) { return false; } } /** * Validates the xml file pointed-to by aTextField. * @param aLabel * @param aTextField * @param aSuppressSuccessDialog * @return */ private boolean validateXml(String aLabel, JTextField aTextField, boolean aSuppressSuccessDialog) { boolean isValid; isValid = false; if (isEmpty(aTextField)) { Utils.showDialog(this, stringFactory.getString( LabelStringFactory.MAIN_FRAME_XML_FILE_NOT_SPECIFIED), stringFactory.getString( LabelStringFactory.MAIN_FRAME_ERROR_LBL), JOptionPane.ERROR_MESSAGE); } else if (!isValidFile(aTextField)) { Utils.showDialog(this, stringFactory.getString( LabelStringFactory. MAIN_FRAME_XML_FILE_NOT_EXIST_SPECIFY_VALID_FILE), stringFactory.getString( LabelStringFactory.MAIN_FRAME_ERROR_LBL), JOptionPane.ERROR_MESSAGE); } else { isValid = validateXml(aLabel, aTextField.getText(), checkSaxWarning.isSelected(), checkSaxError.isSelected(), checkSaxFatalError.isSelected(), this, aSuppressSuccessDialog); } return isValid; } /** * Validates the input xml, each of the stylesheets. * @return */ private boolean validateAll() { boolean isValid; int loop, size; String autosavePath; XSLRow xslRow; JTextField textField; File file; isValid = true; if (autosaveCb.isSelected()) { autosavePath = autosavePathTf.getText(); if (StringUtils.isNotBlank(autosavePath)) { file = new File(autosavePathTf.getText()); if ((file.getParentFile() == null) || (!(isValid = file.getParentFile().exists()))) { isValid = false; Utils.showDialog(this, MessageFormat.format( stringFactory.getString(LabelStringFactory. MAIN_FRAME_AUTOSAVE_PATH_DOES_NOT_EXIST), file.getAbsolutePath()), stringFactory.getString( LabelStringFactory. MAIN_FRAME_INVALID_AUTOSAVE_PATH), JOptionPane.ERROR_MESSAGE); } } else { isValid = false; Utils.showDialog(this, stringFactory.getString( LabelStringFactory. MAIN_FRAME_PLEASE_SPECIFY_AUTOSAVE_PATH), stringFactory.getString(LabelStringFactory. MAIN_FRAME_INVALID_AUTOSAVE_PATH) , JOptionPane.ERROR_MESSAGE); } } if (isValid) { if (isValid = validateXml(stringFactory.getString( LabelStringFactory.MAIN_FRAME_XML_FILE), sourceXmlTf, true)) { size = xslRows.size(); for (loop = 0; (loop < size) && isValid; loop++) { xslRow = xslRows.get(loop); textField = xslRow.getTextField(); if (xslRow.isOnAndNotEmpty()) { isValid = validateXml(xslRow.getDescription(), textField, true); } } } } return isValid; } /** * Returns true if any XSL input textfields are turned on and have a file * specified. * @return */ private boolean areAnyStylesheets() { boolean areAnyStylesheets; XSLRow xslRow; int loop, size; areAnyStylesheets = false; size = xslRows.size(); for (loop = 0; loop < size; loop++) { xslRow = xslRows.get(loop); if (xslRow.isOnAndNotEmpty()) { areAnyStylesheets = true; break; } } return areAnyStylesheets; } /** * Refreshes the XSL-panel * */ private void refreshXSLPanel() { rebuildXSLPanel(); xslPanel.repaint(); xslPanel.revalidate(); } /** * Resets the form * */ private void resetForm() { XSLRow.removeAll(xslRows); addXSLRow(); addXSLRow(); addXSLRow(); refreshXSLPanel(); sourceXmlTf.setText(""); xmlIdentityTransformOutputProps.clear(); setAreOutputPropertiesSet(false); autosaveCb.setSelected(false); autosavePathTf.setText(""); autosavePathTf.setEnabled(false); browseAutosavePathBtn.setEnabled(false); checkSaxError.setSelected(false); checkSaxWarning.setSelected(false); checkSaxFatalError.setSelected(false); removeCheckedBtn.setEnabled(false); suppressOutputWindowCb.setSelected(false); outputAsTextIfXml.setSelected(false); outputAsTextIfXml.setEnabled(true); outputAsTextIfXmlLabel.setEnabled(true); } /** * Method to handle button clicks. * @param evt */ public void actionPerformed(ActionEvent evt) { String actionCommand, action, allConfigurations[]; Object eventSource; XSLRow xslRow; eventSource = evt.getSource(); setCursor(new Cursor(Cursor.WAIT_CURSOR)); try { if (eventSource == transformBtn) { if (areAnyStylesheets()) { doTransform(); } else { Utils.showDialog(this, stringFactory.getString(LabelStringFactory. MAIN_FRAME_SPECIFICY_AT_LEAST_ONE_STYLESHEET), stringFactory.getString(LabelStringFactory. MAIN_FRAME_TRANSFORM_MESSAGE), JOptionPane.ERROR_MESSAGE); } } else if (eventSource == about) { about(); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == exit) { destroy(); } else if (eventSource == transformTimings) { new TimingsFrame(this, Utils.toArray(xslRows)); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == validateAutosaveBtn) { doValidateXml(stringFactory.getString( LabelStringFactory.MAIN_FRAME_XML_FILE), autosavePathTf, false); } else if (eventSource == exitBtn) { destroy(); } else if (eventSource == resetForm) { resetForm(); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == browseAutosavePathBtn) { populateTFFromFileDialog(autosavePathTf); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == browseXmlBtn) { populateTFFromFileDialog(sourceXmlTf); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == autosaveCb) { autosavePathTf.setEnabled(autosaveCb.isSelected()); browseAutosavePathBtn.setEnabled(autosaveCb.isSelected()); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == suppressOutputWindowCb) { outputAsTextIfXmlLabel.setEnabled( !suppressOutputWindowCb.isSelected()); outputAsTextIfXml.setEnabled( !suppressOutputWindowCb.isSelected()); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == removeCheckedBtn) { transformTimings.setEnabled(false); XSLRow.removeChecked(xslRows); if (xslRows.size() == 0) { addXSLRow(); refreshXSLPanel(); } enableRemoveCheckedBtn(); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == addXslBtn) { transformTimings.setEnabled(false); addXSLRow(); refreshXSLPanel(); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == saveConfiguration) { persistUserPrefs(); userPrefs.persistUserPrefs(); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == saveAsConfiguration) { new SaveAsConfigurationFrame(this, userPrefs.getConfiguration()); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (eventSource == loadConfiguration) { allConfigurations = userPrefs.getAllConfigurations(); if (allConfigurations.length > 0) { new LoadConfigurationFrame(this, userPrefs.getConfiguration(), allConfigurations); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); Utils.showDialog(this, MessageFormat.format( stringFactory.getString(LabelStringFactory. MAIN_FRAME_ONLY_CONFIGURATION), userPrefs.getConfiguration(), saveAsConfiguration.getText()), stringFactory.getString(LabelStringFactory. MAIN_FRAME_MESSAGE), JOptionPane.INFORMATION_MESSAGE); } } else if (eventSource == xmlAction) { if (xmlAction.getItemCount() > 0) { action = (String)xmlAction.getSelectedItem(); xmlAction.setSelectedIndex(0); if (action.equals(XML_ACTIONS[XML_VALIDATE_ACTION_INDEX])) { components.clear(); components.add(sourceXmlTf); components.add(xmlAction); components.add(browseXmlBtn); doValidateXml(stringFactory.getString( LabelStringFactory.MAIN_FRAME_XML_FILE), sourceXmlTf, false); } else if (action.equals( XML_ACTIONS[XML_VIEW_EDIT_OUTPUT_PROPS_INDEX])) { new TransformOutputPropertiesFrame(this, xmlIdentityTransformOutputProps, sourceXmlTf.getText()); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (action.equals( XML_ACTIONS[XML_CLEAR_OUTPUT_PROPS_INDEX])) { xmlIdentityTransformOutputProps.clear(); setAreOutputPropertiesSet(false); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } else if (action.equals( XML_ACTIONS[XML_DO_IDENTITY_TRANSFORM_ACTION_INDEX])) { if (validateXml(stringFactory.getString( LabelStringFactory.MAIN_FRAME_XML_FILE), sourceXmlTf, true)) { components.clear(); components.add(sourceXmlTf); components.add(browseXmlBtn); components.add(xmlAction); doIdentityTransform( stringFactory.getString( LabelStringFactory. MAIN_FRAME_SELECT_FILE_FOR_IT_RESULT), sourceXmlTf.getText(), sourceXmlTf.getText()); } else { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } else { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } } else { actionCommand = evt.getActionCommand(); if (AppConstants.INSERT.equals(actionCommand)) { xslRow = XSLRow.getRowByInsertBtn(xslRows, (JButton)eventSource); insertXSLRow(xslRow.getIndex()); refreshXSLPanel(); } else if (AppConstants.REMOVE_CB.equals(actionCommand)) { enableRemoveCheckedBtn(); } else if (stringFactory.getString( LabelStringFactory.MAIN_FRAME_BROWSE_BTN).equals( actionCommand)) { xslRow = XSLRow.getRowByBrowseBtn(xslRows, (JButton)eventSource); populateTFFromFileDialog(xslRow.getTextField()); } else if (AppConstants.TAKE_ACTION.equals(actionCommand)) { xslRow = XSLRow.getRowByAction(xslRows, (JComboBox)eventSource); if (xslRow.getAction().getItemCount() > 0) { action = (String)xslRow.getAction().getSelectedItem(); xslRow.setSelectedActionIndex(0); if (action.equals( XSLRow.ACTIONS[XSLRow.VALIDATE_INDEX])) { components.clear(); components.add(xslRow.getTextField()); components.add(xslRow.getAction()); components.add(xslRow.getRemoveCb()); components.add(xslRow.getInsertBtn()); components.add(xslRow.getBrowseBtn()); doValidateXml(stringFactory.getString( LabelStringFactory.MAIN_FRAME_XSL_PREFIX) + (xslRow.getIndex() + 1), xslRow.getTextField(), false); } else if ( action.startsWith(XSLRow.ON_OFF_ITEM_PREFIX)) { xslRow.toggleOnOffBtn(); } else if (action.equals( XSLRow.ACTIONS[XSLRow.VIEW_EDIT_OUTPUT_PROPS_INDEX])) { new TransformOutputPropertiesFrame(this, xslRow); } else if (action.equals( XSLRow.ACTIONS[XSLRow.CLEAR_OUTPUT_PROPS_INDEX])) { xslRow.setAreOutputPropertiesSet(false); xslRow.clearOutputProperties(); } else if (action.equals( XSLRow.ACTIONS[XSLRow. CLEAR_ALL_PARAMETERS_INDEX])) { xslRow.clearAllParameters(); } else if (action.equals(XSLRow.ACTIONS[XSLRow. VIEW_EDIT_PARAMETERS_INDEX])) { new TransformParametersFrame(this, xslRow); } else if (action.equals(XSLRow.ACTIONS[XSLRow. PERFORM_IDENTITY_TRANSFORM_INDEX])) { if (validateXml(stringFactory.getString( LabelStringFactory.MAIN_FRAME_XSL_PREFIX) + (xslRow.getIndex()+1), xslRow.getTextField(), true)) { components.clear(); components.add(xslRow.getBrowseBtn()); components.add(xslRow.getRemoveCb()); components.add(xslRow.getInsertBtn()); components.add(xslRow.getTextField()); doIdentityTransform( stringFactory.getString( LabelStringFactory. MAIN_FRAME_PICK_FILE_FOR_IT), xslRow.getTextField().getText(), xslRow.getTextField().getText()); } else { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } } } setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } catch (Throwable aAny) { // log and show dialog... logger.error(ExceptionUtils.getFullStackTrace(aAny)); Utils.showErrorDialog(this, aAny); } } /** * Refreshes the configuration label * */ public void refreshConfigurationLabel() { currentConfigLabel.setText(userPrefs.getConfiguration()); } /** * Refreshes the entire application window * */ public void refreshApplication() { refreshStylesheets(); refreshConfigurationLabel(); initializeControls(); } /** * Helper method that populates aTextField by presenting a file-open dialog * to the user. * @param aTextField */ public void populateTFFromFileDialog(JTextField aTextField) throws IOException { int returnVal; File file; Utils.getInstance().getFileChooser().setDialogType( JFileChooser.OPEN_DIALOG); returnVal = Utils.getInstance().getFileChooser().showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { file = Utils.getInstance().getFileChooser().getSelectedFile(); setLastFileChosen(file.getAbsolutePath()); aTextField.setText(file.getAbsolutePath()); } } /** * Inserts a new XSL row * @param aIndex */ private void insertXSLRow(int aIndex) { int size, loop; xslRows.add(aIndex, new XSLRow(this, xslPanel, new JButton(AppConstants.INSERT), // label text is updated by subsequent XSLRow.setIndex() call... new JLabel(""), new JTextField(AppConstants.TF_LENGTH), new JCheckBox(), new JButton(stringFactory.getString( LabelStringFactory.MAIN_FRAME_BROWSE_BTN)), new JComboBox(), new JLabel(), -1)); size = xslRows.size(); for (loop = 0; loop < size; loop++) { ((XSLRow)(xslRows.get(loop))).setIndex(loop); } } /** * Appends a new XSL row * */ private void addXSLRow() { int size; size = xslRows.size(); xslRows.add(new XSLRow(this, xslPanel, new JButton(AppConstants.INSERT), new JLabel(MessageFormat.format(stringFactory.getString( LabelStringFactory.XSLROW_XSL_LABEL), xslRows.size()+1)), new JTextField(AppConstants.TF_LENGTH), new JCheckBox(), new JButton(stringFactory.getString( LabelStringFactory.MAIN_FRAME_BROWSE_BTN)), new JComboBox(), new JLabel(), size)); } /** * Enables or disables the "remove checked" button. If any of the xsl * rows are checked, the button will be enabled. * */ private void enableRemoveCheckedBtn() { boolean enable; int size, loop; enable = false; size = xslRows.size(); for (loop = 0; loop < size; loop++) { if (((XSLRow)(xslRows.get(loop))).getRemoveCb().isSelected()) { enable = true; break; } } removeCheckedBtn.setEnabled(enable); } /** * Method to validate the source xml. */ private boolean validateXml(String aLabel, String sourceXmlFile, boolean checkWarnings, boolean checkErrors, boolean checkFatalErrors, JFrame parent, boolean aSuppressSuccessDialog) { boolean isValid; FileContent content; isValid = false; try { content = fsManager.resolveFile(sourceXmlFile).getContent(); Utils.getInstance().isValidXml(content, checkWarnings, checkErrors, checkFatalErrors); isValid = true; if (!aSuppressSuccessDialog) { Utils.showDialog(parent, MessageFormat.format( stringFactory.getString(LabelStringFactory. MAIN_FRAME_VALID_XML_MSG), sourceXmlFile), stringFactory.getString(LabelStringFactory. MAIN_FRAME_VALID_XML_MSG_HDR_YES), JOptionPane.INFORMATION_MESSAGE); } } catch (UnknownHostException aException) { logger.error(aException); Utils.handleXMLError(stringFactory.getString(LabelStringFactory. MAIN_FRAME_VALID_XML_MSG_HDR_NO), aLabel, stringFactory.getString(LabelStringFactory. MAIN_FRAME_XML_VALIDATION_ERR), sourceXmlFile, this, aException.getMessage()); } catch (SocketException aException) { logger.error(aException); Utils.handleXMLError(stringFactory.getString(LabelStringFactory. MAIN_FRAME_VALID_XML_MSG_HDR_NO), aLabel, stringFactory.getString(LabelStringFactory. MAIN_FRAME_XML_VALIDATION_ERR), sourceXmlFile, this, aException.getMessage()); } catch (Throwable aAny) { Utils.handleXMLError(stringFactory.getString(LabelStringFactory. MAIN_FRAME_VALID_XML_MSG_HDR_NO), aLabel, stringFactory.getString(LabelStringFactory. MAIN_FRAME_XML_VALIDATION_ERR), sourceXmlFile, this, aAny); } return isValid; } /** * Returns true if a stylesheet between the indexes of aStartIndex * and the end of the list are enabled and have a file specified. * @param aStartIndex * @param aSizeOfList * @return */ private boolean isNextStylesheet(int aStartIndex, int aSizeOfList) { boolean isNextStylesheet; int loop; isNextStylesheet = false; for (loop = aStartIndex; loop < aSizeOfList; loop++) { if (((XSLRow)(xslRows.get(loop))).isOnAndNotEmpty()) { isNextStylesheet = true; break; } } return isNextStylesheet; } /** * Initiates the xml-validation in a separate thread. * @param aLabel * @param aTextField * @param aSuppressSuccessDialog */ private void doValidateXml(String aLabel, JTextField aTextField, boolean aSuppressSuccessDialog) { label = aLabel; textField = aTextField; suppressSuccessDialog = aSuppressSuccessDialog; threadMode = THREADMODE_DO_VALIDATE; Utils.setEnabled(components, false); new Thread(this).start(); } /** * Entry point of threads. */ public void run() { String sresultsFile; File xmlFile, resultsFile; byte results[]; try { switch (threadMode) { case THREADMODE_DO_TRANSFORM: executeTransform(); break; case THREADMODE_DO_VALIDATE: validateXml(label, textField, suppressSuccessDialog); break; case THREADMODE_DO_XML_IDENTITY_TRANSFORM: xmlFile = new File(identityTransformSourceXmlFile); sresultsFile = (String)JOptionPane.showInputDialog(this, identityTransformMessage, stringFactory.getString( LabelStringFactory. MAIN_FRAME_IDENTITY_TRANSFORM), JOptionPane.QUESTION_MESSAGE, null, null, identityTransformResultXmlFile); if (sresultsFile != null) { resultsFile = new File(sresultsFile); resultsFile.getParentFile().mkdirs(); results = XMLUtils.transform(xmlFile, xmlIdentityTransformOutputProps); IOUtils.writeFile(resultsFile, results); } break; } } catch (Throwable aAny) { logger.error(ExceptionUtils.getFullStackTrace(aAny)); Utils.showErrorDialog(this, aAny); } finally { Utils.setEnabled(components, true); setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } /** * Initiates the transform operation in a seperate thread. * */ private void doTransform() { components.clear(); components.add(transformBtn); threadMode = THREADMODE_DO_TRANSFORM; Utils.setEnabled(components, false); new Thread(this).start(); } /** * Initiates the identity-transform operation in a separate thread. * @param aMessage * @param aIdentityTransformSourceXmlFile * @param aIdentityTransformResultXmlFile */ private void doIdentityTransform(String aMessage, String aIdentityTransformSourceXmlFile, String aIdentityTransformResultXmlFile) { Utils.setEnabled(components, false); threadMode = THREADMODE_DO_XML_IDENTITY_TRANSFORM; identityTransformMessage = aMessage; identityTransformSourceXmlFile = aIdentityTransformSourceXmlFile; identityTransformResultXmlFile = aIdentityTransformResultXmlFile; new Thread(this).start(); } /** * Performs transforms. * @throws Exception */ private void executeTransform() throws Exception { int loop; XSLRow lrows[]; if (validateAll()) { lrows = Utils.toArray(xslRows); for (loop = 0; loop < lrows.length; loop++) { lrows[loop].setTimeToTransform(0); } transform(Utils.getXMLContents(fsManager, sourceXmlTf.getText())); } } /** * Method to do xslt transform. */ private void transform(byte aXmlContents[]) throws TransformerException, IOException, ParserConfigurationException, SAXException { int loop, size; long transformTime; byte tmp[]; XSLRow xslRow; byte transformResult[]; boolean success; TransformOutputProperties transformOutputProps; TransformParameters transformParameters; xslRow = null; transformOutputProps = null; transformParameters = null; size = xslRows.size(); transformResult = aXmlContents; success = true; lastTotalTransformTime = 0; try { for (loop = 0; loop < size; loop++) { xslRow = (XSLRow)xslRows.get(loop); transformOutputProps = xslRow.getTransformOutputProperties(); transformParameters = xslRow.getTransformParameters(); if (xslRow.isOnAndNotEmpty()) { transformResult = XMLUtils.transform(tmp = transformResult, Utils.getXSLSource(fsManager, xslRow.getTextField().getText()), transformOutputProps, transformParameters); transformTime = XMLUtils.getTransformTime(tmp, Utils.getXSLSource(fsManager, xslRow.getTextField().getText()), transformOutputProps, transformParameters); xslRow.setTimeToTransform(transformTime); lastTotalTransformTime += transformTime; if (!XMLUtils.isXml(transformResult)) { if (isNextStylesheet(loop + 1, size)) { success = false; Utils.showDialog(this, MessageFormat.format( stringFactory.getString( LabelStringFactory. MAIN_FRAME_TRANSFORM_RESULT_NOT_XML), (loop + 1)), stringFactory.getString( LabelStringFactory. MAIN_FRAME_TRANSFORM_ERR_MSG), JOptionPane.INFORMATION_MESSAGE); break; } } } } } catch (TransformerException aTransformerException) { success = false; Utils.handleXMLError(stringFactory.getString( LabelStringFactory.MAIN_FRAME_ERR_IN_XSL), xslRow.getDescription(), stringFactory.getString( LabelStringFactory.MAIN_FRAME_XSL_TRANSFORMATION_ERR), xslRow.getTextField().getText(), this, aTransformerException); } if (success) { transformTimeLabel.setText(lastTotalTransformTime + " " + stringFactory.getString( LabelStringFactory. MAIN_FRAME_MILLISECONDS_ABBREVIATION)); logger.info("total transform time: " + lastTotalTransformTime + " " + stringFactory.getString(LabelStringFactory. MAIN_FRAME_MILLISECONDS_ABBREVIATION)); transformTimings.setEnabled(true); if (autosaveCb.isSelected()) { IOUtils.writeFile(new File(autosavePathTf.getText()), transformResult); } if (!suppressOutputWindowCb.isSelected()) { if (XMLUtils.isXml(transformResult)) { if (outputAsTextIfXml.isSelected()) { new OutputFrame(this, stringFactory.getString( LabelStringFactory. MAIN_FRAME_TRANSFORM_RESULTS), transformResult, Utils.toArray(xslRows)); } else { new OutputFrame(this, stringFactory.getString( LabelStringFactory. MAIN_FRAME_TRANSFORM_RESULTS), XMLUtils.getDocument(transformResult), transformOutputProps, Utils.toArray(xslRows), true); } } else { new OutputFrame(this, stringFactory.getString( LabelStringFactory.MAIN_FRAME_TRANSFORM_RESULTS), transformResult, Utils.toArray(xslRows)); } } } } /** * Writes transform output property values to the user preferences * object. * @param aOutputProperties * @param aPropertyNamePrefix */ private void persistOutputProperties( TransformOutputProperties aOutputProperties, String aPropertyNamePrefix) { String val; if (StringUtils.isNotBlank(val = aOutputProperties.getCDATA_SECTION_ELEMENTS())) { userPrefs.setProperty(aPropertyNamePrefix + AppConstants.CDATA_SECTION_ELEMENTS, val); } if (StringUtils.isNotBlank(val = aOutputProperties.getDOCTYPE_PUBLIC())) { userPrefs.setProperty(aPropertyNamePrefix + AppConstants.DOCTYPE_PUBLIC, val); } if (StringUtils.isNotBlank(val = aOutputProperties.getDOCTYPE_SYSTEM())) { userPrefs.setProperty(aPropertyNamePrefix + AppConstants.DOCTYPE_SYSTEM, val); } if (StringUtils.isNotBlank(val = aOutputProperties.getENCODING())) { userPrefs.setProperty(aPropertyNamePrefix + AppConstants.ENCODING, val); } if (StringUtils.isNotBlank(val = aOutputProperties.getINDENT())) { userPrefs.setProperty(aPropertyNamePrefix + AppConstants.INDENT, val); } if (StringUtils.isNotBlank(val = aOutputProperties.getMEDIA_TYPE())) { userPrefs.setProperty(aPropertyNamePrefix + AppConstants.MEDIA_TYPE, val); } if (StringUtils.isNotBlank(val = aOutputProperties.getMETHOD())) { userPrefs.setProperty(aPropertyNamePrefix + AppConstants.METHOD, val); } if (StringUtils.isNotBlank(val = aOutputProperties.getOMIT_XML_DECLARATION())) { userPrefs.setProperty(aPropertyNamePrefix + AppConstants.OMIT_XML_DECLARATION, val); } if (StringUtils.isNotBlank(val = aOutputProperties.getSTANDALONE())) { userPrefs.setProperty(aPropertyNamePrefix + AppConstants.STANDALONE, val); } if (StringUtils.isNotBlank(val = aOutputProperties.getVERSION())) { userPrefs.setProperty(aPropertyNamePrefix + AppConstants.VERSION, val); } } /** * Persists the user preferences object to the preferences file. * */ private void persistUserPrefs() { int loop, size, innerLoop; String paramNames[]; XSLRow xslRow; String propertyName; TransformParameters parameters; userPrefs.clearDynamicPrefs(); userPrefs.setProperty(AppConstants.CHK_WARNINGS_PROP, "" + checkSaxWarning.isSelected()); userPrefs.setProperty(AppConstants.CHK_ERRORS_PROP, "" + checkSaxError.isSelected()); userPrefs.setProperty(AppConstants.CHK_FATAL_ERRORS_PROP, "" + checkSaxFatalError.isSelected()); userPrefs.setProperty(AppConstants.X_COORD_PROP, Integer.toString(this.getX())); userPrefs.setProperty(AppConstants.Y_COORD_PROP, Integer.toString(this.getY())); userPrefs.setProperty(AppConstants.LAST_XML_FILE_PROP, sourceXmlTf.getText()); userPrefs.setProperty(AppConstants.SUPPRESS_OUTPUT_WINDOW_PROP, "" + suppressOutputWindowCb.isSelected()); userPrefs.setProperty(AppConstants.OUTPUT_AS_TEXT_IF_XML_PROP, "" + outputAsTextIfXml.isSelected()); userPrefs.setProperty(AppConstants.AUTOSAVE_RESULT_PROP, "" + autosaveCb.isSelected()); userPrefs.setProperty(AppConstants.AUTOSAVE_FILE_PROP, autosavePathTf.getText()); persistOutputProperties(xmlIdentityTransformOutputProps, "xml_identity_transform_outputproperties_"); userPrefs.setProperty("xml_identity_transform_opInd", "" + areXmlOutputPropertiesSet); size = xslRows.size(); for (loop = 0; loop < size; loop++) { xslRow = (XSLRow)xslRows.get(loop); // text field value propertyName = "xsl_" + loop + "_file"; userPrefs.setProperty(propertyName, xslRow.getTextField().getText()); // on/off propertyName = "xsl_" + loop + "_onoff"; userPrefs.setProperty(propertyName, "" + xslRow.isOn()); // output properties indicator propertyName = "xsl_" + loop + "_opInd"; userPrefs.setProperty(propertyName, "" + xslRow.areOutputPropertiesSet()); persistOutputProperties(xslRow.getTransformOutputProperties(), "xsl_" + loop + "_outputproperties_"); parameters = xslRow.getTransformParameters(); paramNames = parameters.getParameterNames(); for (innerLoop = 0; innerLoop < paramNames.length; innerLoop++) { userPrefs.setProperty("xsl_" + loop + "_params_" + innerLoop + "_" + paramNames[innerLoop], (String)parameters.getParameter(paramNames[innerLoop])); } } userPrefs.setProperty(AppConstants.NUM_STYLESHEETS_PROP, Integer.toString(size)); userPrefs.setProperty(AppConstants.FRAME_HEIGHT_PROP, Integer.toString(getHeight())); userPrefs.setProperty(AppConstants.FRAME_WIDTH_PROP, Integer.toString(getWidth())); if (StringUtils.isNotBlank(lastFileChosen)) { userPrefs.setProperty(AppConstants.LAST_FILE_CHOSEN_PROP, lastFileChosen); } } /** * Method to shutdown the app. */ private void destroy() { try { persistUserPrefs(); userPrefs.persistUserPrefs(); } catch (IOException aException) { logger.error(ExceptionUtils.getFullStackTrace(aException)); Utils.showErrorDialog(this, aException); } finally { dispose(); System.exit(0); } } /** * class main() method - application entry point * @param aArgs */ public static void main(String aArgs[]) throws Exception { JFrame.setDefaultLookAndFeelDecorated(true); new BasicXSLTFrame(); } }