hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
94b9ca6298e8f7ebeb7e71854d3cecb752bbc16f
508
package com.thinkgem.jeesite.modules.report.dao; import java.util.List; import com.thinkgem.jeesite.common.persistence.CrudDao; import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao; import com.thinkgem.jeesite.modules.report.entity.MsgList; /** * 下游发送明细DAO接口 * @author apple * @version 2019-05-17 */ @MyBatisDao public interface MsgListDao extends CrudDao<MsgList> { public List<MsgList> getBySeqIdAndType(MsgList msgList); public List<MsgList> getByMsgIdAndType(MsgList msgList); }
26.736842
69
0.801181
23810ff8a2f2ceea2d09e0050676ce08913dd425
1,132
package com.rocketchat.core.model; import com.rocketchat.common.data.model.User; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Created by sachin on 27/7/17. */ public class RoomRole { private String id; private String roomId; private User user; private ArrayList<String> roles; public RoomRole(JSONObject object) { try { id = object.getString("_id"); roomId = object.getString("rid"); // TODO user = new UserObject(object.getJSONObject("u")); roles = new ArrayList<>(); JSONArray array = object.optJSONArray("roles"); for (int i = 0; i < array.length(); i++) { roles.add(array.getString(i)); } } catch (JSONException e) { e.printStackTrace(); } } public String getId() { return id; } public String getRoomId() { return roomId; } public User getUser() { return user; } public ArrayList<String> getRoles() { return roles; } }
22.64
69
0.577739
0946424c543fb79bf6e7ca7082a7b7e3d71d7f31
2,117
package org.springframework.boot.web.servlet.context; import javax.servlet.Servlet; import org.junit.Test; import org.springframework.boot.web.servlet.server.MockServletWebServerFactory; import org.springframework.core.io.ClassPathResource; import static org.mockito.Mockito.verify; /** * Tests for {@link XmlServletWebServerApplicationContext}. * * @author Phillip Webb */ public class XmlServletWebServerApplicationContextTests { private static final String PATH = XmlServletWebServerApplicationContextTests.class .getPackage().getName().replace('.', '/') + "/"; private static final String FILE = "exampleEmbeddedWebApplicationConfiguration.xml"; private XmlServletWebServerApplicationContext context; @Test public void createFromResource() { this.context = new XmlServletWebServerApplicationContext( new ClassPathResource(FILE, getClass())); verifyContext(); } @Test public void createFromResourceLocation() { this.context = new XmlServletWebServerApplicationContext(PATH + FILE); verifyContext(); } @Test public void createFromRelativeResourceLocation() { this.context = new XmlServletWebServerApplicationContext(getClass(), FILE); verifyContext(); } @Test public void loadAndRefreshFromResource() { this.context = new XmlServletWebServerApplicationContext(); this.context.load(new ClassPathResource(FILE, getClass())); this.context.refresh(); verifyContext(); } @Test public void loadAndRefreshFromResourceLocation() { this.context = new XmlServletWebServerApplicationContext(); this.context.load(PATH + FILE); this.context.refresh(); verifyContext(); } @Test public void loadAndRefreshFromRelativeResourceLocation() { this.context = new XmlServletWebServerApplicationContext(); this.context.load(getClass(), FILE); this.context.refresh(); verifyContext(); } private void verifyContext() { MockServletWebServerFactory factory = this.context .getBean(MockServletWebServerFactory.class); Servlet servlet = this.context.getBean(Servlet.class); verify(factory.getServletContext()).addServlet("servlet", servlet); } }
26.797468
85
0.775154
d4ed7269e92c75cd7ff2696dae9e948402df8e0e
2,149
package uk.gov.di.ipv.atp.dcs.services; import com.nimbusds.jose.*; import com.nimbusds.jose.crypto.RSADecrypter; import com.nimbusds.jose.crypto.RSAEncrypter; import reactor.core.publisher.Mono; import java.security.Key; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.interfaces.RSAPublicKey; import java.text.ParseException; public abstract class AbstractEncryptionService implements EncryptionService { private final Key clientEncryptionKey; private final Certificate serverEncryptionCert; public AbstractEncryptionService( Key clientEncryptionKey, Certificate serverEncryptionCert ) { this.clientEncryptionKey = clientEncryptionKey; this.serverEncryptionCert = serverEncryptionCert; } @Override public Mono<String> encrypt(String data) { try { var header = new JWEHeader .Builder(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A128CBC_HS256) .type(new JOSEObjectType("JWE")) .build(); var jwe = new JWEObject(header, new Payload(data)); var encrypter = new RSAEncrypter((RSAPublicKey) serverEncryptionCert.getPublicKey()); jwe.encrypt(encrypter); if (!jwe.getState().equals(JWEObject.State.ENCRYPTED)) { throw new RuntimeException("Something went wrong, couldn't encrypt JWE"); } return Mono.just(jwe.serialize()); } catch (JOSEException e) { return Mono.error(e); } } @Override public Mono<String> decrypt(String data) { try { var jwe = JWEObject.parse(data); var decrypter = new RSADecrypter((PrivateKey) clientEncryptionKey); jwe.decrypt(decrypter); if (!jwe.getState().equals(JWEObject.State.DECRYPTED)) { throw new RuntimeException("Something went wrong, couldn't decrypt JWE"); } return Mono.just(jwe.getPayload().toString()); } catch (ParseException | JOSEException e) { return Mono.error(e); } } }
32.560606
97
0.651466
0c944d514ae114eff542d5598766162b12d4a086
5,669
/* * The MIT License * * Copyright 2013 Cameron Garnham. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.multibit.controller; import java.util.ArrayList; import java.util.Collection; import java.util.Locale; import java.util.concurrent.CopyOnWriteArrayList; import org.multibit.ApplicationDataDirectoryLocator; import org.multibit.Localiser; import org.multibit.model.core.StatusEnum; import org.multibit.viewsystem.DisplayHint; import org.multibit.viewsystem.View; import org.multibit.viewsystem.ViewSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Cameron Garnham */ public abstract class BaseController<C extends BaseController<C>> implements Controller{ private Logger log = LoggerFactory.getLogger(BaseController.class); /** * The view systems under control of the MultiBitController. */ private final Collection<ViewSystem> viewSystems; /** * The localiser used to localise everything. */ private Localiser localiser; /** * Class encapsulating the location of the Application Data Directory. */ private final ApplicationDataDirectoryLocator applicationDataDirectoryLocator; private volatile boolean applicationStarting = true; protected BaseController(){ this(null); } protected BaseController(ApplicationDataDirectoryLocator applicationDataDirectoryLocator){ this.applicationDataDirectoryLocator = applicationDataDirectoryLocator; viewSystems = new CopyOnWriteArrayList<ViewSystem>(); // By default localise to English. localiser = new Localiser(Locale.ENGLISH); } @Override public final Collection<ViewSystem> getViewSystem() { return viewSystems; } /** * Register a new MultiBitViewSystem from the list of views that are managed. * * @param viewSystem * system */ public final void registerViewSystem(ViewSystem viewSystem) { viewSystems.add(viewSystem); } @Override public final Localiser getLocaliser() { return localiser; } public final void setLocaliser(Localiser localiser) { this.localiser = localiser; } @Override public final void setOnlineStatus(StatusEnum statusEnum) { //log.debug("setOnlineStatus called"); for (ViewSystem viewSystem : this.getViewSystem()) { viewSystem.setOnlineStatus(statusEnum); } } @Override public final boolean getApplicationStarting(){ return this.applicationStarting; } @Override public final ApplicationDataDirectoryLocator getApplicationDataDirectoryLocator(){ return applicationDataDirectoryLocator; } public final void setApplicationStarting(boolean applicationStarting){ this.applicationStarting = applicationStarting; } /** * Fire that the model data has changed. */ @Override public final void fireDataChangedUpdateNow() { //log.debug("fireDataChangedUpdateNow called"); for (ViewSystem viewSystem : this.getViewSystem()) { viewSystem.fireDataChangedUpdateNow(DisplayHint.COMPLETE_REDRAW); } } /** * Fire that the model data has changed and similar events are to be collapsed. */ @Override public final void fireDataChangedUpdateLater() { for (ViewSystem viewSystem : this.getViewSystem()) { viewSystem.fireDataChangedUpdateLater(DisplayHint.WALLET_TRANSACTIONS_HAVE_CHANGED); } } /** * Fire that all the views need recreating. */ @Override public final void fireRecreateAllViews(boolean initUI) { //log.debug("fireRecreateAllViews called"); // tell the viewSystems to refresh their views for (ViewSystem viewSystem : this.getViewSystem()) { viewSystem.recreateAllViews(initUI, getCurrentView()); } } @Override abstract public void fireDataStructureChanged(); /** * @return True if the application can quit */ protected final boolean isOKToQuit() { return true; } @Override abstract public View getCurrentView(); @Override abstract public void setCurrentView(View view); @Override abstract public void displayView(View viewToDisplay); @Override abstract public void displayHelpContext(String helpContextToDisplay); abstract protected void addEventHandler(AbstractEventHandler eventHandler); }
30.643243
96
0.696419
e0461f2db44e000c666c2dfada9cd1961469bbb5
503
package com.mb.fhl.net; /** * Created by Administrator on 2016/10/11 0011. * api 异常码 */ public class ApiErrorCode { /** 客户端错误*/ public static int ERROR_CLIENT_AUTHORIZED = 1; /** 用户授权失败*/ public static int ERROR_USER_AUTHORIZED = 2; /** 请求参数错误*/ public static int ERROR_REQUEST_PARAM = 3; /** 参数检验不通过 */ public static int ERROR_PARAM_CHECK = 4; /** 自定义错误*/ public static int ERROR_OTHER = 10; /** 无网络连接*/ public static int ERROR_NO_INTERNET = 11; }
21.869565
50
0.642147
3253cc6287d8fbbdd97543dc3a7369e7b13c46d9
4,637
package com.artemzin.android.bytes.ui; import android.content.Context; import android.content.res.Resources; /** * Contains methods to convert dp to px, px to dp, sp to px and so on * Awesome! * * @see <a href="http://stackoverflow.com/questions/4605527/converting-pixels-to-dp">Converting pixels to dp on stackoverflow.com</a> * @author Artem Zinnatullin [[email protected]] */ public class DisplayUnitsConverter { private DisplayUnitsConverter() {} //region with Context /** * Converts dp unit to equivalent pixels, depending on device density. * * @param context * Context to get resources and device specific display metrics * @param dp * A value in dp (density independent pixels) unit. Which we need to convert into pixels * @return A float value to represent px equivalent to dp depending on device density */ public static float dpToPx(Context context, final float dp) { return dp * (context.getResources().getDisplayMetrics().densityDpi / 160f); } /** * Converts device specific pixels to density independent pixels. * * @param context * Context to get resources and device specific display metrics * @param px * A value in px (pixels) unit. Which we need to convert into db * @return A float value to represent dp equivalent to px value */ public static float pxToDp(Context context, final float px) { return px / (context.getResources().getDisplayMetrics().densityDpi / 160f); } /** * Converts sp unit to equivalent pixels, depending on device density and user scale options * * @param context * Context to get resources and device and user specific display metrics * @param sp * A value in sp to convert to px * @return A float value to represent px equivalent to sp depending on device density and user's text scale options */ public static float spToPx(Context context, final float sp) { return sp * (context.getResources().getDisplayMetrics().scaledDensity); } /** * Converts device specific pixels to density independent pixels * user's value of text scale * * @param context * Context to get resources and device and user specific display metrics * @param px * A value in px to convert to sp * @return A float value to represent sp equivalent to px depending on device density and user's text scale options */ public static float pxToSp(Context context, final float px) { return px / (context.getResources().getDisplayMetrics().scaledDensity); } //endregion //region without Context /** * Converts dp unit to equivalent pixels, depending on device density. * Works without Context object * * @param dp * A value in dp (density independent pixels) unit. Which we need to convert into pixels * @return A float value to represent px equivalent to dp depending on device density */ public static float dpToPx(final float dp) { return dp * (Resources.getSystem().getDisplayMetrics().densityDpi / 160f); } /** * Converts device specific pixels to density independent pixels. * Works without Context object * * @param px * A value in px (pixels) unit. Which we need to convert into db * @return A float value to represent dp equivalent to px value */ public static float pxToDp(final float px) { return px / (Resources.getSystem().getDisplayMetrics().densityDpi / 160f); } /** * Converts sp unit to equivalent pixels, depending on device density and user scale options * Works without Context object * * @param sp * A value in sp to convert to px * @return A float value to represent px equivalent to sp depending on device density and user's text scale options */ public static float spToPx(final float sp) { return sp * (Resources.getSystem().getDisplayMetrics().scaledDensity); } /** * Converts device specific pixels to density independent pixels * user's value of text scale * Works without Context object * * @param px * A value in px to convert to sp * @return A float value to represent sp equivalent to px depending on device density and user's text scale options */ public static float pxToSp(final float px) { return px / (Resources.getSystem().getDisplayMetrics().scaledDensity); } //endregion }
37.096
133
0.662282
e69c0c3d06a88159539b7bf98b7c36a1a004b005
547
package cn.leetechweb.summer.mvc.support; /** * Project Name: summer * Create Time: 2020/11/18 14:28 * * @author junyu lee **/ public enum HttpStatus { /** * 响应成功 */ OK(200), /** * 资源未找到 */ NOT_FOUND(404), /** * 服务器发生内部错误 */ INTERNAL_SERVER_ERROR(500), /** * 重定向 */ REDIRECT(302); /** * 对应的响应状态码 */ private final int value; HttpStatus(int value) { this.value = value; } public int getValue() { return value; } }
12.431818
41
0.491773
41d9e14071aa9f9fcb9a4794a9ca24db75db92bf
219
package example.service; import example.repo.Customer43Repository; import org.springframework.stereotype.Service; @Service public class Customer43Service { public Customer43Service(Customer43Repository repo) { } }
18.25
54
0.826484
69666edf4cde7a9b08fee60efecab1f3aaf6f7da
1,275
/* * Copyright (c) 2010 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. */ /* * Modified by Sergio Martinez. Copyright 2011 Vodafone Group Services Ltd. * */ package com.phonegap.calendar.android.model; import com.google.api.client.util.Key; import com.google.common.collect.Lists; import java.util.List; /** * Calendar object for new calendar feed * @author Yaniv Inbar * @author Sergio Martinez Rodriguez */ public class CalendarFeed extends Feed { /** * entry tag in calendar feed */ @Key("entry") public List<CalendarEntry> calendars = Lists.newArrayList(); /* (non-Javadoc) * @see com.phonegap.calendar.android.model.Feed#getEntries() */ @Override public List<CalendarEntry> getEntries() { return calendars; } }
25.5
100
0.724706
f7479b9757f454d437d5641274c566acc7bdf932
2,254
import java.sql.*; public class projectdb { public static String project = "test127"; public static void main(String[] args) throws ClassNotFoundException { // load the sqlite-JDBC driver using the current class loader Class.forName("org.sqlite.JDBC"); Connection connection = null; try { // create a database connection connection = DriverManager.getConnection( String.format("jdbc:sqlite:%s/data/project.db", System.getProperty("user.home"))); Statement statement = connection.createStatement(); statement.setQueryTimeout(30); // set timeout to 30 sec. statement.executeUpdate(String.format("delete from projectdb where name='%s';",project)); // create a database connection connection = DriverManager.getConnection( String.format("jdbc:sqlite:%s/data/task.db", System.getProperty("user.home"))); statement = connection.createStatement(); statement.setQueryTimeout(30); // set timeout to 30 sec. statement.executeUpdate(String.format("drop table taskdb_%s;",project)); // create a database connection connection = DriverManager.getConnection( String.format("jdbc:sqlite:%s/data/result.db", System.getProperty("user.home"))); statement = connection.createStatement(); statement.setQueryTimeout(30); // set timeout to 30 sec. statement.executeUpdate(String.format("drop table resultdb_%s;",project)); System.out.println("ok"); } catch(SQLException e) { // if the error message is "out of memory", // it probably means no database file is found System.err.println(e.getMessage()); } finally { try { if(connection != null) connection.close(); } catch(SQLException e) { // connection close failed. System.err.println(e); } } } }
35.21875
101
0.550133
83cde6ae75daca4c9d69ee0a57c065b291e5ac8c
4,411
/* * Copyright 2017 Steve McDuff * * 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.ibm.profiler.mongo; import org.bson.Document; import com.mongodb.ClientSessionOptions; import com.mongodb.MongoClient; import com.mongodb.MongoClientException; import com.mongodb.MongoClientOptions; import com.mongodb.MongoNamespace; import com.mongodb.client.ClientSession; import com.mongodb.client.ListDatabasesIterable; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; /** * ProfiledMongoClient * * @author Steve McDuff */ public class ProfiledMongoClient { private final MongoClient client; public ProfiledMongoClient(MongoClient client) { super(); this.client = client; } /** * Get the original mongo client to access unprofiled APIs. * * @return The mongo client. */ public MongoClient getClient() { return client; } /** * Gets the options that this client uses to connect to server. * * <p> * Note: {@link MongoClientOptions} is immutable. * </p> * * @return the options */ public MongoClientOptions getMongoClientOptions() { return client.getMongoClientOptions(); } /** * Get a list of the database names * * @return an iterable containing all the names of all the databases */ public MongoIterable<String> listDatabaseNames() { return client.listDatabaseNames(); } /** * Gets the list of databases * * @return the list of databases */ public ListDatabasesIterable<Document> listDatabases() { return listDatabases(Document.class); } /** * Gets the list of databases * * @param clazz * the class to cast the database documents to * @param <T> * the type of the class to use instead of {@code Document}. * @return the list of databases */ public <T> ListDatabasesIterable<T> listDatabases(final Class<T> clazz) { return client.listDatabases(clazz); } /** * Get a database by name. * * @param databaseName * the name of the database to retrieve * @return a {@code MongoDatabase} representing the specified database * @throws IllegalArgumentException * if databaseName is invalid * @see MongoNamespace#checkDatabaseNameValidity(String) */ public MongoDatabase getDatabase(final String databaseName) { MongoDatabase database = client.getDatabase(databaseName); ProfiledMongoDatabase profiledDatabase = new ProfiledMongoDatabase(database); return profiledDatabase; } /** * Closes all resources associated with this instance, in particular any open network connections. Once called, this * instance and any databases obtained from it can no longer be used. */ public void close() { client.close(); } /** * Creates a client session with default session options. * * @return the client session * @throws MongoClientException if the MongoDB cluster to which this client is connected does not support sessions */ public ClientSession startSession() { return client.startSession(); } /** * Creates a client session. * * @param options the options for the client session * @return the client session * @throws MongoClientException if the MongoDB cluster to which this client is connected does not support sessions */ public ClientSession startSession(final ClientSessionOptions options) { return client.startSession(options); } }
29.019737
121
0.641805
fae46d5f9acf9211c6d8758bebf36660de8b34c3
11,475
// Copyright 2014 takahashikzn // // 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 jp.root42.indolently; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import jp.root42.indolently.function.Expression; import jp.root42.indolently.function.Statement; import jp.root42.indolently.ref.$bool; import jp.root42.indolently.ref.$int; import static jp.root42.indolently.Expressive.*; import static jp.root42.indolently.Indolently.in; import static jp.root42.indolently.Indolently.list; import static jp.root42.indolently.Indolently.not; import static jp.root42.indolently.Indolently.*; import static jp.root42.indolently.Iterative.iterator; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.junit.Assert.*; /** * A test class for {@link Expressive}. * * @author takahashikzn */ @RunWith(JUnitParamsRunner.class) public class ExpressiveTest { /** * {@link Expressive#raise(Throwable)} */ @Test public void testRaiseException() { final RaiseTestException e = new RaiseTestException(); try { fail(eval(() -> raise(e))); } catch (final RaisedException err) { assertThat(err.getCause()).isSameAs(e); } } private static final class RaiseTestException extends Exception { private static final long serialVersionUID = 1L; } /** * {@link Expressive#raise(Throwable)} */ @Test(expected = RaiseTestRuntimeException.class) public void testRaiseRuntimeException() { fail(eval(() -> raise(new RaiseTestRuntimeException()))); } private static final class RaiseTestRuntimeException extends RuntimeException { private static final long serialVersionUID = 1L; } /** * {@link Expressive#raise(Throwable)} */ @Test(expected = RaiseTestError.class) public void testRaiseError() { fail(eval(() -> raise(new RaiseTestError()))); } private static final class RaiseTestError extends Error { private static final long serialVersionUID = 1L; } /** * {@link Expressive#eval(Expression)} */ @Test public void testEval() { assertEquals( // list(1, 2, 3).map(x -> x * x), // eval( // list(1, 2, 3), // l -> l.map(x -> x * x)) // ); } /** * {@link Expressive#eval(Expression)} */ @Test public void testEval2() { final Exception e = new Exception(); try { eval(() -> { throw e; }); fail(); } catch (final RaisedException err) { assertThat(err.getCause()).isSameAs(e); } } /** * {@link Expressive#let(Statement)} */ @Test public void testLet() { final $bool called = ref(false); let(() -> called.$ = true); assertTrue(called.$); } /** * {@link Expressive#let(Statement)} */ @Test public void testLet2() { final Exception e = new Exception(); try { let(() -> { throw e; }); fail(); } catch (final RaisedException err) { assertThat(err.getCause()).isSameAs(e); } } /** * {@link Expressive#let(Object, Consumer)} */ @Test public void testLet3() { final $bool called = ref(false); let(called, x -> x.$ = true); assertTrue(called.$); } /** * {@link Expressive#match(Object)} */ @Test public void testMatch() { final Function<Integer, String> f = // ctx -> match(ctx) // .when(x -> x == 1).then(x -> "one") // .when(x -> x == 2).then(x -> "two") // .when(x -> x == 3).then("three") // .none(x -> "" + x); assertThat(f.apply(1)).isEqualTo("one"); assertThat(f.apply(2)).isEqualTo("two"); assertThat(f.apply(3)).isEqualTo("three"); assertThat(f.apply(4)).isEqualTo("4"); } /** * {@link Expressive#match(Object)} */ @Test public void testMatchType() { final Function<Number, String> f = // ctx -> match(ctx) // .type((final Long x) -> "long: " + x) // .when(x -> x.intValue() < 0).then(x -> "negative: " + x) // .when(Double.class).then(x -> "double: " + x.doubleValue()) // .none(x -> "num: " + x.doubleValue()); assertThat(f.apply(1)).isEqualTo("num: 1.0"); assertThat(f.apply(2L)).isEqualTo("long: 2"); assertThat(f.apply(3.1)).isEqualTo("double: 3.1"); assertThat(f.apply(-1)).isEqualTo("negative: -1"); } /** * {@link Expressive#match(Object)} */ @Test public void testMatchType2() { final Function<Foo, String> f = // ctx -> match(ctx) // .type((final Bar x) -> "BAR!!") // .type((final Baz x) -> "BAZ!!") // .none("FOO!!"); assertThat(f.apply(new Foo())).isEqualTo("FOO!!"); assertThat(f.apply(new Bar())).isEqualTo("BAR!!"); assertThat(f.apply(new Baz())).isEqualTo("BAZ!!"); } public static class Foo {} public static class Bar extends Foo {} public static class Baz extends Foo {} /** * {@link Expressive#match(Object)} */ @Test public void testMatchConst() { final Function<Integer, String> f = // ctx -> match(ctx) // .when(() -> 1).then(x -> "one") // .when(() -> 2).then(x -> "two") // .when(() -> 3).then("three") // .none(x -> "" + x); assertThat(f.apply(1)).isEqualTo("one"); assertThat(f.apply(2)).isEqualTo("two"); assertThat(f.apply(3)).isEqualTo("three"); assertThat(f.apply(4)).isEqualTo("4"); } /** * {@link Expressive#match(Object)} */ @Test public void testMatchFatal() { //noinspection ErrorNotRethrown try { match(1) // .when(eq(1)) // .then(() -> "NG").fatal("OK"); } catch (final AssertionError e) { assertThat(e.getMessage()).isEqualTo("OK"); } } /** * {@link Expressive#when(boolean)} */ @Test public void testWhenFatal() { //noinspection ErrorNotRethrown try { when(false).then("NG").fatal("OK"); } catch (final AssertionError e) { assertThat(e.getMessage()).isEqualTo("OK"); } } /** * {@link Expressive#match(Object)} */ @Test public void testMatchWithOps() { assertThat(match(7) // .when(eq(1)).then(() -> "NG") // .when(not(not(eq(2)))).then(() -> "NG") // .when(in(3, 4)).then(() -> "NG") // .when(or(eq(5), eq(6))).then(() -> "NG") // .when(and(ge(7), lt(8))).then(() -> "OK") // .when(gele(7, 8)).then("NG") // .fatal()).isEqualTo("OK"); } public enum EnumOfTestMatch { FOO, BAR, BAZ } /** * {@link Expressive#match(Object)} */ @Test public void testMatchEnum() { final Function<EnumOfTestMatch, String> f = // ctx -> match(ctx) // .when(() -> EnumOfTestMatch.FOO).then(x -> "foo") // .when(() -> EnumOfTestMatch.BAR).then(x -> "bar") // .none(x -> "none"); assertThat(f.apply(EnumOfTestMatch.FOO)).isEqualTo("foo"); assertThat(f.apply(EnumOfTestMatch.BAR)).isEqualTo("bar"); assertThat(f.apply(EnumOfTestMatch.BAZ)).isEqualTo("none"); } /** * {@link Expressive#when(boolean)} */ @Test public void testWhen() { final $int i = ref(0); final Supplier<String> f = // () -> when(() -> i.$ == 1).then(() -> "one") // .when(() -> i.$ == 2).then(() -> "two") // .when(() -> i.$ == 3).then("three") // .none("" + i.$); i.$ = 1; assertThat(f.get()).isEqualTo("one"); i.$ = 2; assertThat(f.get()).isEqualTo("two"); i.$ = 3; assertThat(f.get()).isEqualTo("three"); i.$ = 4; assertThat(f.get()).isEqualTo("4"); } /** * complicated type inference test of {@link Expressive#when(boolean)}. * * @param expected expected value * @param from range from * @param to range to * @param step range step */ @Parameters @Test public void testComplicatedTypeInference(final List<Integer> expected, final int from, final int to, final int step) { assertThat(list( // iterator( // ref(from), // ref -> when(from < to).then(() -> ref.$ <= to) // .when(to < from).then(() -> to <= ref.$) // .none(() -> ref.$ == from), // ref -> when(from < to) // .then(() -> ref.getThen(self -> self.$ += step)) // .none(() -> prog1(ref, () -> ref.$ -= step)) // ) // )) // .isEqualTo(expected); assertThat(list( // iterator( // ref(from), // ref -> when(from < to).then(() -> ref.$ <= to) // .when(to < from).then(() -> to <= ref.$) // .none(() -> ref.$ == from), // ref -> when(from < to) // .then(() -> ref.getThen(self -> self.$ += step)) // .none(() -> prog1(ref, () -> ref.$ -= step)) // ) // ).reduce((l, r) -> l + r)) // .isEqualTo(list(expected).reduce((l, r) -> l + r)); } static List<Object[]> parametersForTestComplicatedTypeInference() { return list( // oarray(list(1, 3, 5), 1, 6, 2), // oarray(list(3, 1, -1), 3, -1, 2), // oarray(list(1), 1, 1, 1) // ); } /** * {@link Match.IntroCase#raise(Supplier)} */ @Test public void testSwitchOfFailure() { final Function<Integer, String> f = // ctx -> match(ctx) // .when(x -> x == 1).then(x -> "one") // .when(x -> x == 2).then(x -> "two") // .raise(x -> new RuntimeException("THE TEST OF " + x)); try { f.apply(42); fail(); } catch (final RuntimeException e) { assertThat(e.getMessage()).contains("THE TEST OF 42"); } } }
27
104
0.505185
1cc3b6730234dd16f3b513768512a6e651694928
10,545
package a05_graphs_trees_heaps; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; import java.util.TreeSet; import util.Interval; import util.ListNode; import util.TreeNode; public class BinarySearchTreeBootCamp { /** * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in * the BST. */ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root.val > p.val && root.val > q.val) { return lowestCommonAncestor(root.left, p, q); } else if (root.val < p.val && root.val < q.val) { return lowestCommonAncestor(root.right, p, q); } else { return root; } } /** * <pre> Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: 2 / \ 1 3 Binary tree [2,1,3], return true. Example 2: 1 / \ 2 3 Binary tree [1,2,3], return false. * </pre> * * @author lchen * */ public boolean isValidBST(TreeNode root) { return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); } private boolean isValidBST(TreeNode root, long minVal, long maxVal) { if (root == null) return true; if (root.val >= maxVal || root.val <= minVal) return false; return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal); } /** * Given a binary search tree with non-negative values, find the minimum absolute difference * between values of any two nodes. */ private TreeNode prev; public int minDifference(TreeNode node) { if (node == null) return Integer.MAX_VALUE; int minDiff = minDifference(node.left); if (prev != null) minDiff = Math.min(minDiff, Math.abs(node.val - prev.val)); prev = node; minDiff = Math.min(minDiff, minDifference(node.right)); return minDiff; } /** * Write a program that takes as input a BST and an interval and returns the BST keys that lie * in the interval. */ public List<Integer> rangeLookupInBST(TreeNode tree, Interval interval) { List<Integer> result = new ArrayList<>(); rangeLookupInBST(tree, interval, result); return result; } private void rangeLookupInBST(TreeNode tree, Interval interval, List<Integer> result) { if (tree == null) return; if (interval.start <= tree.val && tree.val <= interval.end) { rangeLookupInBST(tree.left, interval, result); result.add(tree.val); rangeLookupInBST(tree.right, interval, result); } else if (interval.start > tree.val) { rangeLookupInBST(tree.right, interval, result); } else { rangeLookupInBST(tree.left, interval, result); } } /** * Given a non-empty binary search tree and a target value, find the value in the BST that is * closest to the target. */ public int closestValue(TreeNode root, double target) { int result = root.val; while (root != null) { if (Math.abs(target - root.val) < Math.abs(target - result)) result = root.val; root = root.val > target ? root.left : root.right; } return result; } /** * Given a non-empty binary search tree and a target value, find k values in the BST that are * closest to the target. */ public List<Integer> closestKValues(TreeNode root, double target, int k) { LinkedList<Integer> list = new LinkedList<Integer>(); closestKValues(list, root, target, k); return list; } // in-order traverse private boolean closestKValues(LinkedList<Integer> list, TreeNode node, double target, int k) { if (node == null) return false; if (closestKValues(list, node.left, target, k)) return true; if (list.size() == k) { if (Math.abs(list.getFirst() - target) < Math.abs(node.val - target)) return true; else list.removeFirst(); } list.addLast(node.val); return closestKValues(list, node.right, target, k); } /** * <pre> Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it. Note: A subtree must include all of its descendants. Here's an example: 10 / \ 5 15 / \ \ 1 8 7 The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3. * </pre> */ public int largestBSTSubtree(TreeNode root) { if (root == null) return 0; if (root.left == null && root.right == null) return 1; if (isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE)) return countTreeNode(root); return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right)); } private int countTreeNode(TreeNode root) { if (root == null) return 0; if (root.left == null && root.right == null) return 1; return 1 + countTreeNode(root.left) + countTreeNode(root.right); } /** * Given a singly linked list where elements are sorted in ascending order, convert it to a * height balanced BST. * */ public TreeNode sortedListToBST(ListNode head) { if (head == null) return null; return convertToBST(head, null); } private TreeNode convertToBST(ListNode head, ListNode tail) { ListNode slow = head; ListNode fast = head; if (head == tail) return null; while (fast != tail && fast.next != tail) { fast = fast.next.next; slow = slow.next; } TreeNode thead = new TreeNode(slow.val); thead.left = convertToBST(head, slow); thead.right = convertToBST(slow.next, tail); return thead; } /** * Given a BST which may be unbalanced. convert it into a balanced BST that has minimum possible * height. * * <pre> Input: 4 / 3 / 2 / 1 Output: 3 3 2 / \ / \ / \ 1 4 OR 2 4 OR 1 3 OR .. \ / \ 2 1 4 Input: 4 / \ 3 5 / \ 2 6 / \ 1 7 Output: 4 / \ 2 6 / \ / \ 1 3 5 7 * </pre> * * @param root * @return */ public TreeNode convertToBalancedTree(TreeNode root) { List<TreeNode> nodes = new ArrayList<>(); storeBSTNodes(root, nodes); return buildBalancedTree(nodes, 0, nodes.size() - 1); } // in-order traverse private void storeBSTNodes(TreeNode node, List<TreeNode> nodes) { if (node == null) return; storeBSTNodes(node.left, nodes); nodes.add(node); storeBSTNodes(node.right, nodes); } private TreeNode buildBalancedTree(List<TreeNode> nodes, int start, int end) { if (start > end) return null; // get mid node and make it root int mid = start + (end - start) / 2; TreeNode node = nodes.get(mid); // use index in in-order traverse node.left = buildBalancedTree(nodes, start, mid - 1); node.right = buildBalancedTree(nodes, mid + 1, end); return node; } /** * Suppose you are given the sequence in which keys are visited in an preorder traversal of a * BST, and all keys are distinct. Can you reconstruct the BST from the sequence? * * The complexity is O(n) */ private Integer rootIdx; public TreeNode rebuildBSTFromPreorder(List<Integer> preorderSequence) { rootIdx = 0; return rebuildBSTFromPreorderOnValueRange(preorderSequence, Integer.MIN_VALUE, Integer.MAX_VALUE); } private TreeNode rebuildBSTFromPreorderOnValueRange(List<Integer> preorderSequence, Integer lowerBound, Integer upperBound) { if (rootIdx == preorderSequence.size()) return null; Integer root = preorderSequence.get(rootIdx); if (root < lowerBound || root > upperBound) return null; rootIdx++; TreeNode leftSubtree = rebuildBSTFromPreorderOnValueRange(preorderSequence, lowerBound, root); TreeNode rightSubtree = rebuildBSTFromPreorderOnValueRange(preorderSequence, root, upperBound); return new TreeNode(root, leftSubtree, rightSubtree); } /** * For example, if the three arrays are [5, 10, 15], [3, 6, 9, 12, 15] and [8, 16, 24], then 15, * 15, 16 lie in the smallest possible interval which is 1. * * <br> * * Idea: We can begin with the first element of each arrays, [5, 3, 8]. The smallest interval * whose left end point is 3 has length 8 - 3 = 5. The element after 3 is 6, so we continue with * the triple (5, 6, 8). The smallest interval whose left end point is 5 has length 8 - 5 = 3. * The element after 5 is 10, so we continue with the triple (10, 6, 8)... */ public int minDistanceInKSortedArrays(List<List<Integer>> sortedArrays) { int result = Integer.MAX_VALUE; // int[3]: arrayIdx, valueIdx, value NavigableSet<int[]> currentHeads = new TreeSet<>((a, b) -> (a[2] - b[2] == 0 ? a[0] - b[0] : a[2] - b[2])); for (int i = 0; i < sortedArrays.size(); i++) { currentHeads.add(new int[] { i, 0, sortedArrays.get(i).get(0) }); } while (true) { result = Math.min(result, currentHeads.last()[2] - currentHeads.first()[2]); int[] data = currentHeads.pollFirst(); // Return if some array has no remaining elements. int nextValueIdx = data[1] + 1; if (nextValueIdx >= sortedArrays.get(data[0]).size()) { return result; } currentHeads.add(new int[] { data[0], nextValueIdx, sortedArrays.get(data[0]).get(nextValueIdx) }); } } public static void main(String[] args) { BinarySearchTreeBootCamp bootCamp = new BinarySearchTreeBootCamp(); List<Integer> preorder = Arrays.asList(3, 2, 1, 5, 4, 6); TreeNode tree = bootCamp.rebuildBSTFromPreorder(preorder); assert (3 == tree.val); assert (2 == tree.left.val); assert (1 == tree.left.left.val); assert (5 == tree.right.val); assert (4 == tree.right.left.val); assert (6 == tree.right.right.val); List<List<Integer>> sortedArrays = new ArrayList<>(); sortedArrays.add(Arrays.asList(5, 10, 15)); sortedArrays.add(Arrays.asList(3, 6, 9, 12, 15)); sortedArrays.add(Arrays.asList(8, 16, 24)); int result = bootCamp.minDistanceInKSortedArrays(sortedArrays); assert result == 1; tree = new TreeNode(10); tree.left = new TreeNode(8); tree.left.left = new TreeNode(7); tree.left.left.left = new TreeNode(6); tree.left.left.left.left = new TreeNode(5); tree = bootCamp.convertToBalancedTree(tree); assert tree.val == 7; } }
28.96978
147
0.655097
4da6bf308a5c368256fd34efed5b6aff1b2502a3
7,310
package com.ms.silverking.net.test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.GatheringByteChannel; import java.util.Random; import com.ms.silverking.time.SimpleStopwatch; import com.ms.silverking.time.Stopwatch; public class ChannelWriteTest { private final Random random; public enum Test {buffer, array, direct, mixed}; private static final int checksumSize = 16; private static final int bufferSendLimit = 16; public ChannelWriteTest() { random = new Random(); } public void runTests(String[] tests, int valueSize, int numValues, int iterations) throws IOException { for (String test : tests) { runTest(Test.valueOf(test), valueSize, numValues, iterations); } } public void runTest(Test test, int valueSize, int numValues, int iterations) throws IOException { Stopwatch sw; byte[] value; byte[] checksum; int entrySize; int totalBytes; GatheringByteChannel outChannel; long totalWritten; ByteBuffer valuesBuffer; ByteBuffer[] buffers; entrySize = valueSize + checksumSize; totalBytes = entrySize * numValues; value = new byte[valueSize]; checksum = new byte[checksumSize]; random.nextBytes(value); outChannel = new FileOutputStream(new File("/dev/null")).getChannel(); sw = new SimpleStopwatch(); switch (test) { case array: { byte[] msg; for (int j = 0; j < iterations; j++) { msg = new byte[totalBytes]; for (int i = 0; i < numValues; i++) { System.arraycopy(value, 0, msg, i * entrySize, valueSize); System.arraycopy(checksum, 0, msg, i * entrySize + valueSize, checksumSize); } valuesBuffer = ByteBuffer.wrap(msg); totalWritten = 0; while (totalWritten < totalBytes) { long written; written = outChannel.write(valuesBuffer); if (written > 0) { totalWritten += written; } } if (totalWritten != totalBytes) { throw new RuntimeException("totalWritten != totalBytes"); } } } break; case buffer: buffers = new ByteBuffer[numValues * 2]; for (int i = 0; i < numValues; i++) { buffers[i * 2] = ByteBuffer.allocate(value.length); buffers[i * 2 + 1] = ByteBuffer.allocate(checksum.length); } sw.reset(); sendBuffers(buffers, iterations, totalBytes, outChannel); break; case direct: buffers = new ByteBuffer[numValues * 2]; for (int i = 0; i < numValues; i++) { buffers[i * 2] = ByteBuffer.allocateDirect(valueSize); //buffers[i * 2].put(value); //buffers[i * 2].flip(); buffers[i * 2 + 1] = ByteBuffer.allocateDirect(checksumSize); //buffers[i * 2 + 1].put(checksum); //buffers[i * 2 + 1].flip(); } sw.reset(); sendBuffers(buffers, iterations, totalBytes, outChannel); break; case mixed: buffers = new ByteBuffer[numValues * 2]; for (int i = 0; i < numValues; i++) { buffers[i * 2] = ByteBuffer.allocateDirect(valueSize); //buffers[i * 2].put(value); //buffers[i * 2].flip(); buffers[i * 2 + 1] = ByteBuffer.allocate(checksum.length); //buffers[i * 2 + 1].put(checksum); //buffers[i * 2 + 1].flip(); } sw.reset(); sendBuffers(buffers, iterations, totalBytes, outChannel); break; } sw.stop(); System.out.printf("%s\tTime per iteration %e\n", test.toString(), sw.getElapsedSeconds()/(double)iterations); } private void fillBuffers(ByteBuffer[] buffers) throws IOException{ for (ByteBuffer buffer : buffers) { while (buffer.hasRemaining()) { buffer.put((byte)1); } } } private void sendBuffers(ByteBuffer[] buffers, int iterations, long totalToWrite, GatheringByteChannel outChannel) throws IOException{ if (false && buffers.length > bufferSendLimit) { int curGroupMax; int prevGroupMax; curGroupMax = Integer.MIN_VALUE; prevGroupMax = -1; while (curGroupMax < buffers.length - 1) { ByteBuffer[] splitBuffers; long subTotal; curGroupMax = Math.min(buffers.length - 1, prevGroupMax + bufferSendLimit); splitBuffers = new ByteBuffer[curGroupMax - prevGroupMax]; subTotal = 0; for (int i = 0; i < splitBuffers.length; i++) { splitBuffers[i] = buffers[prevGroupMax + i + 1]; subTotal += splitBuffers[i].capacity(); } sendBuffers(splitBuffers, iterations, subTotal, outChannel); prevGroupMax = curGroupMax; } } else { long totalWritten; fillBuffers(buffers); for (int j = 0; j < iterations; j++) { for (int i = 0; i < buffers.length; i++) { buffers[i].rewind(); } totalWritten = 0; while (totalWritten < totalToWrite) { long written; written = outChannel.write(buffers); if (written > 0) { totalWritten += written; } } if (totalWritten != totalToWrite) { throw new RuntimeException("totalWritten != totalToWrite"); } } } } /** * @param args */ public static void main(String[] args) { try { if (args.length != 4) { System.out.println("<tests> <valueSize> <numValues> <iterations>"); } else { String[] tests; int valueSize; int numValues; int iterations; tests = args[0].split(","); valueSize = Integer.parseInt(args[1]); numValues = Integer.parseInt(args[2]); iterations = Integer.parseInt(args[3]); new ChannelWriteTest().runTests(tests, valueSize, numValues, iterations); } } catch (Exception e) { e.printStackTrace(); } } }
37.487179
117
0.487688
ce9426df3f439c1cd02dd2fe2a700ce6e5654eca
2,581
package org.eastars.javasourcer.gui.controller.impl; import java.awt.Dimension; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.Locale; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import org.eastars.javasourcer.gui.context.ApplicationResources; import org.springframework.context.MessageSource; public abstract class AbstractDialogPanelController extends AbstractInternationalizableController { private JPanel panel; public AbstractDialogPanelController( MessageSource messageSource, Locale locale) { super(messageSource, locale); } public JPanel getPanel() { if (panel == null) { panel = buildPanel(); } return panel; } protected abstract JPanel buildPanel(); protected JPanel buildTableWithButtons(JTable table, int width, int height, ActionListener addAction, ActionListener removeAction) { table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scrollPaneLibraries = new JScrollPane(table); scrollPaneLibraries.setPreferredSize(new Dimension(width, height)); JPanel panelButton = new JPanel(); JButton buttonAdd = new JButton(ApplicationResources.PLUSSIGN); buttonAdd.addActionListener(addAction); panelButton.add(buttonAdd); JButton buttonRemove = new JButton(ApplicationResources.MINUSSIGN); buttonRemove.addActionListener(removeAction); panelButton.add(buttonRemove); return makeCompactGrid(Arrays.asList( scrollPaneLibraries, panelButton), 2, 1, 0, 0, 0, 0); } protected JPanel buildTableWithButtons( JTable table, int width, int height, ActionListener addAction, ActionListener removeAction, ActionListener editAction) { table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scrollPaneLibraries = new JScrollPane(table); scrollPaneLibraries.setPreferredSize(new Dimension(width, height)); JPanel panelButton = new JPanel(); JButton buttonEdit = new JButton(ApplicationResources.THREEDOTS); buttonEdit.addActionListener(editAction); panelButton.add(buttonEdit); JButton buttonAdd = new JButton(ApplicationResources.PLUSSIGN); buttonAdd.addActionListener(addAction); panelButton.add(buttonAdd); JButton buttonRemove = new JButton(ApplicationResources.MINUSSIGN); buttonRemove.addActionListener(removeAction); panelButton.add(buttonRemove); return makeCompactGrid(Arrays.asList( scrollPaneLibraries, panelButton), 2, 1, 0, 0, 0, 0); } }
29.329545
133
0.782642
b015db7c2a23e14863f1645b0800d451fe28ddcd
348
package error998.ple; import error998.ple.init.ModItems; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; public class PLECreativeTab extends CreativeTabs{ public PLECreativeTab() { super("creativeTab"); } // Creative Tab Icon @Override public Item getTabIconItem() { return ModItems.plasticRaw; } }
15.818182
49
0.761494
52363cbfa66d74e74bb988234ba17ff428f56340
5,730
package com.symphony.bdk.core.auth.impl; import static com.symphony.bdk.core.auth.JwtHelperTest.JWT; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.symphony.bdk.core.auth.exception.AuthUnauthorizedException; import com.symphony.bdk.gen.api.model.Token; import org.junit.jupiter.api.Test; import java.util.UUID; class AuthSessionImplTest { @Test void testRefresh() throws AuthUnauthorizedException { final String sessionToken = UUID.randomUUID().toString(); Token authToken = new Token(); authToken.setToken(sessionToken); final String kmToken = UUID.randomUUID().toString(); final BotAuthenticatorRsaImpl auth = mock(BotAuthenticatorRsaImpl.class); when(auth.retrieveSessionToken()).thenReturn(authToken); when(auth.retrieveKeyManagerToken()).thenReturn(kmToken); final AuthSessionImpl session = new AuthSessionImpl(auth); session.refresh(); assertEquals(sessionToken, session.getSessionToken()); assertEquals(kmToken, session.getKeyManagerToken()); verify(auth, times(1)).retrieveSessionToken(); verify(auth, times(1)).retrieveKeyManagerToken(); } @Test void testRefreshAuthTokenException() throws AuthUnauthorizedException { Token token = new Token(); token.setAuthorizationToken("Invalid jwt"); final BotAuthenticatorRsaImpl auth = mock(BotAuthenticatorRsaImpl.class); when(auth.retrieveSessionToken()).thenReturn(token); assertThrows(AuthUnauthorizedException.class, new AuthSessionImpl(auth)::refresh); } @Test void testRefreshBearerTokenOnly() throws AuthUnauthorizedException { final String sessionToken = UUID.randomUUID().toString(); final String kmToken = UUID.randomUUID().toString(); final BotAuthenticatorRsaImpl auth = mock(BotAuthenticatorRsaImpl.class); when(auth.retrieveSessionToken()).thenReturn(getToken(sessionToken)); when(auth.retrieveKeyManagerToken()).thenReturn(kmToken); when(auth.isCommonJwtEnabled()).thenReturn(true); when(auth.retrieveAuthorizationToken(sessionToken)).thenReturn(JWT); final AuthSessionImpl session = new AuthSessionImpl(auth); // first refresh initialise the tokens session.refresh(); verify(auth, times(1)).retrieveSessionToken(); verify(auth, never()).retrieveAuthorizationToken(any()); // second refresh should try only with the bearer token session.refresh(); verify(auth).retrieveAuthorizationToken(any()); } @Test void testGetAuthorizationTokenWithRefresh() throws AuthUnauthorizedException { final String sessionToken = UUID.randomUUID().toString(); final String kmToken = UUID.randomUUID().toString(); final BotAuthenticatorRsaImpl auth = mock(BotAuthenticatorRsaImpl.class); when(auth.retrieveSessionToken()).thenReturn(getToken(sessionToken)); when(auth.retrieveKeyManagerToken()).thenReturn(kmToken); when(auth.isCommonJwtEnabled()).thenReturn(true); when(auth.retrieveAuthorizationToken(sessionToken)).thenReturn(JWT); final AuthSessionImpl session = new AuthSessionImpl(auth); // first refresh initialise the tokens session.refresh(); verify(auth, times(1)).retrieveSessionToken(); verify(auth, never()).retrieveAuthorizationToken(any()); // getting auth token checks if token is expired and refresh bearer token only session.getAuthorizationToken(); verify(auth).retrieveAuthorizationToken(any()); verify(auth, times(1)).retrieveSessionToken(); } @Test void testGetAuthorizationTokenWhenNotSupported() throws AuthUnauthorizedException { final String sessionToken = UUID.randomUUID().toString(); final String kmToken = UUID.randomUUID().toString(); Token authToken = new Token(); authToken.setToken(sessionToken); final BotAuthenticatorRsaImpl auth = mock(BotAuthenticatorRsaImpl.class); when(auth.retrieveSessionToken()).thenReturn(authToken); when(auth.retrieveKeyManagerToken()).thenReturn(kmToken); when(auth.isCommonJwtEnabled()).thenReturn(true); final AuthSessionImpl session = new AuthSessionImpl(auth); assertThrows(UnsupportedOperationException.class, session::getAuthorizationToken); } @Test void testGetAuthorizationTokenWhenRefreshBearerFails() throws AuthUnauthorizedException { final String sessionToken = UUID.randomUUID().toString(); final String kmToken = UUID.randomUUID().toString(); final BotAuthenticatorRsaImpl auth = mock(BotAuthenticatorRsaImpl.class); when(auth.retrieveSessionToken()).thenReturn(getToken(sessionToken)); when(auth.retrieveKeyManagerToken()).thenReturn(kmToken); when(auth.isCommonJwtEnabled()).thenReturn(true); when(auth.retrieveAuthorizationToken(sessionToken)).thenThrow(AuthUnauthorizedException.class); final AuthSessionImpl session = new AuthSessionImpl(auth); // first refresh initialise the tokens session.refresh(); verify(auth, times(1)).retrieveSessionToken(); verify(auth, never()).retrieveAuthorizationToken(any()); // getting auth token fails then we refresh all tokens session.getAuthorizationToken(); verify(auth).retrieveAuthorizationToken(any()); verify(auth, times(2)).retrieveSessionToken(); } private Token getToken(String sessionToken) { Token authToken = new Token(); authToken.setToken(sessionToken); authToken.setAuthorizationToken(JWT); return authToken; } }
35.590062
99
0.760558
12575b0f9d50b27505d0145c3d2cd279894958be
3,731
package usi.dbdp.uic.base.dao; import java.util.List; import usi.dbdp.uic.dto.PageObj; import usi.dbdp.uic.dto.RoleInfo; import usi.dbdp.uic.dto.RoleUser; import usi.dbdp.uic.dto.UserInfo; import usi.dbdp.uic.dto.UserInfo4Session; import usi.dbdp.uic.entity.Menu; import usi.dbdp.uic.entity.Role; import usi.dbdp.uic.entity.User; /** * @author zhqnie * @version 2015年9月6日 上午10:33:06 * 说明 */ public interface RoleDao { /** * 给某应用增加一个角色 * @param appCode * @param role * @return */ public int addRole(Role role); /** * 更新某应用角色 * @param appCode * @param role * @return */ public int updateRole(Role role); /** * 查询某应用某角色信息 * @param appCode * @param roleId * @return */ public List<Role> queryRoleById(String appCode, long roleId); /** * 角色与菜单之间的关系删除 * @param roleId */ public boolean deleteRoleMenus(long roleId); /** *角色与用户之间的关系删除 * @param roleId 角色id */ public void deleteRoleUsers(long roleId); /** *删除某应用角色(逻辑删除,设置角色状态为失效) * @param appCode * @param roleId * @return */ public int deleteRoleById(String appCode, long roleId); /** * 激活某应用角色(将角色从失效状态改为生效) * @param appCode * @param roleId * @return */ public int activateRoleById(String appCode, long roleId); /** * 获取某应用的所有角色 分页 * @param appCode * @return */ public List<Role> getAllRolesByAppCodePage(String appCode, PageObj pageObj); /** * 获取某应用的所有角色 * @param appCode * @return */ public List<Role> getAllRolesByAppCode(String appCode); /** * @author ma.guangming * 获取某应用下某角色名称(模糊查询)的角色列表 * @param appCode 应用code * @param roleName 角色名称 * @param roleType 角色类型(0:系统角色,1:应用角色)默认0 * @param pageObj 分页对象 * @return 角色列表 */ public List<Role> getRolesByAppCodeAndRoleNameWithPage( String appCode, String roleName,Long province, int roleType, PageObj pageObj); /** * @author ma.guangming * 获取某应用下某角色拥有的所有菜单 * @param appCode 应用code * @param roleId 角色id * @return 菜单列表 */ public List<Menu> getMenusByRoleIdAndAppCode(String appCode, long roleId); /** * @author ma.guangming * 批量添加角色下的成员 * @param roleUser */ public boolean batchAddUsersIntoRole(RoleUser roleUser); /** * @author ma.guangming * 批量删除角色下的成员 * @param roleUser */ public boolean batchDeleteUsersFromRole(RoleUser roleUser); /** * 根据应用code和角色类型查询用户列表 * @param appCode应用code * @param roleType角色类型 * @return */ public List<Role> queryByAppCodeAndRoleType(String appCode, int roleType); /** * 查询某应用某角色信息 * @param appCode 应用编码 * @param roleCode 角色编码 * @return */ public List<RoleInfo> queryRoleByCode(String appCode, String roleCode); /** * @author ma.guangming * 依据登录帐号和用户姓名获取某应用下的某角色的用户列表(分页) * @param appCode 应用code * @param roleId 角色id * @param user 用户对象 * @param pageObj 分页对象 * @return 某应用下的某角色的用户列表 */ public List<UserInfo4Session> getUsersByAppCodeAndRoleIdAndUserIdAndUserNameWithPage2( String appCode, User user, long roleId, PageObj pageObj); /** * 查询某应用某角色信息 * @param appCode * @param roleId * @return */ public List<RoleInfo> queryRoleById2(String appCode, long roleId); /** * @author ma.guangming * 根据角色ID查询出的未添加进该角色的员工,用于选择添加 * @param adminOrgId 当前登录人的机构id * @param orgId 查询条件的机构id * @param adminId 当前登录人的账号 * @param roleId 角色id * @param userId 被查询员工的的登录帐号 * @param userName 被查询员工的用户名称 * @param orgName 被查询员工的机构名称 * @param pageObj 分页对象 * @return 未添加进该角色的员工 */ public List<UserInfo> getAllOtherUsersWithoutRoleByPage2( Long adminOrgId, Long orgId, String adminId, long roleId, String userId, String userName, String orgName, PageObj pageObj); /** * 角色与操作权限之间的关系删除 * @param roleId */ public void deleteRoleOpts(long roleId); }
19.534031
87
0.694184
6859148032f8f20fe7f761d155ced810fc227eea
15,671
/* * Copyright (C) 2010-2014 The MPDroid Project * * 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.namelessdev.mpdroid.fragments; import com.anpmech.mpd.MPDPlaylist; import com.anpmech.mpd.item.Music; import com.mobeta.android.dslv.DragSortListView; import com.namelessdev.mpdroid.MainMenuActivity; import com.namelessdev.mpdroid.NowPlayingActivity; import com.namelessdev.mpdroid.R; import com.namelessdev.mpdroid.helpers.AlbumInfo; import com.namelessdev.mpdroid.helpers.QueueControl; import com.namelessdev.mpdroid.models.AbstractPlaylistMusic; import com.namelessdev.mpdroid.models.PlaylistAlbum; import com.namelessdev.mpdroid.models.PlaylistSong; import com.namelessdev.mpdroid.models.PlaylistStream; import com.namelessdev.mpdroid.tools.Tools; import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.util.SparseBooleanArray; import android.view.ActionMode; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView.MultiChoiceModeListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupMenu.OnMenuItemClickListener; import java.util.ArrayList; import java.util.List; public class CollapsedPlaylistFragment extends QueueFragment implements OnMenuItemClickListener { private final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mApp); private final DragSortListView.DropListener onDrop = new DragSortListView.DropListener() { @Override public void drop(final int from, int to) { if (from != to && mFilter == null) { boolean moveDown = (to > from); if (moveDown) { to++; } int plFrom = getPlaylistPosition(from); int plTo = getPlaylistPosition(to); int number = getPlaylistPosition(from + 1) - plFrom; if (moveDown) { plTo -= number; } //Log.d("MPD Coll", "from " + from + " to "+ to + " plFrom " +plFrom + " plTo "+ plTo + " number " + number); QueueControl.run(QueueControl.MOVE, plFrom, number, plTo); } } }; protected boolean collapsedAlbums = false; protected List<PlaylistAlbum> playlistAlbums; // one Album can be expanded besides currently playing: protected int expandedAlbum = -1; protected PlaylistAlbum playlistAlbumWithSongId(int songId) { if (playlistAlbums == null) { return null; } for (PlaylistAlbum p : playlistAlbums) { if (p.hasSongId(songId)) { return p; } } return null; } @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View view = super.onCreateView(inflater, container, savedInstanceState); // only replace these 2 listeners mList.setDropListener(onDrop); mList.setMultiChoiceModeListener(new MultiChoiceModeListener() { @Override public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) { final SparseBooleanArray checkedItems = mList.getCheckedItemPositions(); final int count = mList.getCount(); final ListAdapter adapter = mList.getAdapter(); int j = 0; boolean result = true; final List<Integer> positions = new ArrayList<Integer>(); switch (item.getItemId()) { case R.id.menu_delete: for (int i = 0; i < count; i++) { if (checkedItems.get(i)) { AbstractPlaylistMusic itemi = (AbstractPlaylistMusic) adapter.getItem(i); try { positions.addAll(((PlaylistAlbum) itemi).getSongIds()); } catch (ClassCastException e) { positions.add(itemi.getSongId()); } } } result = true; case R.id.menu_crop: for (int i = 0; i < count; i++) { if (!checkedItems.get(i)) { AbstractPlaylistMusic itemi = (AbstractPlaylistMusic) adapter.getItem(i); try { positions.addAll(((PlaylistAlbum) itemi).getSongIds()); } catch (ClassCastException e) { positions.add(itemi.getSongId()); } } } result = true; default: result = false; break; } if (j > 0) { QueueControl.run(QueueControl.REMOVE_BY_ID, Tools.toIntArray(positions)); mode.finish(); } return result; } @Override public boolean onCreateActionMode(final ActionMode mode, final Menu menu) { final MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.mpd_queuemenu, menu); return true; } @Override public void onDestroyActionMode(final ActionMode mode) { mActionMode = null; mController.setSortEnabled(true); } @Override public void onItemCheckedStateChanged( final ActionMode mode, final int position, final long id, final boolean checked) { final int selectCount = mList.getCheckedItemCount(); if (selectCount == 0) { mode.finish(); } if (selectCount == 1) { mode.setTitle(R.string.actionSongSelected); } else { mode.setTitle(getString(R.string.actionSongsSelected, selectCount)); } } @Override public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) { mActionMode = mode; mController.setSortEnabled(false); return false; } }); return view; } @Override public void onListItemClick(final ListView l, final View v, final int position, final long id) { AbstractPlaylistMusic item = (AbstractPlaylistMusic) l.getAdapter().getItem(position); try { // Try collapsed album final PlaylistAlbum plA = (PlaylistAlbum) item; expandedAlbum = plA.getSongId(); update(true, position); } catch (ClassCastException cce) { expandedAlbum = -1; // none is expanded except current super.onListItemClick(l, v, position, id); // final int song = ((Music) item).getSongId(); // QueueControl.run(QueueControl.SKIP_TO_ID, song); } } private static final String TAG = "...CollapsedPlaylistFragment"; @Override public boolean onMenuItemClick(final MenuItem item) { try { // is this item is a collapsed album? PlaylistAlbum plAlbum = (PlaylistAlbum) item; } catch (ClassCastException cce) { // for non-albums just do as normal and finish return super.onMenuItemClick(item); } // handle only cases with special treatment for albums boolean done = true; switch (item.getItemId()) { case R.id.PLCX_playNext: Tools.notifyUser("playnext not implemented for albums"); break; case R.id.PLCX_moveFirst: Tools.notifyUser("Move to first not implemented for albums"); break; case R.id.PLCX_moveLast: Tools.notifyUser("Move to last not implemented for albums"); break; case R.id.PLCX_removeFromPlaylist: final PlaylistAlbum plAlbum = playlistAlbumWithSongId(mPopupSongID); QueueControl.run(QueueControl.REMOVE_BY_ID, Tools.toIntArray(plAlbum.getSongIds())); if (isAdded()) { Tools.notifyUser(R.string.deletedSongFromPlaylist); } break; default: done = false; // do like non-album break; } if (!done) { return super.onMenuItemClick(item); } else { return true; } } @SuppressLint("LongLogTag") @Override public void scrollToNowPlaying() { final int songPos = getListPosition(mApp.getMPD().getStatus().getSongPos()); if (songPos == -1) { Log.d(TAG, "Missing list item."); } else { if (mActivity instanceof MainMenuActivity) { ((NowPlayingActivity) mActivity).showQueue(); } final ListView listView = getListView(); listView.requestFocusFromTouch(); listView.setSelection(songPos); listView.clearFocus(); } } // list item number from playlist position protected int getListPosition(final int playlistpos) { int sum = 0, pos = 0; for (AbstractPlaylistMusic item : mSongList) { int s = (int) item.size(); if (sum + s < playlistpos) { sum += s; pos++; } else { return pos + (sum + s - playlistpos); } } return pos; } // there are multiple songs in one position if it is an album protected int getPlaylistPosition(final int listto) { return getPlaylistPositions(0, listto); } protected int getPlaylistPositions(final int listfrom, final int listto) { int pos = 0; int to = Math.min(listto, mSongList.size()); for (int i = listfrom; i < to; i++) { pos += mSongList.get(i).size(); } return pos; } /** * Update the current playlist fragment. * * @param forcePlayingIDRefresh Force the current track to refresh. */ @Override void update(final boolean forcePlayingIDRefresh) { update(forcePlayingIDRefresh, -1); } synchronized void update(final boolean forcePlayingIDRefresh, final int jumpTo) { collapsedAlbums = settings.getBoolean("collapseAlbums", false); // Save the scroll bar position to restore it after update final MPDPlaylist playlist = mApp.getMPD().getPlaylist(); final List<Music> musics = playlist.getMusicList(); final ArrayList<AbstractPlaylistMusic> newSongList = new ArrayList<>(musics.size()); // Save the scroll bar position to restore it after update final int firstVisibleElementIndex = mList.getFirstVisiblePosition(); View firstVisibleItem = mList.getChildAt(0); final int firstVisiblePosition = (firstVisibleItem != null) ? firstVisibleItem.getTop() : 0; if (mLastPlayingID == -1 || forcePlayingIDRefresh) { mLastPlayingID = mApp.getMPD().getStatus().getSongId(); } // The position in the song list of the currently played song int listPlayingID = -1; // collect albums playlistAlbums = new ArrayList<PlaylistAlbum>(); PlaylistAlbum plalbum = null; // Copy list to avoid concurrent exception for (final Music music : new ArrayList<>(musics)) { if (music == null) { continue; } AlbumInfo albuminfo = new AlbumInfo(music); if (plalbum == null || !albuminfo.equals(plalbum.getAlbumInfo())) { if (plalbum != null) { playlistAlbums.add(plalbum); } plalbum = new PlaylistAlbum(albuminfo); } if (plalbum != null) { plalbum.add(music); if (music.getSongId() == mLastPlayingID) { plalbum.setPlaying(true); } } } if (plalbum != null) { // remaining playlistAlbums.add(plalbum); } for (PlaylistAlbum a : playlistAlbums) { // add album item if not playing if (collapsedAlbums && !a.isPlaying() && a.size() > 1 && expandedAlbum != a.getSongId()) { if (mFilter != null && !a.hasText(mFilter)) { continue; } newSongList.add(a); } else { // else add all songs for (Music music : a.getMusic()) { final AbstractPlaylistMusic item; if (music.isStream()) { item = new PlaylistStream(music); } else { item = new PlaylistSong(music); } if (mFilter != null) { if (isFiltered(item.getAlbumArtistName()) || isFiltered(item.getAlbumName()) || isFiltered(item.getTitle())) { continue; } } if (item.getSongId() == mLastPlayingID) { if (mLightTheme) { item.setCurrentSongIconRefID(R.drawable.ic_media_play_light); } else { item.setCurrentSongIconRefID(R.drawable.ic_media_play); } item.setCurrentSongIconRefID(mLightTheme ? R.drawable.ic_media_play_light : R.drawable.ic_media_play); /** * Lie a little. Scroll to the previous * song than the one playing. That way it * shows that there are other songs before * it. */ listPlayingID = newSongList.size() - 1; } else { item.setCurrentSongIconRefID(0); } // show only songs of playing album newSongList.add(item); } } } updateScrollbar(newSongList, jumpTo >= 0 ? jumpTo : listPlayingID); } }
37.94431
125
0.544892
78a17c0e88f7eba8923cb0e94ac0e0c1bbb52860
1,353
package com.vson.hybrid.process.webchromeclient; import android.util.Log; import android.webkit.ConsoleMessage; import android.webkit.WebView; import com.vson.hybrid.WebViewCallBack; /** * @author vson */ public class WebChromeClient extends android.webkit.WebChromeClient { private WebViewCallBack mWebViewCallBack; private static final String TAG = "WebChromeClient"; public WebChromeClient(WebViewCallBack webViewCallBack) { this.mWebViewCallBack = webViewCallBack; } @Override public void onReceivedTitle(WebView view, String title) { if (mWebViewCallBack != null) { mWebViewCallBack.updateTitle(title); } else { Log.e(TAG, "WebViewCallBack is null."); } } /** * Report a JavaScript console message to the host application. The ChromeClient * should override this to process the log message as they see fit. * * @param consoleMessage Object containing details of the console message. * @return {@code true} if the message is handled by the client. */ @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { // Call the old version of this function for backwards compatability. Log.d(TAG, consoleMessage.message()); return super.onConsoleMessage(consoleMessage); } }
30.066667
84
0.700665
ffce27d166023aa574271f7f1e0c30b301f385a4
7,846
/* (c) https://github.com/MontiCore/monticore */ package de.monticore.codegen.cd2java._symboltable.scopesgenitor; import com.github.javaparser.JavaParser; import com.github.javaparser.ParseResult; import com.github.javaparser.ParserConfiguration; import de.monticore.cdbasis._ast.*; import de.monticore.cd4codebasis._ast.*; import de.monticore.codegen.cd2java.AbstractService; import de.monticore.codegen.cd2java.CdUtilsPrinter; import de.monticore.codegen.cd2java.CoreTemplates; import de.monticore.codegen.cd2java.DecorationHelper; import de.monticore.codegen.cd2java.DecoratorTestCase; import de.monticore.codegen.cd2java._symboltable.SymbolTableService; import de.monticore.codegen.cd2java._visitor.VisitorService; import de.monticore.generating.GeneratorEngine; import de.monticore.generating.GeneratorSetup; import de.monticore.generating.templateengine.GlobalExtensionManagement; import de.se_rwth.commons.logging.*; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.util.Optional; import static de.monticore.codegen.cd2java.CDModifier.*; import static de.monticore.codegen.cd2java.DecoratorAssert.assertDeepEquals; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getAttributeBy; import static de.monticore.codegen.cd2java.DecoratorTestUtil.getMethodBy; import static org.junit.Assert.*; public class ScopesGenitorDelegatorDecoratorTest extends DecoratorTestCase { private ASTCDClass scopesGenitorClass; private GlobalExtensionManagement glex; private ASTCDCompilationUnit decoratedCompilationUnit; private ASTCDCompilationUnit originalCompilationUnit; private de.monticore.types.MCTypeFacade MCTypeFacade; private ScopesGenitorDelegatorDecorator decorator; private static final String AUTOMATON_GLOBAL_SCOPE = "de.monticore.codegen.symboltable.automaton._symboltable.IAutomatonGlobalScope"; private static final String AUTOMATON_SCOPES_GENITOR = "AutomatonScopesGenitor"; private static final String AUTOMATON_TRAVERSER = "de.monticore.codegen.symboltable.automaton._visitor.AutomatonTraverser"; private static final String AST_AUTOMATON = "de.monticore.codegen.symboltable.automaton._ast.ASTAutomaton"; @Before public void setUp() { LogStub.init(); // replace log by a sideffect free variant // LogStub.initPlusLog(); // for manual testing purpose only this.glex = new GlobalExtensionManagement(); this.MCTypeFacade = MCTypeFacade.getInstance(); this.glex.setGlobalValue("astHelper", DecorationHelper.getInstance()); this.glex.setGlobalValue("cdPrinter", new CdUtilsPrinter()); decoratedCompilationUnit = this.parse("de", "monticore", "codegen", "symboltable", "Automaton"); originalCompilationUnit = decoratedCompilationUnit.deepClone(); this.glex.setGlobalValue("service", new AbstractService(decoratedCompilationUnit)); this.decorator = new ScopesGenitorDelegatorDecorator(this.glex, new SymbolTableService(decoratedCompilationUnit), new VisitorService(decoratedCompilationUnit)); //creates normal Symbol Optional<ASTCDClass> optScopeSkeletonCreator = decorator.decorate(decoratedCompilationUnit); assertTrue(optScopeSkeletonCreator.isPresent()); this.scopesGenitorClass = optScopeSkeletonCreator.get(); } @Test public void testNoStartProd() { LogStub.init(); // replace log by a sideffect free variant // LogStub.initPlusLog(); // for manual testing purpose only GlobalExtensionManagement glex = new GlobalExtensionManagement(); glex.setGlobalValue("astHelper", DecorationHelper.getInstance()); glex.setGlobalValue("cdPrinter", new CdUtilsPrinter()); ASTCDCompilationUnit cd = this.parse("de", "monticore", "codegen", "symboltable", "Automaton"); glex.setGlobalValue("service", new AbstractService(cd)); SymbolTableService mockService = Mockito.spy(new SymbolTableService(cd)); Mockito.doReturn(Optional.empty()).when(mockService).getStartProdASTFullName(Mockito.any(ASTCDDefinition.class)); ScopesGenitorDelegatorDecorator decorator = new ScopesGenitorDelegatorDecorator(glex, mockService, new VisitorService(cd)); //create non present SymbolTableCreator Optional<ASTCDClass> optScopeSkeletonCreatorDelegator = decorator.decorate(cd); assertFalse(optScopeSkeletonCreatorDelegator.isPresent()); } @Test public void testCompilationUnitNotChanged() { assertDeepEquals(originalCompilationUnit, decoratedCompilationUnit); } @Test public void testClassName() { assertEquals("AutomatonScopesGenitorDelegator", scopesGenitorClass.getName()); } @Test public void testNoSuperInterfaces() { assertFalse(scopesGenitorClass.isPresentCDInterfaceUsage()); } @Test public void testNoSuperClass() { assertFalse(scopesGenitorClass.isPresentCDExtendUsage()); } @Test public void testConstructorCount() { assertEquals(1, scopesGenitorClass.getCDConstructorList().size()); } @Test public void testZeroArgsConstructor(){ ASTCDConstructor constructor = scopesGenitorClass.getCDConstructorList().get(0); assertDeepEquals(PUBLIC, constructor.getModifier()); assertEquals("AutomatonScopesGenitorDelegator", constructor.getName()); assertTrue(constructor.isEmptyCDParameters()); assertFalse(constructor.isPresentCDThrowsDeclaration()); } @Test public void testAttributeSize() { assertEquals(4, scopesGenitorClass.getCDAttributeList().size()); } @Test public void testScopeStackAttribute() { ASTCDAttribute astcdAttribute = getAttributeBy("scopeStack", scopesGenitorClass); assertDeepEquals(PROTECTED, astcdAttribute.getModifier()); assertDeepEquals("Deque<de.monticore.codegen.symboltable.automaton._symboltable.IAutomatonScope>", astcdAttribute.getMCType()); } @Test public void testSymTabAttribute() { ASTCDAttribute astcdAttribute = getAttributeBy("symbolTable", scopesGenitorClass); assertDeepEquals(PROTECTED_FINAL, astcdAttribute.getModifier()); assertDeepEquals(AUTOMATON_SCOPES_GENITOR, astcdAttribute.getMCType()); } @Test public void testGlobalScopeAttribute() { ASTCDAttribute astcdAttribute = getAttributeBy("globalScope", scopesGenitorClass); assertDeepEquals(PROTECTED, astcdAttribute.getModifier()); assertDeepEquals(AUTOMATON_GLOBAL_SCOPE, astcdAttribute.getMCType()); } @Test public void testTraverserAttribute(){ ASTCDAttribute astcdAttribute = getAttributeBy("traverser", scopesGenitorClass); assertDeepEquals(PROTECTED, astcdAttribute.getModifier()); assertDeepEquals(AUTOMATON_TRAVERSER, astcdAttribute.getMCType()); } @Test public void testMethods() { assertEquals(1, scopesGenitorClass.getCDMethodList().size()); } @Test public void testCreateFromASTMethod() { ASTCDMethod method = getMethodBy("createFromAST", scopesGenitorClass); assertDeepEquals(PUBLIC, method.getModifier()); assertDeepEquals("de.monticore.codegen.symboltable.automaton._symboltable.IAutomatonArtifactScope", method.getMCReturnType().getMCType()); assertEquals(1, method.sizeCDParameters()); assertDeepEquals(AST_AUTOMATON, method.getCDParameter(0).getMCType()); assertEquals("rootNode", method.getCDParameter(0).getName()); } @Test public void testGeneratedCodeState() { GeneratorSetup generatorSetup = new GeneratorSetup(); generatorSetup.setGlex(glex); GeneratorEngine generatorEngine = new GeneratorEngine(generatorSetup); StringBuilder sb = generatorEngine.generate(CoreTemplates.CLASS, scopesGenitorClass, scopesGenitorClass); // test parsing ParserConfiguration configuration = new ParserConfiguration(); JavaParser parser = new JavaParser(configuration); ParseResult parseResult = parser.parse(sb.toString()); assertTrue(parseResult.isSuccessful()); } }
40.443299
142
0.787153
ac693b5cba18752fad2c061e2a9a1c0bc8972199
4,358
package pokecube.mobs.moves.world; import java.util.List; import net.minecraft.block.BlockState; import net.minecraft.enchantment.Enchantments; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.item.ItemEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import pokecube.core.PokecubeCore; import pokecube.core.events.pokemob.combat.MoveUse; import pokecube.core.handlers.events.MoveEventsHandler; import pokecube.core.interfaces.IMoveAction; import pokecube.core.interfaces.IPokemob; import pokecube.core.interfaces.Move_Base; import pokecube.core.moves.MovesUtils; import pokecube.core.moves.templates.Move_Basic; import pokecube.core.world.terrain.PokecubeTerrainChecker; import thut.api.maths.Vector3; public class ActionSmash implements IMoveAction { public ActionSmash() { } @Override public boolean applyEffect(final IPokemob user, final Vector3 location) { if (user.inCombat()) return false; boolean used = false; int count = 10; int level = user.getLevel(); final int hungerValue = PokecubeCore.getConfig().pokemobLifeSpan / 8; if (!MoveEventsHandler.canAffectBlock(user, location, this.getMoveName())) return false; level = Math.min(99, level); final int rocks = this.smashRock(user, location, true); count = (int) Math.max(1, Math.ceil(rocks * hungerValue * Math.pow((100 - level) / 100d, 3))); if (rocks > 0) { this.smashRock(user, location, false); used = true; user.applyHunger(count); } if (!used) { final World world = user.getEntity().getCommandSenderWorld(); final List<ItemEntity> items = world.getEntitiesOfClass(ItemEntity.class, location.getAABB().inflate(1)); if (!items.isEmpty()) { final Move_Base move = MovesUtils.getMoveFromName(this.getMoveName()); return PokecubeCore.MOVE_BUS.post(new MoveUse.MoveWorldAction.AffectItem(move, user, location, items)); } } return used; } private void doFortuneDrop(final BlockState state, final BlockPos pos, final World worldIn, final PlayerEntity player, final int fortune) { final ItemStack pickaxe = new ItemStack(Items.DIAMOND_PICKAXE); pickaxe.enchant(Enchantments.BLOCK_FORTUNE, fortune); state.getBlock().playerDestroy(worldIn, player, pos, state, null, pickaxe); worldIn.destroyBlock(pos, false); } @Override public String getMoveName() { return "rocksmash"; } private int smashRock(final IPokemob digger, final Vector3 v, final boolean count) { int ret = 0; final LivingEntity owner = digger.getOwner(); PlayerEntity player = null; if (owner instanceof PlayerEntity) player = (PlayerEntity) owner; final int fortune = digger.getLevel() / 30; final boolean silky = Move_Basic.shouldSilk(digger) && player != null; final World world = digger.getEntity().getCommandSenderWorld(); final Vector3 temp = Vector3.getNewVector(); temp.set(v); final int range = 1; for (int i = -range; i <= range; i++) for (int j = -range; j <= range; j++) for (int k = -range; k <= range; k++) { if (!(i == 0 || k == 0 || j == 0)) continue; temp.set(v).addTo(i, j, k); final BlockState state = temp.getBlockState(world); if (PokecubeTerrainChecker.isRock(state)) { if (!MoveEventsHandler.canAffectBlock(digger, temp, this.getMoveName(), false, true)) continue; if (!count) if (!silky) this.doFortuneDrop(state, temp.getPos(), world, player, fortune); else { Move_Basic.silkHarvest(state, temp.getPos(), world, player); temp.breakBlock(world, false); } ret++; } } return ret; } }
38.910714
119
0.614961
1ed53c200bbe4deeb1afd954d1881d9ee39a375e
1,603
/* * Copyright 2014 AgentTroll * * 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.gmail.woodyc40.commons.reflection; import java.lang.reflect.Method; /** * {@code Interface} for weak access to method invocation methods <p> <p>Used to method and {@code return} the result * the method represented by this {@code class}</p> <p> <p>Should be faster than conventional Reflection API</p> * * @param <Declaring> the {@code class} type declaring the method * @param <T> the type the method returns * @author AgentTroll * @version 1.0 * @since 1.0 */ public interface MethodManager<Declaring, T> { /** * Calls the method * * @param inst instance of the {@code class} containing the method, {@code null} for {@code static}s * @param args arguments the pass to the method invocation * @return the result of the method call */ T invoke(Declaring inst, Object... args); /** * The wrapped method contained by this {@code class} * * @return the method that this {@code class} represents */ Method raw(); }
33.395833
117
0.689333
d2ef46993e2edf5790766bf6f0b983548d8475ed
2,556
package dao; import models.News; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sql2o.Sql2o; import java.sql.Connection; import java.util.List; import static org.junit.Assert.assertEquals; public class Sql2oNewsDaoTest { private Connection con; private Sql2oNewsDao newsDao; private Sql2oDepartmentDao departmentDao; @Before public void setUp() throws Exception { String connectionString = "jdbc:postgresql://localhost:5432/news_portal"; Sql2o sql2o = new Sql2o(connectionString, "moringa", "1234"); newsDao = new Sql2oNewsDao(sql2o); departmentDao =new Sql2oDepartmentDao(sql2o); con = (Connection) sql2o.open(); } @After public void tearDown() throws Exception { con.close(); } // SetUp Helper Methods public News setUpNews(){ News news = new News ("Promotion","The company is seek to promote job groups","Daily Nation","Jobs",1); newsDao.add(news); return news; } // Organisation News public News setUpOrgNews(){ News organizationNews = new News ("Technology","Implementation of AI Technology","Kogei","Journal",1); newsDao.add(organizationNews); return organizationNews; } @Test public void add(){ News news =setUpNews(); assertEquals(1,newsDao.getAll().size()); } @Test public void add_assignsId(){ News news = setUpNews(); assertEquals(1,news.getId()); } @Test public void getAll_returns_organizationNews(){ News orgNews = setUpOrgNews(); assertEquals(1,newsDao.getAll().size()); } @Test public void getAll(){ News news1 = setUpNews(); News news2 = setUpNews(); assertEquals(2,newsDao.getAll().size()); } @Test public void getAllNewsByDepartment(){ News news = setUpNews(); List<News>allNewsByDepartmentId = newsDao.getAllNewsByDepartment(news.getDepartment_id()); assertEquals(news.getDepartment_id(),allNewsByDepartmentId.get(0).getDepartment_id()); } @Test public void deleteById(){ News news =setUpNews(); News news1= setUpNews(); assertEquals(2,newsDao.getAll().size()); newsDao.deleteById(news.getId()); assertEquals(1,newsDao.getAll().size()); } @Test public void clearAll(){ News news = setUpNews(); News news1 = setUpNews(); newsDao.clearAll(); assertEquals(0,newsDao.getAll().size()); } }
29.045455
111
0.638106
ee57c7d50b44a11a2de08c01e985257736986452
1,726
// Template Source: BaseEntityCollectionPage.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.models.Event; import com.microsoft.graph.requests.EventCollectionRequestBuilder; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.requests.EventCollectionResponse; import com.microsoft.graph.http.BaseCollectionPage; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Event Collection Page. */ public class EventCollectionPage extends BaseCollectionPage<Event, EventCollectionRequestBuilder> { /** * A collection page for Event * * @param response the serialized EventCollectionResponse from the service * @param builder the request builder for the next collection page */ public EventCollectionPage(@Nonnull final EventCollectionResponse response, @Nonnull final EventCollectionRequestBuilder builder) { super(response, builder); } /** * Creates the collection page for Event * * @param pageContents the contents of this page * @param nextRequestBuilder the request builder for the next page */ public EventCollectionPage(@Nonnull final java.util.List<Event> pageContents, @Nullable final EventCollectionRequestBuilder nextRequestBuilder) { super(pageContents, nextRequestBuilder); } }
42.097561
152
0.688876
abfda9b91c7bc7b3862ce1864f3d7d13b1938d1b
860
package com.cyecize.summer.areas.startup.models; import com.cyecize.summer.areas.routing.models.ActionMethod; import com.cyecize.summer.areas.startup.services.DependencyContainer; import java.util.Map; import java.util.Set; public class SummerAppContext { private final DependencyContainer dependencyContainer; private final Map<String, Set<ActionMethod>> actionsByMethod; public SummerAppContext(DependencyContainer dependencyContainer, Map<String, Set<ActionMethod>> actionsByMethod) { this.dependencyContainer = dependencyContainer; this.actionsByMethod = actionsByMethod; } public DependencyContainer getDependencyContainer() { return this.dependencyContainer; } public Map<String, Set<ActionMethod>> getActionsByMethod() { return this.actionsByMethod; } }
30.714286
119
0.744186
551127c263ff1f7c15d5abc5b1a989cc780ccabc
3,817
package uk.ac.ebi.tsc.portal.clouddeployment.image; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import uk.ac.ebi.tsc.portal.clouddeployment.utils.InputStreamLogger; import java.io.File; import java.io.IOException; import java.util.Map; /** * @author Jose A. Dianes <[email protected]> * @since v0.0.1 * @author Navis Raj <[email protected]> */ public class ImageInstaller { private static final Logger logger = LoggerFactory.getLogger(ImageInstaller.class); private static final String GLANCE_COMMAND = "glance"; private String osUsername; private String osTenantName; private String osAuthUrl; private String osPassword; public ImageInstaller(String osUsername, String osTenantName, String osAuthUrl, String osPassword) { this.osUsername = osUsername; this.osTenantName = osTenantName; this.osAuthUrl = osAuthUrl; this.osPassword = osPassword; } public int installImage(String imagePath, String diskFormat, String imageName) { try { activateVirtualEnvironment("venv"); // Call glance uploadImageToProvider(imagePath, diskFormat, imageName); // Deactivate venv deactivateVirtualEnvironment(); } catch (IOException e) { e.printStackTrace(); } return 0; // TODO: temporary } private int activateVirtualEnvironment(String virtualEnvironmentName) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder( "source", virtualEnvironmentName + File.separator + "bin" + File.separator + "activate"); Process p = processBuilder.start(); // TODO: return something meaningful? try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } if (p.exitValue() != 0) { InputStreamLogger.logInputStream(p.getErrorStream()); } else { InputStreamLogger.logInputStream(p.getInputStream()); } return p.exitValue(); } private int uploadImageToProvider(String imagePath, String diskFormat, String imageName) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder( "glance", "image-create", "--file", imagePath, "--disk-format", diskFormat, "--container-format", "bare", "--name", imageName ); Map<String, String> env = processBuilder.environment(); env.put("OS_USERNAME", this.osUsername); env.put("OS_TENANT_NAME", this.osTenantName); env.put("OS_AUTH_URL", this.osAuthUrl); env.put("OS_PASSWORD", this.osPassword); Process p = processBuilder.start(); // TODO: return something meaningful? try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } if (p.exitValue() != 0) { InputStreamLogger.logInputStream(p.getErrorStream()); } else { InputStreamLogger.logInputStream(p.getInputStream()); } return p.exitValue(); } private int deactivateVirtualEnvironment() throws IOException { ProcessBuilder processBuilder = new ProcessBuilder("deactivate"); Process p = processBuilder.start(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } if (p.exitValue() != 0) { InputStreamLogger.logInputStream(p.getErrorStream()); } else { InputStreamLogger.logInputStream(p.getInputStream()); } return p.exitValue(); } }
28.485075
113
0.615667
7e84372f1b8dd6695970e7f3005bbb7f59429a29
1,561
/** * Copyright (c) 2013 Martin Geisse * * This file is distributed under the terms of the MIT license. */ package name.martingeisse.guiserver.template.basic.form; import javax.xml.stream.XMLStreamException; import name.martingeisse.guiserver.template.AbstractSingleComponentConfiguration; import name.martingeisse.guiserver.template.ComponentGroupConfiguration; import name.martingeisse.guiserver.template.ConfigurationAssembler; import name.martingeisse.guiserver.xml.builder.RegisterComponentElement; import name.martingeisse.guiserver.xml.builder.StructuredElement; import org.apache.wicket.Component; /** * This configuration generates a submit button. */ @StructuredElement @RegisterComponentElement(localName = "submit") public final class SubmitButtonConfiguration extends AbstractSingleComponentConfiguration { /** * Constructor. */ public SubmitButtonConfiguration() { } /* (non-Javadoc) * @see name.martingeisse.guiserver.configuration.content.AbstractComponentConfiguration#assemble(name.martingeisse.guiserver.xmlbind.result.ConfigurationAssembler) */ @Override public void assemble(ConfigurationAssembler<ComponentGroupConfiguration> assembler) throws XMLStreamException { super.assemble(assembler); assembler.getMarkupWriter().writeEmptyElement("input"); assembler.getMarkupWriter().writeAttribute("type", "submit"); } /* (non-Javadoc) * @see name.martingeisse.guiserver.configuration.content.ComponentConfiguration#buildComponent() */ @Override public Component buildComponent() { return null; } }
30.607843
165
0.806534
7b92f9806e9ac8f86d656469f874b7c22d71e8b8
1,614
package ru.job4j.comparable; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class SortUserTest { @Test public void whenListUserThenTreeSetUser() { User user1 = new User("Ivan", 24); User user2 = new User("Sergey", 20); int result = user1.compareTo(user2); assertThat(result, is(1)); } @Test public void whenLengthThenSortLength() { SortUser sortUser = new SortUser(); User user1 = new User("Sergey", 25); User user2 = new User("Ivan", 30); User user3 = new User("Sergey", 20); User user4 = new User("Ivan", 25); List<User> result = Arrays.asList( user1, user2, user3, user4 ); sortUser.sortNameLength(result); List<User> expect = Arrays.asList( user2, user4, user1, user3 ); assertEquals(result, expect); } @Test public void whenNameAndLengthThenSortNameLength() { SortUser sortUser = new SortUser(); User user1 = new User("Sergey", 25); User user2 = new User("Ivan", 30); User user3 = new User("Sergey", 20); User user4 = new User("Ivan", 25); List<User> result = Arrays.asList( user1, user2, user3, user4 ); sortUser.sortByAllFields(result); List<User> expect = Arrays.asList( user4, user2, user3, user1 ); assertEquals(result, expect); } }
29.888889
55
0.592317
1c7eea83e6b3f2caa487b0cb2184087ac082fa42
961
package xdean.stackoverflow.rx; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import io.reactivex.MaybeSource; import io.reactivex.Observable; import io.reactivex.schedulers.Schedulers; public class Q44234633 { public static void main(String[] args) throws InterruptedException { Observable.interval(50, TimeUnit.MILLISECONDS) .takeWhile(l -> l < 8) .observeOn(Schedulers.io()) .filter(l -> isConditionTrue(l)) .observeOn(Schedulers.computation()) .firstElement() .doOnSuccess(System.out::println) .switchIfEmpty((MaybeSource<? extends Long>)o -> o.onSuccess(-1L)) .isEmpty() .filter(empty -> empty) .doOnSuccess(b -> System.out.println("TimeOut")) .blockingGet(); } private static boolean isConditionTrue(long time) { return time > ThreadLocalRandom.current().nextInt(5, 20 + 1); } }
32.033333
75
0.663892
62e1978eba48159bf0fc2d24e6eef0d0ccf14cce
5,092
package ca.bc.gov.tno.services.models; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import ca.bc.gov.tno.services.converters.Settings; import ca.bc.gov.tno.services.converters.ZonedDateTimeDeserializer; /** * ContentReference class, provides a way to capture a reference to content from * data sources. This is used to map content in Kafka and to ensure duplicates * are not entered. */ public class ContentReference extends AuditColumns { /** * The data source abbreviation. */ private String source; /** * The source content unique key. */ private String uid; /** * The Kafka topic the message is stored in. */ private String topic; /** * The Kafka partition the message is stored in. */ private int partition; /** * The Kafka offset the message was saved. */ private long offset; /** * The date and time the content was published. */ // @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = // Settings.dateTimeFormat) // @JsonDeserialize(using = ZonedDateTimeDeserializer.class) private String publishedOn; /** * The date and time the source content was updated. */ // @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = // Settings.dateTimeFormat) // @JsonDeserialize(using = ZonedDateTimeDeserializer.class) private String sourceUpdatedOn; /** * The status of the reference in Kafka. */ private WorkflowStatus workflowStatus; /** * A collection of content reference logs linked to this content. */ private List<ContentReferenceLog> logs = new ArrayList<>(); /** * Creates a new instance of a ContentReference object. */ public ContentReference() { } /** * Creates a new instance of a ContentReference object, initializes with * specified parameters. * * @param source Data source abbreviation * @param uid Unique identify of the content * @param topic The Kafka topic it was stored in */ public ContentReference(String source, String uid, String topic) { this.source = source; this.uid = uid; this.topic = topic; this.partition = -1; this.offset = -1; this.workflowStatus = WorkflowStatus.InProgress; } /** * Creates a new instance of a ContentReference object, initializes with * specified parameters. * * @param source Data source abbreviation * @param uid Unique identify of the content * @param topic The Kafka topic it was stored in * @param version Row version value */ public ContentReference(String source, String uid, String topic, long version) { this(source, uid, topic); this.setVersion(version); } /** * @return String return the source */ public String getSource() { return source; } /** * @param source the source to set */ public void setSource(String source) { this.source = source; } /** * @return String return the uid */ public String getUid() { return uid; } /** * @param uid the uid to set */ public void setUid(String uid) { this.uid = uid; } /** * @return String return the topic */ public String getTopic() { return topic; } /** * @param topic the topic to set */ public void setTopic(String topic) { this.topic = topic; } /** * @return int return the partition */ public int getPartition() { return partition; } /** * @param partition the partition to set */ public void setPartition(int partition) { this.partition = partition; } /** * @return long return the offset */ public long getOffset() { return offset; } /** * @param offset the offset to set */ public void setOffset(long offset) { this.offset = offset; } /** * @return ZonedDateTime return the publishedOn */ public String getPublishedOn() { return publishedOn; } /** * @param publishedOn the publishedOn to set */ public void setPublishedOn(String publishedOn) { this.publishedOn = publishedOn; } /** * @return ZonedDateTime return the sourceUpdatedOn */ public String getSourceUpdatedOn() { return sourceUpdatedOn; } /** * @param sourceUpdatedOn the sourceUpdatedOn to set */ public void setSourceUpdatedOn(String sourceUpdatedOn) { this.sourceUpdatedOn = sourceUpdatedOn; } /** * @return WorkflowStatus return the workflowStatus */ public WorkflowStatus getWorkflowStatus() { return workflowStatus; } /** * @param workflowStatus the workflowStatus to set */ public void setWorkflowStatus(WorkflowStatus workflowStatus) { this.workflowStatus = workflowStatus; } /** * @return List{ContentReferenceLog} return the logs */ public List<ContentReferenceLog> getLogs() { return logs; } /** * @param logs the logs to set */ public void setLogs(List<ContentReferenceLog> logs) { this.logs = logs; } }
21.668085
82
0.668303
f4092b8a7b19110a6b33e896d8410d1e85de3cea
2,638
package project2.gintonics.Entities; import project2.gintonics.Utils.Utils; public class Combination extends Primitive { private String gin; private String tonic; private String garnish; private float avgRating; private int numRatings; public Combination(){ super(); } public Combination(Gin gin, Tonic tonic, Garnish garnish){ super(Utils.getCombinationName(gin.getName(), tonic.getName(), garnish.getName())); this.gin = gin.getName(); this.tonic = tonic.getName(); this.garnish = garnish.getName(); this.avgRating = 0f; this.numRatings = 0; } public Combination(Gin gin, Tonic tonic){ super(Utils.getCombinationName(gin.getName(), tonic.getName())); this.gin = gin.getName(); this.tonic = tonic.getName(); this.avgRating = 0f; this.numRatings = 0; } public Combination(Combination other){ super(other); this.gin = other.gin; this.tonic = other.tonic; this.garnish = other.garnish; this.avgRating = other.avgRating; this.numRatings = other.numRatings; } public String getGin() { return gin; } public void setGin(String gin) { this.gin = gin; } public String getTonic() { return tonic; } public void setTonic(String tonic) { this.tonic = tonic; } public String getGarnish() { return garnish; } public void setGarnish(String garnish) { this.garnish = garnish; } public float getAvgRating() { return avgRating; } public int getNumRatings() { return numRatings; } public void updateMovingAverage(int newRating){ if(this.numRatings == 0){ this.avgRating = newRating; }else{ float avg = this.avgRating * this.numRatings; this.avgRating = (avg + newRating) / (this.numRatings + 1); } this.numRatings++; } public String prettyPrint(){ StringBuilder response = new StringBuilder(); response.append("Combination: " + name); response.append("\n\tid: " + key); response.append("\n\tgin: " + gin); response.append("\n\ttonic: " + tonic); if(garnish != null) response.append("\n\tgarnish: " + garnish); response.append("\n\tAverage rating: " + avgRating); response.append("\n\tNum ratings: " + numRatings); return response.toString(); } }
26.38
92
0.568234
54a0f61b56813f5d1cd270d9e50c94a35da9bcaa
718
package com.github.badoualy.telegram.tl.api.help; import static com.github.badoualy.telegram.tl.StreamUtils.*; import static com.github.badoualy.telegram.tl.TLObjectUtils.*; import com.github.badoualy.telegram.tl.core.TLObject; /** * Abstraction level for the following constructors: * <ul> * <li>{@link TLPassportConfig}: help.passportConfig#a098d6af</li> * <li>{@link TLPassportConfigNotModified}: help.passportConfigNotModified#bfb9f457</li> * </ul> * * @author Yannick Badoual [email protected] * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ public abstract class TLAbsPassportConfig extends TLObject { public TLAbsPassportConfig() { } }
32.636364
95
0.756267
b23c17aa3bb32a41886511db92f24e0773466747
1,047
package com.gusfot.service; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.gusfot.pray.model.Pray; import com.gusfot.pray.service.PrayService; public class PrayServiceTest { @Autowired private PrayService prayService; @Test public void testRegist() { Pray pray = new Pray(); boolean result = prayService.regist(pray ); assertTrue(result); } @Test public void testModify() { Pray pray = new Pray(); boolean result = prayService.modify(pray ); assertTrue(result); } @Test public void testRemove() { Integer prayId = null; boolean result = prayService.remove(prayId ); assertTrue(result); } @Test public void testGet() { Integer prayId = null; Pray result = prayService.get(prayId ); assertTrue(result != null); } @Test public void testGetList() { Integer prayId = null; List<Pray> result = prayService.getList( ); assertTrue(result != null); } }
17.163934
62
0.69914
056c35d25b624b14be8b6ba398ca18cf6de2a554
265
package net.thevpc.nuts.toolbox.ndiff.jar; public interface DiffItemCreateContext { DiffEvalContext getEvalContext(); DiffCommand getDiff(); DiffKey getKey(); DiffStatus getStatus(); String getSourceValue(); String getTargetValue(); }
16.5625
42
0.716981
23987012fff839a8321016b7afb84cc82aba5a8b
115
package com.sq.resume.dao; import com.sq.resume.bean.Award; public interface AwardDao extends BaseDao<Award> { }
16.428571
50
0.773913
1910e9b7483de0d79913f7a82b36f93a7562c6ee
695
// Copyright (c) 2017, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8; import com.android.tools.r8.utils.AndroidApp; import com.android.tools.r8.utils.OutputMode; import java.io.IOException; import java.nio.file.Path; /** Represents the output of a D8 compilation. */ public class D8Output extends BaseOutput { D8Output(AndroidApp app, OutputMode outputMode) { super(app, outputMode); } @Override public void write(Path output) throws IOException { getAndroidApp().write(output, getOutputMode()); } }
30.217391
77
0.74964
faf631705c842760597d87bc1d32d3e4cf1be930
2,927
package org.robobinding.viewattribute.event; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.robobinding.BindingContext; import org.robobinding.attribute.Command; import org.robobinding.attribute.EventAttribute; import org.robobinding.presentationmodel.PresentationModelAdapter; import org.robobinding.viewattribute.ViewAttributeContractTest; import org.robobinding.widget.view.ClickEvent; import android.view.View; /** * * @since 1.0 * @version $Revision: 1.0 $ * @author Robert Taylor */ @RunWith(MockitoJUnitRunner.class) public final class EventViewAttributeBinderTest extends ViewAttributeContractTest<EventViewAttributeBinder<View>> { @Mock private BindingContext bindingContext; @Mock private View view; @Mock private EventViewAttribute<View> viewAttribute; @Mock private EventAttribute attribute; private EventViewAttributeBinder<View> viewAttributeBinder; @Before public void setUp() { viewAttributeBinder = new EventViewAttributeBinder<View>(view, viewAttribute, attribute); } @Test public void givenAMatchingCommandWithArgs_whenBinding_thenBindWithTheCommand() { Command commandWithArgs = mock(Command.class); Mockito.<Class<?>> when(viewAttribute.getEventType()).thenReturn(ClickEvent.class); when(attribute.findCommand(bindingContext, ClickEvent.class)).thenReturn(commandWithArgs); viewAttributeBinder.bindTo(bindingContext); verify(viewAttribute).bind(view, commandWithArgs); } @Test public void givenAMatchingCommandWithNoArgs_whenBinding_thenBindWithTheCommand() { Command commandWithNoArgs = mock(Command.class); when(attribute.findCommand(bindingContext)).thenReturn(commandWithNoArgs); viewAttributeBinder.bindTo(bindingContext); verify(viewAttribute).bind(view, commandWithNoArgs); } @Test @Ignore @Override public void whenAnExceptionIsThrownDuringPreInitializingView_thenCatchAndRethrowAsBindingException() { // Ignored as PreInitializingView is not supported by event attribute. } @Override protected EventViewAttributeBinder<View> throwsExceptionDuringPreInitializingView() { throw new UnsupportedOperationException(); } @Override protected EventViewAttributeBinder<View> throwsExceptionDuringBinding() { return new ExceptionDuringBinding(null, null, attribute); } private static class ExceptionDuringBinding extends EventViewAttributeBinder<View> { public ExceptionDuringBinding(View view, EventViewAttribute<View> viewAttribute, EventAttribute attribute) { super(view, viewAttribute, attribute); } @Override void performBind(PresentationModelAdapter presentationModelAdapter) { throw new RuntimeException(); } } }
30.810526
115
0.815169
cbbf055bb0478a3bb3f2e9c247d0eff9325e23fe
4,042
// // ======================================================================== // Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under // the terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0 // // This Source Code may also be made available under the following // Secondary Licenses when the conditions for such availability set // forth in the Eclipse Public License, v. 2.0 are satisfied: // the Apache License v2.0 which is available at // https://www.apache.org/licenses/LICENSE-2.0 // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.websocket.core.server; import java.io.IOException; import java.util.function.Function; import org.eclipse.jetty.io.ByteBufferPool; import org.eclipse.jetty.util.DecoratedObjectFactory; import org.eclipse.jetty.websocket.core.FrameHandler; import org.eclipse.jetty.websocket.core.WebSocketComponents; import org.eclipse.jetty.websocket.core.WebSocketExtensionRegistry; public interface WebSocketNegotiator extends FrameHandler.Customizer { FrameHandler negotiate(Negotiation negotiation) throws IOException; WebSocketExtensionRegistry getExtensionRegistry(); DecoratedObjectFactory getObjectFactory(); ByteBufferPool getByteBufferPool(); WebSocketComponents getWebSocketComponents(); static WebSocketNegotiator from(Function<Negotiation, FrameHandler> negotiate) { return new AbstractNegotiator() { @Override public FrameHandler negotiate(Negotiation negotiation) { return negotiate.apply(negotiation); } }; } static WebSocketNegotiator from(Function<Negotiation, FrameHandler> negotiate, FrameHandler.Customizer customizer) { return new AbstractNegotiator(null, customizer) { @Override public FrameHandler negotiate(Negotiation negotiation) { return negotiate.apply(negotiation); } }; } static WebSocketNegotiator from( Function<Negotiation, FrameHandler> negotiate, WebSocketComponents components, FrameHandler.Customizer customizer) { return new AbstractNegotiator(components, customizer) { @Override public FrameHandler negotiate(Negotiation negotiation) { return negotiate.apply(negotiation); } }; } abstract class AbstractNegotiator implements WebSocketNegotiator { final WebSocketComponents components; final FrameHandler.Customizer customizer; public AbstractNegotiator() { this(null, null); } public AbstractNegotiator(WebSocketComponents components, FrameHandler.Customizer customizer) { this.components = components == null ? new WebSocketComponents() : components; this.customizer = customizer; } @Override public void customize(FrameHandler.Configuration configurable) { if (customizer != null) customizer.customize(configurable); } @Override public WebSocketExtensionRegistry getExtensionRegistry() { return components.getExtensionRegistry(); } @Override public DecoratedObjectFactory getObjectFactory() { return components.getObjectFactory(); } @Override public ByteBufferPool getByteBufferPool() { return components.getBufferPool(); } @Override public WebSocketComponents getWebSocketComponents() { return components; } public FrameHandler.Customizer getCustomizer() { return customizer; } } }
30.164179
118
0.637061
2c427dc9ccee0139cfc41d95f0730d277058c5a6
2,096
package com.lukedeighton.wheelsample; /** * Created by Akash Wangalwar on 20-12-2016. */ import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Path; import android.graphics.Point; import android.util.AttributeSet; import android.view.View; public class Slice extends View { Paint mPaint; Path mPath; public enum Direction { NORTH, SOUTH, EAST, WEST } public Slice(Context context) { super(context); create(); } public Slice(Context context, AttributeSet attrs) { super(context, attrs); create(); } public void setColor(int color) { mPaint.setColor(color); invalidate(); } private void create() { mPaint = new Paint(); mPaint.setStyle(Style.FILL); mPaint.setColor(Color.WHITE); } @Override protected void onDraw(Canvas canvas) { mPath = calculate(Direction.SOUTH); canvas.drawPath(mPath, mPaint); } private Path calculate(Direction direction) { Point p1 = new Point(); p1.x = 0; p1.y = 0; Point p2 = null, p3 = null; int width = getWidth(); if (direction == Direction.NORTH) { p2 = new Point(p1.x + width, p1.y); p3 = new Point(p1.x + (width / 2), p1.y - width); } else if (direction == Direction.SOUTH) { p2 = new Point(p1.x + width, p1.y); p3 = new Point(p1.x + (width / 2), p1.y + width); } else if (direction == Direction.EAST) { p2 = new Point(p1.x, p1.y + width); p3 = new Point(p1.x - width, p1.y + (width / 2)); } else if (direction == Direction.WEST) { p2 = new Point(p1.x, p1.y + width); p3 = new Point(p1.x + width, p1.y + (width / 2)); } Path path = new Path(); path.moveTo(p1.x, p1.y); path.lineTo(p2.x, p2.y); path.lineTo(p3.x, p3.y); return path; } }
24.952381
61
0.567748
4970656f20b4c7cae55043dcec21ed76c0c6dd91
3,775
package l2f.gameserver.skills.skillclasses; import java.util.ArrayList; import java.util.List; import l2f.gameserver.model.Creature; import l2f.gameserver.model.Player; import l2f.gameserver.model.Skill; import l2f.gameserver.model.instances.MonsterInstance; import l2f.gameserver.model.items.ItemInstance; import l2f.gameserver.model.reward.RewardItem; import l2f.gameserver.network.serverpackets.SystemMessage2; import l2f.gameserver.network.serverpackets.components.SystemMsg; import l2f.gameserver.templates.StatsSet; import l2f.gameserver.utils.ItemFunctions; public class Sweep extends Skill { public Sweep(StatsSet set) { super(set); } @Override public boolean checkCondition(Creature activeChar, Creature target, boolean forceUse, boolean dontMove, boolean first) { if (isNotTargetAoE()) return super.checkCondition(activeChar, target, forceUse, dontMove, first); if (target == null) return false; if (!target.isMonster() || !target.isDead()) { activeChar.sendPacket(SystemMsg.INVALID_TARGET); return false; } if (!((MonsterInstance) target).isSpoiled()) { activeChar.sendPacket(SystemMsg.SWEEPER_FAILED_TARGET_NOT_SPOILED); return false; } if (!((MonsterInstance) target).isSpoiled((Player) activeChar)) { activeChar.sendPacket(SystemMsg.THERE_ARE_NO_PRIORITY_RIGHTS_ON_A_SWEEPER); return false; } return super.checkCondition(activeChar, target, forceUse, dontMove, first); } @Override public void useSkill(Creature activeChar, List<Creature> targets) { if (!activeChar.isPlayer()) return; Player player = (Player) activeChar; List<MonsterInstance> monstersToDecay = new ArrayList<>(); for (Creature targ : targets) { if (targ == null || !targ.isMonster() || !targ.isDead() || !((MonsterInstance) targ).isSpoiled()) continue; MonsterInstance target = (MonsterInstance) targ; if (!target.isSpoiled(player)) { activeChar.sendPacket(SystemMsg.THERE_ARE_NO_PRIORITY_RIGHTS_ON_A_SWEEPER); continue; } List<RewardItem> items = target.takeSweep(); if (items == null) { activeChar.getAI().setAttackTarget(null); target.endDecayTask(); continue; } for (RewardItem item : items) { ItemInstance sweep = ItemFunctions.createItem(item.itemId); sweep.setCount(item.count); if (player.isInParty() && player.getParty().isDistributeSpoilLoot()) { player.getParty().distributeItem(player, sweep, null); continue; } if (!player.getInventory().validateCapacity(sweep) || !player.getInventory().validateWeight(sweep)) { sweep.dropToTheGround(player, target); continue; } player.getInventory().addItem(sweep, "Sweep"); SystemMessage2 smsg; if (item.count == 1) { smsg = new SystemMessage2(SystemMsg.YOU_HAVE_OBTAINED_S1); smsg.addItemName(item.itemId); player.sendPacket(smsg); } else { smsg = new SystemMessage2(SystemMsg.YOU_HAVE_OBTAINED_S2_S1); smsg.addItemName(item.itemId); smsg.addInteger(item.count); player.sendPacket(smsg); } if (player.isInParty()) if (item.count == 1) { smsg = new SystemMessage2(SystemMsg.C1_HAS_OBTAINED_S2_BY_USING_SWEEPER); smsg.addName(player); smsg.addItemName(item.itemId); player.getParty().sendPacket(player, smsg); } else { smsg = new SystemMessage2(SystemMsg.C1_HAS_OBTAINED_S3_S2_BY_USING_SWEEPER); smsg.addName(player); smsg.addItemName(item.itemId); smsg.addInteger(item.count); player.getParty().sendPacket(player, smsg); } } activeChar.getAI().setAttackTarget(null); monstersToDecay.add(target); } for (MonsterInstance c : monstersToDecay) c.endDecayTask(); } }
26.215278
119
0.708874
02fe871eb9610e264eb6f0b58468df1bc825640a
502
package com.github.ztgreat.leetcode.problem_121; /** * 思路:找最低点到最高点的差 */ public class Solution { public int maxProfit(int[] prices) { int minPrices = Integer.MAX_VALUE; int maxProfit = 0; for(int i=0;i<prices.length;i++){ if(prices[i]<minPrices){ minPrices=prices[i]; } if(prices[i]-minPrices>maxProfit){ maxProfit = prices[i]-minPrices; } } return maxProfit; } }
18.592593
48
0.525896
6674691bf14b87a6919928d351f8ba11f80798e4
21,873
/******************************************************************************* * Copyright 2018 Niranjan Khare * * 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.seleniumng.ui; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.jooq.Condition; import org.jooq.DataType; import org.jooq.Field; import org.jooq.InsertValuesStepN; import org.jooq.Record; import org.jooq.Record1; import org.jooq.Record16; import org.jooq.Record2; import org.jooq.Record3; import org.jooq.Record4; import org.jooq.Result; import org.jooq.Select; import org.jooq.SelectConditionStep; import org.jooq.SelectField; import org.jooq.SelectJoinStep; import org.jooq.SelectWhereStep; import org.jooq.Table; import org.jooq.TableField; import org.jooq.TableLike; import org.jooq.UpdateSetMoreStep; import org.jooq.impl.DSL; import org.jooq.impl.TableImpl; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import db.jooq.generated.automationDb.*; import db.jooq.generated.automationDb.tables.records.ExtendedpropsRecord; import db.jooq.generated.automationDb.tables.records.GuimapRecord; import db.jooq.generated.automationDb.tables.records.PagesRecord; import db.jooq.generated.automationDb.tables.records.PropertiesRecord; import static db.jooq.generated.automationDb.Automation.AUTOMATION; import static db.jooq.generated.automationDb.tables.Guimap.*; import static db.jooq.generated.automationDb.tables.Pages.*; import static db.jooq.generated.automationDb.tables.Types.*; import static db.jooq.generated.automationDb.tables.Propsview.*; import static db.jooq.generated.automationDb.tables.Extendedpropsview.*; import static db.jooq.generated.automationDb.tables.Properties.*; import static db.jooq.generated.automationDb.tables.Extendedprops.*; import static db.jooq.generated.automationDb.tables.Propwriterview.*; public class LibDatabase { private static List<String> allTables = getTableList(); public static void main(String[] args) { String x = Utils.getScriptResource(LibDatabase.class, "DATABASE.sql"); System.out.println(x); } public static List<String> getTableFields(String tableName) { // Connection is the only JDBC resource that we need // PreparedStatement and ResultSet are handled by jOOQ, internally Table<?> result = null; List<Table<?>> tables = Automation.AUTOMATION.getTables(); for (Table<?> t : tables) { if (t.getName().toUpperCase().equals(tableName.toUpperCase())) { result = t; break; } } // TODO: validate and throw error if result is still null; org.jooq.Field<?>[] fieldList = result.fields(); List<String> returnList = new ArrayList<String>(); for (org.jooq.Field<?> tf : fieldList) { returnList.add(tf.getName()); } return returnList; } public static String insertUpdatePages(LinkedHashMap<String, LinkedHashMap<String, String>> postParamMap) { try { List<Integer> pagesToDelete = new ArrayList<Integer>(); for (Entry<String, LinkedHashMap<String, String>> row : postParamMap.entrySet()) { // for // 1 Boolean isInsert = false; LinkedHashMap<String, String> fieldMap = row.getValue(); Set<String> keys = fieldMap.keySet(); List<TableField<?, ?>> pagesFields = new ArrayList<TableField<?, ?>>(); List<Object> pagesValues = new ArrayList<Object>(); Integer pageId = null; for (String key : keys) { if (key.equalsIgnoreCase("delete")) { if (!fieldMap.get(key).equalsIgnoreCase("")) { pagesToDelete.add(Integer.parseInt(fieldMap.get(key))); } continue; } if (key.equalsIgnoreCase("PAGEID")) { isInsert = fieldMap.get(key).equalsIgnoreCase(""); if (!isInsert) pageId = Integer.parseInt(fieldMap.get(key)); else continue; } else { if (Arrays.asList(PAGES.fields()).contains(PAGES.field(key))) { System.out.println("adding key:" + key); pagesFields.add((TableField<PagesRecord, ?>) PAGES.field(key)); pagesValues.add(fieldMap.get(key)); } } } if (!isInsert) { if (pagesFields.size() > 0) { UpdateSetMoreStep<PagesRecord> updateGuiMap = (UpdateSetMoreStep<PagesRecord>) getTableUpdateStatement( PAGES, pagesFields, pagesValues); updateGuiMap.where(PAGES.PAGEID.eq(pageId)).execute(); } } else { if (!pagesFields.contains(PAGES.PARENTID)) { pagesFields.add(PAGES.PARENTID); pagesValues.add(-1); } InsertValuesStepN<?> insertSetStepGuiMap = DbManager.getOpenContext().insertInto(PAGES, pagesFields); insertSetStepGuiMap.values(pagesValues); Result<?> x = insertSetStepGuiMap.returning(PAGES.PAGEID).fetch(); pageId = x.getValue(0, PAGES.PAGEID); } } DbManager.getOpenContext().delete(PAGES).where(PAGES.PAGEID.in(pagesToDelete)).execute(); } catch (Exception e) { System.out.println("Some problem updating database:"); e.printStackTrace(); } System.out.println("done"); return LibHtml.getPageProvisioningForm(); } public static String updateGuiMap(String pageName, LinkedHashMap<String, LinkedHashMap<String, String>> cleanParamMap) { try { List<Integer> fieldsToDelete = new ArrayList<Integer>(); for (Entry<String, LinkedHashMap<String, String>> row : cleanParamMap.entrySet()) { Boolean isInsert = false; LinkedHashMap<String, String> fieldMap = row.getValue(); Set<String> keys = fieldMap.keySet(); List<TableField<?, ?>> guimapFields = new ArrayList<TableField<?, ?>>(); List<Object> guimapValues = new ArrayList<Object>(); Integer pageId = DbManager.getOpenContext().select(PAGES.PAGEID).from(PAGES) .where(PAGES.PAGENAME.eq(pageName)).fetchOne(PAGES.PAGEID); List<TableField<?, ?>> propertiesFields = new ArrayList<TableField<?, ?>>(); List<Object> propertiesValues = new ArrayList<Object>(); List<TableField<?, ?>> expropertiesFields = new ArrayList<TableField<?, ?>>(); List<Object> expropertiesValues = new ArrayList<Object>(); Integer currentGuiMapId = null; for (String key : keys) { if (key.equalsIgnoreCase("delete")) { if (!fieldMap.get(key).equalsIgnoreCase("")) { fieldsToDelete.add(Integer.parseInt(fieldMap.get(key))); } continue; } if (key.equalsIgnoreCase("GUIMAPID")) { isInsert = fieldMap.get(key).equalsIgnoreCase(""); if (!isInsert) currentGuiMapId = Integer.parseInt(fieldMap.get(key)); else ; } else { if (GUIMAP.field(key) != null) { guimapFields.add((TableField<GuimapRecord, ?>) GUIMAP.field(key)); guimapValues.add(fieldMap.get(key)); } else if (PROPERTIES.field(key) != null) { propertiesFields.add((TableField<PropertiesRecord, ?>) PROPERTIES.field(key)); propertiesValues.add((Object) fieldMap.get(key)); } else if (EXTENDEDPROPS.field(key) != null) { expropertiesFields.add((TableField<ExtendedpropsRecord, ?>) EXTENDEDPROPS.field(key)); expropertiesValues.add(fieldMap.get(key)); } } } if (!isInsert) { if (guimapFields.size() > 0) { UpdateSetMoreStep<GuimapRecord> updateGuiMap = (UpdateSetMoreStep<GuimapRecord>) getTableUpdateStatement( GUIMAP, guimapFields, guimapValues); updateGuiMap.where(GUIMAP.GUIMAPID.eq(currentGuiMapId)).execute(); } if (propertiesFields.size() > 0) { // propertiesFields.add(PROPERTIES.LOCATORS); // LinkedHashMap <String,String>map = new LinkedHashMap<String,String>(); // map.put((String)propertiesValues.get(propertiesFields.indexOf(PROPERTIES.LOCATORTYPE)), (String)propertiesValues.get(propertiesFields.indexOf(PROPERTIES.LOCATORVALUE))); // List<LinkedHashMap<String,String>> list = Arrays.asList(map); // String json = new Gson().toJson(map); // propertiesValues.add(json); UpdateSetMoreStep<PropertiesRecord> updateProperties = (UpdateSetMoreStep<PropertiesRecord>) getTableUpdateStatement( PROPERTIES, propertiesFields, propertiesValues); updateProperties.where(PROPERTIES.GUIMAPID.eq(currentGuiMapId)).execute(); } if (expropertiesFields.size() > 0) { UpdateSetMoreStep<ExtendedpropsRecord> updateExtendedProperties = (UpdateSetMoreStep<ExtendedpropsRecord>) getTableUpdateStatement( EXTENDEDPROPS, expropertiesFields, expropertiesValues); updateExtendedProperties.where(EXTENDEDPROPS.GUIMAPID.eq(currentGuiMapId)).execute(); } } else { guimapFields.add(GUIMAP.PAGEID); guimapValues.add(pageId); InsertValuesStepN<?> insertSetStepGuiMap = DbManager.getOpenContext().insertInto(GUIMAP, guimapFields); insertSetStepGuiMap.values(guimapValues); Result<?> x = insertSetStepGuiMap.returning(GUIMAP.GUIMAPID).fetch(); currentGuiMapId = x.getValue(0, GUIMAP.GUIMAPID); propertiesFields.add(PROPERTIES.GUIMAPID); propertiesValues.add(currentGuiMapId); InsertValuesStepN<?> insertSetStepProperties = DbManager.getOpenContext().insertInto(PROPERTIES, propertiesFields); insertSetStepProperties.values(propertiesValues).execute(); expropertiesFields.add(EXTENDEDPROPS.GUIMAPID); expropertiesValues.add(currentGuiMapId); InsertValuesStepN<?> insertSetStepExtendedProps = DbManager.getOpenContext() .insertInto(EXTENDEDPROPS, expropertiesFields); insertSetStepExtendedProps.values(expropertiesValues).execute(); } } if (!fieldsToDelete.isEmpty()) DbManager.getOpenContext().delete(GUIMAP).where(GUIMAP.GUIMAPID.in(fieldsToDelete)).execute(); System.out.println("done"); } catch (Exception e) { e.printStackTrace(); } return LibHtml.getPageUpdateGUIForm(pageName); } private static List<String> getTableList() { List<String> tables = new ArrayList<String>(); for (TableLike<?> t : Automation.AUTOMATION.getTables()) { tables.add(((Table) t).getName()); } return tables; } public static LinkedHashMap getAvailablePages() { return getKeyValues(PAGES.PAGENAME, PAGES.PAGEDESCRIPTION, PAGES); } public static LinkedHashMap getAvailablePageIds() { LinkedHashMap<String, String> pageData = getKeyValues(PAGES.PAGEID, PAGES.PAGENAME, PAGES); LinkedHashMap<String, Object> toReturn = new LinkedHashMap<String, Object>(); for (String key : pageData.keySet()) { toReturn.put(key, Arrays.asList(pageData.get(key), null)); } return toReturn; } public static LinkedHashMap getStandardTypes() { // LinkedHashMap oldMap = getTypes("STANDARD"); LinkedHashMap<String, String[]> list = new LinkedHashMap<String, String[]>(); SelectConditionStep<Record3<String, String, String>> x = DbManager.getOpenContext() .select(TYPES.ABRV, TYPES.CLASS, TYPES.PROPERTYMAP).from(TYPES).where(TYPES.TYPE.eq("STANDARD")); for (Record rec : x.fetch()) { String[] nestedMap = new String[2]; nestedMap[0] = rec.get(TYPES.CLASS); nestedMap[1] = rec.get(TYPES.PROPERTYMAP); list.put(rec.get(TYPES.CLASS), nestedMap); } return list; } public static LinkedHashMap getCustomTypes() { return getTypes("CUSTOM"); } private static LinkedHashMap getTypes(String classType) { LinkedHashMap<String, String[]> list = new LinkedHashMap<String, String[]>(); SelectConditionStep<Record3<String, String, String>> x = DbManager.getOpenContext() .select(TYPES.ABRV, TYPES.CLASS, TYPES.PROPERTYMAP).from(TYPES).where(TYPES.TYPE.eq(classType)); for (Record rec : x.fetch()) { String[] nestedMap = new String[2]; nestedMap[0] = rec.get(TYPES.CLASS); nestedMap[1] = rec.get(TYPES.PROPERTYMAP); list.put(rec.get(TYPES.CLASS), nestedMap); } return list; } private static LinkedHashMap getKeyValues(SelectField keyField, SelectField valueField, Table table) { LinkedHashMap<String, String> list = new LinkedHashMap<String, String>(); SelectJoinStep<Record2<String, String>> x = DbManager.getOpenContext().select(keyField, valueField).from(table); for (Record rec : x.fetch()) { list.put(rec.get(keyField.getName()).toString(), rec.get(valueField.getName()).toString()); } return list; } public static Object getUIPropsView(String tableName, String pageName) { // Connection is the only JDBC resource that we need // PreparedStatement and ResultSet are handled by jOOQ, internally Table<?> table = AUTOMATION.getTable(tableName.toUpperCase()); Collection<Condition> conditions = new ArrayList<Condition>(); SelectConditionStep<?> x = DbManager.getOpenContext().selectFrom(table).where(PROPSVIEW.PAGENAME.eq(pageName)); List<Object> returnList = new ArrayList<Object>(); Result<?> result = x.fetch(); List<Object> fields = new ArrayList<Object>(); for (Field<?> f : result.fields()) { String fName = f.getName(); if (!fName.equalsIgnoreCase("MAPPEDCLASS")) fields.add(fName); else continue; } // fields.remove(fields.indexOf("MAPPEDCLASS")); returnList.add(fields); for (Record r : result) { List<Object> values1 = new ArrayList<Object>(); for (Object f : fields) { values1.add(r.get((String) f)); } returnList.add(values1); } return returnList; } public static Object getPageExtendedProperties(Integer gId) { // Table<?> table = AUTOMATION.getTable(tableName.toUpperCase()); Collection<Condition> conditions = new ArrayList<Condition>(); SelectConditionStep<?> x = DbManager.getOpenContext().selectFrom(EXTENDEDPROPSVIEW) .where(EXTENDEDPROPSVIEW.GUIMAPID.equal(gId)); List<Object> returnList = new ArrayList<Object>(); Result<?> result = x.fetch(); List<Object> fields = new ArrayList<Object>(); for (Field<?> f : result.fields()) { fields.add(f.getName()); } returnList.add(fields); List<Object> values = new ArrayList<Object>(); for (Record r : result) { for (Field<?> f : r.fields()) { values.add(r.get(f)); } returnList.add(values); } return returnList; } public static Object getExtendedProptypes(String tableName) { LinkedHashMap<String, String[]> list = new LinkedHashMap<String, String[]>(); SelectConditionStep<Record3<String, String, String>> x = DbManager.getOpenContext() .select(TYPES.ABRV, TYPES.CLASS, TYPES.PROPERTYMAP).from(TYPES).where(TYPES.HASEXTENDEDPROPS.isTrue()); for (Record rec : x.fetch()) { String[] nestedMap = new String[2]; nestedMap[0] = rec.get(TYPES.CLASS); nestedMap[1] = rec.get(TYPES.PROPERTYMAP); list.put(rec.get(TYPES.CLASS), nestedMap); } return list; } public static UpdateSetMoreStep<?> getTableUpdateStatement(TableImpl<?> table, List<TableField<?, ?>> tableFields, List<Object> values) { UpdateSetMoreStep<?> updateStatement = (UpdateSetMoreStep<?>) DbManager.getOpenContext().update(table);// .set(f, // DSL.cast(values.get(0), t)); for (Integer i = 0; i < tableFields.size(); i++) { Field<?> f = table.field(tableFields.get(i)); ; DataType<?> t = f.getDataType(); Field x = DSL.cast(values.get(i), t); updateStatement = updateStatement.set(f, x); } return updateStatement; } public static LinkedHashMap<String, LinkedHashMap<String, String>> getPageGuiMapData(String webPage) { LinkedHashMap<String, LinkedHashMap<String, String>> pageData = new LinkedHashMap<String, LinkedHashMap<String, String>>(); SelectConditionStep<Record4<String, String, String, String>> selectStatement = DbManager.getOpenContext() .select(PROPSVIEW.CONTROLNAME, PROPSVIEW.MAPPEDCLASS, PROPSVIEW.STANDARDCLASS, TYPES.ABRV) .from(PROPSVIEW).innerJoin(TYPES).on(PROPSVIEW.STANDARDCLASS.eq(TYPES.CLASS)) .where(PROPSVIEW.PAGENAME.equal(webPage)); for (Record r : selectStatement.fetch()) { LinkedHashMap<String, String> classmap = new LinkedHashMap<String, String>(); classmap.put("standardClass", r.get(PROPSVIEW.STANDARDCLASS)); classmap.put("customClass", r.get(PROPSVIEW.MAPPEDCLASS)); classmap.put("typeAbrv", r.get(TYPES.ABRV)); pageData.put(r.get(PROPSVIEW.CONTROLNAME), classmap); } return pageData; } public static List<Object> getPageGuiMapData2(String webPage) { Object obj1 = getPageGuiMapData(webPage); Object obj2 = getPageGuiPropertyData(webPage); return Arrays.asList(obj1, obj2); } public static Map<String, Object> getPageGuiPropertyData(String webPage) { Map<String, Object> pageData = new LinkedHashMap<String, Object>(); SelectConditionStep<Record16<Integer, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String>> selectProperties = DbManager .getOpenContext() .select(PROPWRITERVIEW.GUIMAPID, PROPWRITERVIEW.ABRV, PROPWRITERVIEW.CONTROLNAME, PROPWRITERVIEW.CONTROLDESCRIPTION, PROPWRITERVIEW.LOCATORTYPE, PROPWRITERVIEW.LOCATORVALUE, PROPWRITERVIEW.MAPPEDCLASS, PROPWRITERVIEW.EXPROP1, PROPWRITERVIEW.EXPROP2, PROPWRITERVIEW.EXPROP3, PROPWRITERVIEW.EXPROP4, PROPWRITERVIEW.EXPROP5, PROPWRITERVIEW.EXPROP6, PROPWRITERVIEW.EXPROP7, PROPWRITERVIEW.EXPROP8, PROPWRITERVIEW.EXPROP9) .from(PROPWRITERVIEW).where(PROPWRITERVIEW.PAGENAME.equal(webPage)); Result<Record2<String, String>> result = DbManager.getOpenContext().select(TYPES.CLASS, TYPES.PROPERTYMAP) .from(TYPES).where(TYPES.HASEXTENDEDPROPS.isTrue()).fetch(); Map<String, List<String>> xPropertyMap = result.intoGroups(TYPES.CLASS, TYPES.PROPERTYMAP); for (Record r : selectProperties.fetch()) { HashMap<String, String> exmap = null; if (r.get(PROPWRITERVIEW.MAPPEDCLASS) != null && !r.get(PROPWRITERVIEW.MAPPEDCLASS).equalsIgnoreCase("(No Maping)")) { String jSon = xPropertyMap.get(r.get(PROPWRITERVIEW.MAPPEDCLASS)).get(0); exmap = new Gson().fromJson(jSon, new TypeToken<HashMap<String, String>>() { }.getType()); } LinkedHashMap<String, Object> propertyMap = new LinkedHashMap<String, Object>(); propertyMap.put("CONTROLDESCRIPTION", r.get(PROPSVIEW.CONTROLDESCRIPTION)); propertyMap.put("LOCATORTYPE", r.get(PROPSVIEW.LOCATORTYPE)); propertyMap.put("LOCATORVALUE", r.get(PROPSVIEW.LOCATORVALUE)); if (exmap != null) { for (String xf : exmap.keySet()) { propertyMap.put(exmap.get(xf), r.get(xf)); } } propertyMap.put("LOCATORVALUE", r.get(PROPSVIEW.LOCATORVALUE)); Object o = (Object) propertyMap; pageData.put(r.get(PROPWRITERVIEW.ABRV) + r.get(PROPWRITERVIEW.CONTROLNAME).toString(), o); } return pageData; } public static String getClassAbrv(String string) { Record1<String> r = DbManager.getOpenContext().select(TYPES.ABRV).from(TYPES).where(TYPES.CLASS.equal(string)) .fetchOne(); return r.get(TYPES.ABRV); } public static List<HashMap<String, String>> getPageHeirarchy(Integer... pageId) { List<HashMap<String, String>> returnList = new ArrayList<HashMap<String, String>>(); Select<?> selectStatement = null; if (pageId.length == 0) selectStatement = DbManager.getOpenContext().select(PAGES.PAGEID, PAGES.PARENTID).from(PAGES) .where(PAGES.PARENTID.isNull()); else selectStatement = DbManager.getOpenContext().select(PAGES.PAGEID, PAGES.PARENTID).from(PAGES) .where(PAGES.PARENTID.in(pageId)); HashMap<String, String> pageHeirarchy = new HashMap<String, String>(); for (Record r : selectStatement.fetch()) { Integer pId = r.get(PAGES.PAGEID); Integer prId = r.get(PAGES.PARENTID); String pageName = DbManager.getOpenContext().select(PAGES.PAGENAME).from(PAGES).where(PAGES.PAGEID.eq(pId)) .fetchOne().get(PAGES.PAGENAME); Record1<String> s = DbManager.getOpenContext().select(PAGES.PAGENAME).from(PAGES) .where(PAGES.PAGEID.eq(prId)).fetchOne(); String parentName = (s == null) ? null : s.get(PAGES.PAGENAME); pageHeirarchy.put(pageName, parentName); } returnList.add(pageHeirarchy); List<Integer> a = selectStatement.fetch().getValues(PAGES.PAGEID, Integer.class); if (a.size() > 0) { Integer list2[] = new Integer[a.size()]; returnList.addAll(getPageHeirarchy((Integer[]) a.toArray(list2))); } return returnList; } public static Object getTableData(String tableName) { SelectWhereStep<?> pages = DbManager.getOpenContext().selectFrom(AUTOMATION.getTable(tableName.toUpperCase())); List<Object> returnList = new ArrayList<Object>(); Result<?> result = pages.fetch(); List<Object> fields = new ArrayList<Object>(); for (Field<?> f : result.fields()) { fields.add(f.getName()); } returnList.add(fields); for (Record r : result) { List<Object> values = new ArrayList<Object>(); for (Object f : fields) { values.add(r.get((String) f)); } returnList.add(values); } return returnList; } }
40.505556
190
0.693092
cb01612d7686d4fae88572b4d5dc4bcae285ca11
952
/** * Copyright 2015 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package wherehows.converters; import org.apache.avro.generic.IndexedRecord; /** * Interface for Kafka message converter. */ public interface KafkaMessageConverter<T extends IndexedRecord> { /** * Method 'convert' to be implemented by specific converter. * Input one kafka message, output one converted kafka message. * * @param indexedRecord IndexedRecord * @return IndexedRecord */ T convert(T indexedRecord); }
28.848485
75
0.733193
01a94f39742bcaa0b61849e00f9810835d36df37
2,737
package it.denv.supsi.i3b.advalg.algorithms.TSP.ra.intermediate.genetic.eax; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Optional; public class ABCycle { private List<ABEdge> path; public ABCycle(){ path = new ArrayList<>(); } public ABCycle(List<ABEdge> edgeList){ this.path = edgeList; } public List<ABEdge> getPath() { return path; } public void add(ABEdge e){ path.add(e); } public boolean contains(ABEdge e){ return path.contains(e); } public void addAll(List<ABEdge> l){ this.path.addAll(l); } public static ABCycle getCycle(List<ABEdge> edges) { for(int i=0; i<edges.size(); i++) { int startCity = edges.get(i).getU(); for(int j=i; j<edges.size(); j++){ if(edges.get(j).getV() == startCity){ return new ABCycle(edges.subList(i,j+1)); } } } return null; } public static List<ABCycle> getSubtours(List<ABEdge> edgesArray, HashMap<Integer, ArrayList<ABEdge>> edges) { if(edges.size() == 0){ return null; } List<ABCycle> cycles = new ArrayList<>(); while(edgesArray.size() > 0){ // Select the first city ArrayList<ABEdge> mEdges = new ArrayList<>(); ABEdge firstEdge = edgesArray.get(0); int firstCity = firstEdge.getU(); int currentCity = firstEdge.getV(); mEdges.add(firstEdge); edges.get(firstEdge.getU()).remove(firstEdge); edges.get(firstEdge.getV()).remove(firstEdge); edgesArray.remove(firstEdge); while(currentCity != firstCity){ ArrayList<ABEdge> edgesAtCity = edges.get(currentCity); if(edgesAtCity == null){ throw new RuntimeException("No edge starts at" + currentCity); } Optional<ABEdge> nextEdge = edgesAtCity.stream().findAny(); if(nextEdge.isEmpty()){ System.out.println(mEdges); throw new RuntimeException("Invalid E-Set!"); } ABEdge nextEdgeV = nextEdge.get(); if(nextEdgeV.getV() == currentCity){ nextEdgeV = ABEdge.getInverted(nextEdgeV); } currentCity = nextEdgeV.getV(); edges.get(nextEdgeV.getU()).remove(nextEdgeV); edges.get(nextEdgeV.getV()).remove(nextEdgeV); edgesArray.remove(nextEdgeV); mEdges.add(nextEdgeV); } cycles.add(new ABCycle(mEdges)); } return cycles; } public List<ABCycle> intoSubtours() { HashMap<Integer, ArrayList<ABEdge>> nextNodes = new HashMap<>(); for(ABEdge e : path){ if(!nextNodes.containsKey(e.getU())){ nextNodes.put(e.getU(), new ArrayList<>()); } if(!nextNodes.containsKey(e.getV())){ nextNodes.put(e.getV(), new ArrayList<>()); } nextNodes.get(e.getU()).add(e); nextNodes.get(e.getV()).add(e); } return getSubtours(new ArrayList<>(path), nextNodes); } }
22.252033
76
0.655828
6d5727eda793bfa1eb4fb6d61dd6e556d2a626cb
426
package hello; /** * @author: liangcan * @version: 1.0 * @date: 2018/12/7 10:35 * @describtion: Greeting */ public class Greeting { private final long id; private final String content; public Greeting(long id, String content) { this.id = id; this.content = content; } public long getId() { return id; } public String getContent() { return content; } }
15.777778
46
0.58216
dca79b997703a545fe97adbb45aea45e90a82b3a
1,056
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: IGDBProtoFile.proto package proto; public interface PlatformWebsiteResultOrBuilder extends // @@protoc_insertion_point(interface_extends:proto.PlatformWebsiteResult) com.google.protobuf.MessageOrBuilder { /** * <code>repeated .proto.PlatformWebsite platformwebsites = 1;</code> */ java.util.List<proto.PlatformWebsite> getPlatformwebsitesList(); /** * <code>repeated .proto.PlatformWebsite platformwebsites = 1;</code> */ proto.PlatformWebsite getPlatformwebsites(int index); /** * <code>repeated .proto.PlatformWebsite platformwebsites = 1;</code> */ int getPlatformwebsitesCount(); /** * <code>repeated .proto.PlatformWebsite platformwebsites = 1;</code> */ java.util.List<? extends proto.PlatformWebsiteOrBuilder> getPlatformwebsitesOrBuilderList(); /** * <code>repeated .proto.PlatformWebsite platformwebsites = 1;</code> */ proto.PlatformWebsiteOrBuilder getPlatformwebsitesOrBuilder( int index); }
31.058824
78
0.729167
2e69b79c43dd656b0cbc127bbd71f7bbc43c4d5d
3,681
package com.alipay.android.phone.mrpc.core; import android.text.format.Time; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class k { private static final Pattern a = Pattern.compile("([0-9]{1,2})[- ]([A-Za-z]{3,9})[- ]([0-9]{2,4})[ ]([0-9]{1,2}:[0-9][0-9]:[0-9][0-9])"); private static final Pattern b = Pattern.compile("[ ]([A-Za-z]{3,9})[ ]+([0-9]{1,2})[ ]([0-9]{1,2}:[0-9][0-9]:[0-9][0-9])[ ]([0-9]{2,4})"); private static class a { int a; int b; int c; a(int i, int i2, int i3) { this.a = i; this.b = i2; this.c = i3; } } public static long a(String str) { int c; int d; a e; int i; int i2 = 1; Matcher matcher = a.matcher(str); int b; if (matcher.find()) { b = b(matcher.group(1)); c = c(matcher.group(2)); d = d(matcher.group(3)); e = e(matcher.group(4)); i = b; } else { Matcher matcher2 = b.matcher(str); if (matcher2.find()) { c = c(matcher2.group(1)); b = b(matcher2.group(2)); a e2 = e(matcher2.group(3)); d = d(matcher2.group(4)); e = e2; i = b; } else { throw new IllegalArgumentException(); } } if (d >= 2038) { d = 2038; c = 0; } else { i2 = i; } Time time = new Time("UTC"); time.set(e.c, e.b, e.a, i2, c, d); return time.toMillis(false); } private static int b(String str) { return str.length() == 2 ? ((str.charAt(0) - 48) * 10) + (str.charAt(1) - 48) : str.charAt(0) - 48; } private static int c(String str) { switch (((Character.toLowerCase(str.charAt(0)) + Character.toLowerCase(str.charAt(1))) + Character.toLowerCase(str.charAt(2))) - 291) { case 9: return 11; case 10: return 1; case 22: return 0; case 26: return 7; case 29: return 2; case 32: return 3; case 35: return 9; case 36: return 4; case 37: return 8; case 40: return 6; case 42: return 5; case 48: return 10; default: throw new IllegalArgumentException(); } } private static int d(String str) { if (str.length() != 2) { return str.length() == 3 ? ((((str.charAt(0) - 48) * 100) + ((str.charAt(1) - 48) * 10)) + (str.charAt(2) - 48)) + 1900 : str.length() == 4 ? ((((str.charAt(0) - 48) * 1000) + ((str.charAt(1) - 48) * 100)) + ((str.charAt(2) - 48) * 10)) + (str.charAt(3) - 48) : 1970; } else { int charAt = ((str.charAt(0) - 48) * 10) + (str.charAt(1) - 48); return charAt >= 70 ? charAt + 1900 : charAt + 2000; } } private static a e(String str) { int i; int charAt = str.charAt(0) - 48; if (str.charAt(1) != ':') { i = 2; charAt = (charAt * 10) + (str.charAt(1) - 48); } else { i = 1; } i++; int i2 = i + 1; i = ((str.charAt(i) - 48) * 10) + (str.charAt(i2) - 48); i2 = (i2 + 1) + 1; return new a(charAt, i, ((str.charAt(i2) - 48) * 10) + (str.charAt(i2 + 1) - 48)); } }
30.421488
279
0.41755
6044e7be94dd2e5e1b73c943df99766b9f218c21
2,353
package no.fint.consumer.models.korrespondanseparttype; import no.fint.model.resource.Link; import no.fint.model.resource.administrasjon.arkiv.KorrespondansepartTypeResource; import no.fint.model.resource.administrasjon.arkiv.KorrespondansepartTypeResources; import no.fint.relations.FintLinker; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.Objects.isNull; import static org.springframework.util.StringUtils.isEmpty; @Component public class KorrespondansepartTypeLinker extends FintLinker<KorrespondansepartTypeResource> { public KorrespondansepartTypeLinker() { super(KorrespondansepartTypeResource.class); } public void mapLinks(KorrespondansepartTypeResource resource) { super.mapLinks(resource); } @Override public KorrespondansepartTypeResources toResources(Collection<KorrespondansepartTypeResource> collection) { KorrespondansepartTypeResources resources = new KorrespondansepartTypeResources(); collection.stream().map(this::toResource).forEach(resources::addResource); resources.addSelf(Link.with(self())); return resources; } @Override public String getSelfHref(KorrespondansepartTypeResource korrespondanseparttype) { return getAllSelfHrefs(korrespondanseparttype).findFirst().orElse(null); } @Override public Stream<String> getAllSelfHrefs(KorrespondansepartTypeResource korrespondanseparttype) { Stream.Builder<String> builder = Stream.builder(); if (!isNull(korrespondanseparttype.getSystemId()) && !isEmpty(korrespondanseparttype.getSystemId().getIdentifikatorverdi())) { builder.add(createHrefWithId(korrespondanseparttype.getSystemId().getIdentifikatorverdi(), "systemid")); } return builder.build(); } int[] hashCodes(KorrespondansepartTypeResource korrespondanseparttype) { IntStream.Builder builder = IntStream.builder(); if (!isNull(korrespondanseparttype.getSystemId()) && !isEmpty(korrespondanseparttype.getSystemId().getIdentifikatorverdi())) { builder.add(korrespondanseparttype.getSystemId().getIdentifikatorverdi().hashCode()); } return builder.build().toArray(); } }
38.57377
134
0.756906
515ff77f9d9569adfcbb683c698c870d67c21efe
3,122
package kaptainwutax.playback.replay.capture; import kaptainwutax.playback.gui.WindowSize; import kaptainwutax.playback.replay.action.PacketAction; import kaptainwutax.playback.replay.action.WindowFocusAction; import kaptainwutax.playback.replay.action.WindowSizeAction; import kaptainwutax.playback.util.PlaybackSerializable; import net.minecraft.client.MinecraftClient; import net.minecraft.client.options.GameOptions; import net.minecraft.network.Packet; import net.minecraft.network.listener.ClientPlayPacketListener; import net.minecraft.network.packet.s2c.play.GameJoinS2CPacket; import net.minecraft.util.PacketByteBuf; import java.io.IOException; public class StartState implements PlaybackSerializable { private PacketAction joinPacket = new PacketAction(); private int perspective; private int isSinglePlayer = -1; private WindowFocusAction windowFocus = new WindowFocusAction(true); private String gameOptions; private WindowSizeAction windowSizeAction; public StartState() {} public void addPerspective(int perspective) { this.perspective = perspective; } public void addJoinPacket(Packet<ClientPlayPacketListener> packet) { this.joinPacket = new PacketAction(packet); } public void addPhysicalSide(boolean isSinglePlayer) { this.isSinglePlayer = isSinglePlayer ? 1 : 0; } public void addWindowFocus(boolean windowFocus) { this.windowFocus = new WindowFocusAction(windowFocus); } public void addWindowSize(WindowSize windowSize) { this.windowSizeAction = new WindowSizeAction(windowSize, false); } public void addGameOptions(GameOptions options) { this.gameOptions = PlayGameOptions.getContents(options); } public void play() { MinecraftClient.getInstance().options.perspective = this.perspective; this.windowFocus.play(); PlayGameOptions.loadContents(MinecraftClient.getInstance().options, this.gameOptions); this.windowSizeAction.play(); } @Override public void read(PacketByteBuf buf) throws IOException { this.perspective = buf.readVarInt(); this.isSinglePlayer = buf.readBoolean() ? 1 : 0; this.joinPacket.read(buf); this.windowFocus = new WindowFocusAction(true); this.windowFocus.read(buf); this.gameOptions = buf.readString(); this.windowSizeAction = new WindowSizeAction(); this.windowSizeAction.read(buf); } @Override public void write(PacketByteBuf buf) throws IOException { buf.writeVarInt(this.perspective); buf.writeBoolean(this.isSinglePlayer()); this.joinPacket.write(buf); this.windowFocus.write(buf); buf.writeString(this.gameOptions); this.windowSizeAction.write(buf); } public int getPerspective() { return this.perspective; } public PacketAction getJoinPacketAction() { return this.joinPacket; } public boolean isSinglePlayer() { if (this.isSinglePlayer == -1) { System.err.println("Accessing non-initialized isSinglePlayer!"); } return this.isSinglePlayer == 1; } public GameJoinS2CPacket getJoinPacket() { return joinPacket == null ? null : (GameJoinS2CPacket) joinPacket.getPacket(); } public boolean getWindowFocus() { return this.windowFocus.getFocus(); } }
30.31068
88
0.783152
6c78c812431c2b59a3392bd251788f65a5100058
2,604
package org.inferred.freebuilder.processor; import static org.inferred.freebuilder.processor.util.ModelUtils.findAnnotationMirror; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import org.inferred.freebuilder.processor.Metadata.Property; import org.inferred.freebuilder.processor.util.Excerpts; import org.inferred.freebuilder.processor.util.QualifiedName; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; class JacksonSupport { private static final String JSON_DESERIALIZE = "com.fasterxml.jackson.databind.annotation.JsonDeserialize"; private static final QualifiedName JSON_PROPERTY = QualifiedName.of("com.fasterxml.jackson.annotation", "JsonProperty"); /** Annotations which disable automatic generation of JsonProperty annotations. */ private static final Set<QualifiedName> DISABLE_PROPERTY_ANNOTATIONS = ImmutableSet.of( QualifiedName.of("com.fasterxml.jackson.annotation", "JsonAnyGetter"), QualifiedName.of("com.fasterxml.jackson.annotation", "JsonIgnore"), QualifiedName.of("com.fasterxml.jackson.annotation", "JsonUnwrapped"), QualifiedName.of("com.fasterxml.jackson.annotation", "JsonValue")); public static Optional<JacksonSupport> create(TypeElement userValueType) { if (findAnnotationMirror(userValueType, JSON_DESERIALIZE).isPresent()) { return Optional.of(new JacksonSupport()); } return Optional.absent(); } private JacksonSupport() {} public void addJacksonAnnotations( Property.Builder resultBuilder, ExecutableElement getterMethod) { Optional<AnnotationMirror> annotation = findAnnotationMirror(getterMethod, JSON_PROPERTY); if (annotation.isPresent()) { resultBuilder.addAccessorAnnotations(Excerpts.add("%s%n", annotation.get())); } else if (generateDefaultAnnotations(getterMethod)) { resultBuilder.addAccessorAnnotations(Excerpts.add( "@%s(\"%s\")%n", JSON_PROPERTY, resultBuilder.getName())); } } private static boolean generateDefaultAnnotations(ExecutableElement getterMethod) { for (AnnotationMirror annotationMirror : getterMethod.getAnnotationMirrors()) { TypeElement annotationTypeElement = (TypeElement) (annotationMirror.getAnnotationType().asElement()); QualifiedName annotationType = QualifiedName.of(annotationTypeElement); if (DISABLE_PROPERTY_ANNOTATIONS.contains(annotationType)) { return false; } } return true; } }
40.6875
94
0.766897
10747cde160824a6d8dc0c78e0d40a8c347a1569
1,048
package xyz.arkarhein.news.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import xyz.arkarhein.news.R; import xyz.arkarhein.news.viewholders.ItemSportsNewsViewHolder; /** * Created by Arkar Hein on 1/12/2018. */ public class SportsNewsAdapter extends RecyclerView.Adapter { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View sportsNewsView = inflater.inflate(R.layout.items_sports_news, parent, false); ItemSportsNewsViewHolder itemSportsNewsViewHolder = new ItemSportsNewsViewHolder(sportsNewsView); return itemSportsNewsViewHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { } @Override public int getItemCount() { return 6; } }
29.111111
105
0.753817
59bfe60b8f792acdd7ad2f64f04eb7364b6bf093
1,859
package sarf.verb.quadriliteral.unaugmented.passive; import java.util.*; import com.google.inject.Inject; import sarf.*; import sarf.verb.quadriliteral.unaugmented.*; /** * <p>Title: Sarf</p> * * <p>Description: تصريف الأفعال الرباعية المجردة في صيغة الماضي المبني للمجهول </p> * * <p>Copyright: Copyright (c) 2006</p> * * <p>Company: </p> * * @author Haytham Mohtasseb Billah * @version 1.0 */ public class QuadriUnaugmentedPassivePastConjugator { private final PastConjugationDataContainer pastConjugationDataContainer; @Inject public QuadriUnaugmentedPassivePastConjugator(PastConjugationDataContainer pastConjugationDataContainer) { this.pastConjugationDataContainer = pastConjugationDataContainer; } /** * إنشاء الفعل حسب الضمير * @param pronounIndex int * @param root TripleVerb * @return PassivePastVerb */ private PassivePastVerb createVerb(int pronounIndex, UnaugmentedQuadrilateralRoot root) { // اظهار مع هو وهي فقط للمجهول اللازم if (root.getTransitive().equals("ل") && pronounIndex != 7 && pronounIndex != 8) { return null; } String lastDpa = pastConjugationDataContainer.getLastDpa(pronounIndex); String connectedPronoun = pastConjugationDataContainer.getConnectedPronoun(pronounIndex); return new PassivePastVerb(root, lastDpa, connectedPronoun); } /** * إنشاء قائمة تحتوي الأفعال مع الضمائر الثلاثة عشر * @param root TripleVerb * @return List */ public List<PassivePastVerb> createVerbList(UnaugmentedQuadrilateralRoot root) { List<PassivePastVerb> result = new ArrayList<>(); for (int i = 0; i < 13; i++) { result.add(createVerb(i, root)); } return result; } }
31.508475
111
0.663798
0b6d9d883248d550a57267edfa28ce316368fd21
1,100
/* * TestMap.java * chap16 * * .'' * ._.-.___.' (`\ * //( ( `' * '/ )\ ).__. ) * ' <' `\ ._/'\ * ` \ \ * * Created by Chyi Yaqing on 06/05/19 10:27. * Copyright (C) 2019. Chyi Yaqing. * All rights reserved. * * Distributed under terms of the MIT license. */ import java.util.*; public class TestMap { public static void main(String[] args) { // HashMap needs two type parameters one for the key and one for the value. HashMap<String, Integer> scores = new HashMap<String, Integer>(); // Use put() instead of add(), and now of course it takes two arguments (key, value) scores.put("Kathy", 42); scores.put("Bert", 343); scores.put("Skyler", 420); // When you print a Map, it gives you the key=value, in braces{} // instead of the brackets [] you see when you print lists and sets System.out.println(scores); // The get() method takes a key, and returns the value (in this case, and Integer) System.out.println(scores.get("Bert")); } }
26.829268
92
0.559091
413255aa501f1218c9973c62534354ea8c58da3a
892
package us.kbase.common.service; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; public class Tuple1 <T1> { private T1 e1; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); public T1 getE1() { return e1; } public void setE1(T1 e1) { this.e1 = e1; } public Tuple1<T1> withE1(T1 e1) { this.e1 = e1; return this; } @Override public String toString() { return "Tuple1 [e1=" + e1 + "]"; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperties(String name, Object value) { this.additionalProperties.put(name, value); } }
22.3
85
0.649103
978be53b4e712fbf64e423a820cabd972f4a0877
93
package statListeners; public interface DefenseListener { public int getDefenseBonus(); }
13.285714
33
0.795699
d5a4fd8685dcc38e291b77d3346ff7b1d053f077
2,627
import vtk.vtkActor; import vtk.vtkCellArray; import vtk.vtkNamedColors; import vtk.vtkNativeLibrary; import vtk.vtkPoints; import vtk.vtkPolyData; import vtk.vtkPolyDataMapper; import vtk.vtkPolygon; import vtk.vtkRenderWindow; import vtk.vtkRenderWindowInteractor; import vtk.vtkRenderer; public class Polygon { // ----------------------------------------------------------------- // Load VTK library and print which library was not properly loaded static { if (!vtkNativeLibrary.LoadAllNativeLibraries()) { for (vtkNativeLibrary lib : vtkNativeLibrary.values()) { if (!lib.IsLoaded()) { System.out.println(lib.GetLibraryName() + " not loaded"); } } } vtkNativeLibrary.DisableOutputWindow(null); } // ----------------------------------------------------------------- public static void main(String s[]) { vtkNamedColors colors = new vtkNamedColors(); //For Actor Color double actorColor[] = new double[4]; //Renderer Background Color double Bgcolor[] = new double[4]; colors.GetColor("Red", actorColor); colors.GetColor("White", Bgcolor); vtkPoints Points = new vtkPoints(); Points.InsertNextPoint(0.0,0.0,0.0); Points.InsertNextPoint(1.0,0.0,0.0); Points.InsertNextPoint(1.0,1.0,0.0); Points.InsertNextPoint(0.0,1.0,0.0); vtkPolygon Polygon = new vtkPolygon(); Polygon.GetPointIds().SetNumberOfIds(4); Polygon.GetPointIds().SetId(0, 0); Polygon.GetPointIds().SetId(1, 1); Polygon.GetPointIds().SetId(2, 2); Polygon.GetPointIds().SetId(3, 3); vtkCellArray Polygons = new vtkCellArray(); Polygons.InsertNextCell(Polygon); vtkPolyData PolygonPolyData = new vtkPolyData(); PolygonPolyData.SetPoints(Points); PolygonPolyData.SetPolys(Polygons); //Create a Mapper and Actor vtkPolyDataMapper Mapper = new vtkPolyDataMapper(); Mapper.SetInputData(PolygonPolyData); vtkActor Actor = new vtkActor(); Actor.SetMapper(Mapper); Actor.GetProperty().SetColor(actorColor); Actor.GetProperty().SetLineWidth(5); //Create the renderer, render window and interactor. vtkRenderer ren = new vtkRenderer(); vtkRenderWindow renWin = new vtkRenderWindow(); renWin.AddRenderer(ren); vtkRenderWindowInteractor iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow(renWin); // Visualise the arrow ren.AddActor(Actor); ren.SetBackground(Bgcolor); renWin.SetSize(300, 300); renWin.Render(); iren.Initialize(); iren.Start(); } }
26.27
71
0.644461
da9e249e514f77cbab4beb2e98bbc3306b3db3ff
71
package com.examplehub.basics.io; public class StringReaderExample {}
17.75
35
0.816901
fff68ecd2398f2c768953a3e0456de59dbcbea4d
651
package com.kirago.chapter16; import com.kirago.chapter16.config.TaskSchedulerConfig; import com.kirago.chapter16.service.SchedulerdTaskService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @SpringBootApplication public class Chapter16Application { public static void main(String[] args) { // SpringApplication.run(Chapter16Application.class, args); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class); } }
34.263158
119
0.831029
b3d3a1bcb584fd1c8e27313b2169d4b64bd1e7ba
13,679
/* * Copyright 2014-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ package org.springframework.integration.test.mail; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.net.ServerSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.Base64Utils; /** * A basic test mail server for pop3, imap, * Serves up a canned email message with each protocol. * For smtp, it handles the basic handshaking and captures * the pertinent data so it can be verified by a test case. * * @author Gary Russell * @author Artem Bilan * * @since 5.0 * */ public final class TestMailServer { public static SmtpServer smtp(int port) { try { return new SmtpServer(port); } catch (IOException e) { throw new IllegalStateException(e); } } public static Pop3Server pop3(int port) { try { return new Pop3Server(port); } catch (IOException e) { throw new IllegalStateException(e); } } public static ImapServer imap(int port) { try { return new ImapServer(port); } catch (IOException e) { throw new IllegalStateException(e); } } public static class SmtpServer extends MailServer { SmtpServer(int port) throws IOException { super(port); } @Override protected MailHandler mailHandler(Socket socket) { return new SmtpHandler(socket); } class SmtpHandler extends MailHandler { SmtpHandler(Socket socket) { super(socket); } @Override // NOSONAR void doRun() { // NOSONAR try { write("220 foo SMTP"); while (!socket.isClosed()) { String line = reader.readLine(); if (line == null) { break; } if (line.contains("EHLO")) { write("250-foo hello [0,0,0,0], foo"); write("250-AUTH LOGIN PLAIN"); write("250 OK"); } else if (line.contains("MAIL FROM")) { write("250 OK"); } else if (line.contains("RCPT TO")) { write("250 OK"); } else if (line.contains("AUTH LOGIN")) { write("334 VXNlcm5hbWU6"); } else if (line.contains("dXNlcg==")) { // base64 'user' sb.append("user:"); sb.append((new String(Base64Utils.decode(line.getBytes())))); sb.append("\n"); write("334 UGFzc3dvcmQ6"); } else if (line.contains("cHc=")) { // base64 'pw' sb.append("password:"); sb.append((new String(Base64Utils.decode(line.getBytes())))); sb.append("\n"); write("235"); } else if (line.equals("DATA")) { write("354"); } else if (line.equals(".")) { write("250"); } else if (line.equals("QUIT")) { write("221"); socket.close(); } else { sb.append(line); sb.append("\n"); } } messages.add(sb.toString()); } catch (IOException e) { if (!this.stopped) { LOGGER.error(IO_EXCEPTION, e); } } } } } public static class Pop3Server extends MailServer { Pop3Server(int port) throws IOException { super(port); } @Override protected MailHandler mailHandler(Socket socket) { return new Pop3Handler(socket); } class Pop3Handler extends MailHandler { private static final String PLUS_OK = "+OK"; Pop3Handler(Socket socket) { super(socket); } @Override // NOSONAR void doRun() { try { write("+OK POP3"); while (!socket.isClosed()) { String line = reader.readLine(); if (line == null) { break; } switch (line) { case "CAPA": write(PLUS_OK); write("USER"); write("."); break; case "USER user": case "PASS pw": case "NOOP": write(PLUS_OK); break; case "STAT": write("+OK 1 3"); break; case "RETR 1": write(PLUS_OK); write(MESSAGE); write("."); break; case "QUIT": write(PLUS_OK); socket.close(); break; default: throw new UnsupportedOperationException(line); } } } catch (IOException e) { if (!this.stopped) { LOGGER.error(IO_EXCEPTION, e); } } } } } public static class ImapServer extends MailServer { private volatile boolean seen; private volatile boolean idled; ImapServer(int port) throws IOException { super(port); } @Override public void resetServer() { super.resetServer(); this.seen = false; this.idled = false; } @Override protected MailHandler mailHandler(Socket socket) { return new ImapHandler(socket); } class ImapHandler extends MailHandler { private static final String OK_FETCH_COMPLETED = "OK FETCH completed"; /** * Time to wait while IDLE before returning a result. */ private static final int IDLE_WAIT_TIME = 500; ImapHandler(Socket socket) { super(socket); } @Override // NOSONAR void doRun() { try { write("* OK IMAP4rev1 Service Ready"); String idleTag = ""; while (!socket.isClosed()) { String line = reader.readLine(); if (line == null) { break; } String tag = line.substring(0, line.indexOf(' ') + 1); if (line.endsWith("CAPABILITY")) { write("* CAPABILITY IDLE IMAP4rev1"); write(tag + "OK CAPABILITY completed"); } else if (line.endsWith("LOGIN user pw")) { write(tag + "OK LOGIN completed"); } else if (line.endsWith("LIST \"\" INBOX")) { write("* LIST \"/\" \"INBOX\""); write(tag + "OK LIST completed"); } else if (line.endsWith("LIST \"\" \"\"")) { write("* LIST \"/\" \"\""); write(tag + "OK LIST completed"); } else if (line.endsWith("SELECT INBOX")) { write("* 1 EXISTS"); if (!seen) { write("* 1 RECENT"); write("* OK [UNSEEN 1]"); } else { write("* OK"); } write("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\*)]"); // \* - user flags allowed write(tag + "OK SELECT completed"); } else if (line.endsWith("EXAMINE INBOX")) { write(tag + "OK"); } else if (line.endsWith("SEARCH FROM bar@baz UNSEEN ALL")) { searchReply(tag); } else if (line.endsWith("SEARCH NOT (DELETED) NOT (SEEN) NOT (KEYWORD testSIUserFlag) ALL")) { searchReply(tag); assertions.add("searchWithUserFlag"); } else if (line.contains("FETCH 1 (ENVELOPE")) { write("* 1 FETCH (RFC822.SIZE " + MESSAGE.length() + " INTERNALDATE \"27-May-2013 09:45:41 +0000\" " + "FLAGS (\\Seen) " + "ENVELOPE (\"Mon, 27 May 2013 15:14:49 +0530\" " + "\"Test Email\" " + "((\"Bar\" NIL \"bar\" \"baz\")) " // From + "((\"Bar\" NIL \"bar\" \"baz\")) " // Sender + "((\"Bar\" NIL \"bar\" \"baz\")) " // Reply To + "((\"Foo\" NIL \"foo\" \"bar\")) " // To + "((NIL NIL \"a\" \"b\") (NIL NIL \"c\" \"d\")) " // cc + "((NIL NIL \"e\" \"f\") (NIL NIL \"g\" \"h\")) " // bcc + "\"<[email protected]>\" " // In reply to + "\"<[email protected]>\") " // msgid + "BODYSTRUCTURE " + "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"ISO-8859-1\") NIL NIL \"7BIT\" 1 5)))"); write(tag + OK_FETCH_COMPLETED); } else if (line.contains("FETCH 2 (BODYSTRUCTURE)")) { write("* 2 FETCH " + "BODYSTRUCTURE " + "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"ISO-8859-1\") NIL NIL \"7BIT\" 1 5)))"); write(tag + OK_FETCH_COMPLETED); } else if (line.contains("STORE 1 +FLAGS (\\Flagged)")) { write("* 1 FETCH (FLAGS (\\Flagged))"); write(tag + "OK STORE completed"); } else if (line.contains("STORE 1 +FLAGS (\\Seen)")) { write("* 1 FETCH (FLAGS (\\Flagged \\Seen))"); write(tag + "OK STORE completed"); seen = true; } else if (line.contains("FETCH 1 FLAGS")) { write("* 1 FLAGS(\\Seen)"); write(tag + OK_FETCH_COMPLETED); } else if (line.contains("FETCH 1 (BODY.PEEK")) { write("* 1 FETCH (BODY[]<0> {" + (MESSAGE.length() + 2) + "}"); write(MESSAGE); write(")"); write(tag + OK_FETCH_COMPLETED); } else if (line.contains("CLOSE")) { write(tag + "OK CLOSE completed"); } else if (line.contains("NOOP")) { write(tag + "OK NOOP completed"); } else if (line.endsWith("STORE 1 +FLAGS (testSIUserFlag)")) { write(tag + "OK STORE completed"); assertions.add("storeUserFlag"); } else if (line.endsWith("IDLE")) { write("+ idling"); idleTag = tag; if (!idled) { try { Thread.sleep(IDLE_WAIT_TIME); write("* 2 EXISTS"); seen = false; } catch (@SuppressWarnings("unused") InterruptedException e) { Thread.currentThread().interrupt(); } } idled = true; } else if (line.equals("DONE")) { write(idleTag + "OK"); } else if (line.contains("LOGOUT")) { write(tag + "OK LOGOUT completed"); this.socket.close(); } } } catch (IOException e) { if (!this.stopped) { LOGGER.error(IO_EXCEPTION, e); } } } void searchReply(String tag) throws IOException { if (seen) { write("* SEARCH"); } else { write("* SEARCH 1"); } write(tag + "OK SEARCH completed"); } } } public abstract static class MailServer implements Runnable { protected final Log LOGGER = LogFactory.getLog(getClass()); // NOSONAR protected static final String IO_EXCEPTION = "IOException"; // NOSONAR private final ServerSocket serverSocket; private final ExecutorService exec = Executors.newCachedThreadPool(); protected final Set<String> assertions = new HashSet<>(); // NOSONAR protected protected final List<String> messages = new ArrayList<>(); // NOSONAR protected private final List<MailHandler> handlers = new ArrayList<>(); private volatile boolean listening; MailServer(int port) throws IOException { this.serverSocket = ServerSocketFactory.getDefault().createServerSocket(port); this.listening = true; exec.execute(this); } public int getPort() { return this.serverSocket.getLocalPort(); } public boolean isListening() { return listening; } public List<String> getMessages() { return messages; } public void resetServer() { this.assertions.clear(); } public boolean assertReceived(String assertion) { return this.assertions.contains(assertion); } @Override public void run() { try { while (!serverSocket.isClosed()) { Socket socket = this.serverSocket.accept(); MailHandler mailHandler = mailHandler(socket); this.handlers.add(mailHandler); exec.execute(mailHandler); } } catch (@SuppressWarnings("unused") IOException e) { this.listening = false; } } protected abstract MailHandler mailHandler(Socket socket); public void stop() { try { for (MailHandler handler : this.handlers) { handler.stop(); } this.serverSocket.close(); } catch (IOException e) { LOGGER.error(IO_EXCEPTION, e); } this.exec.shutdownNow(); } public abstract class MailHandler implements Runnable { public static final String BODY = "foo\r\n"; public static final String MESSAGE = "To: Foo <foo@bar>\r\n" + "cc: a@b, c@d\r\n" + "bcc: e@f, g@h\r\n" + "From: Bar <bar@baz>, Bar2 <bar2@baz>\r\n" + "Subject: Test Email\r\n" + "\r\n" + BODY; protected final Socket socket; // NOSONAR protected private BufferedWriter writer; protected StringBuilder sb = new StringBuilder(); // NOSONAR protected protected BufferedReader reader; // NOSONAR protected protected boolean stopped; // NOSONAR MailHandler(Socket socket) { this.socket = socket; } @Override public void run() { try { this.reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); this.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream())); } catch (IOException e) { LOGGER.error(IO_EXCEPTION, e); } doRun(); } protected void write(String str) throws IOException { this.writer.write(str); this.writer.write("\r\n"); this.writer.flush(); } abstract void doRun(); void stop() { this.stopped = true; try { this.socket.close(); } catch (IOException e) { // NOSONAR } } } } private TestMailServer() { } }
24.961679
99
0.586154
291244cc2c5748150d859f2072bc8b4091066812
3,619
/* * 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 javax.swing; import java.util.Arrays; import java.util.Vector; @SuppressWarnings("unchecked") public class DefaultComboBoxModel extends AbstractListModel implements MutableComboBoxModel { private static final long serialVersionUID = 3906372640380892983L; private Vector listData; private Object selection; public DefaultComboBoxModel() { super(); listData = new Vector(); } public DefaultComboBoxModel(Object[] items) { super(); listData = new Vector(); listData.addAll(Arrays.asList(items)); if (items.length > 0) { selection = items[0]; } } public DefaultComboBoxModel(Vector<?> items) { listData = items; if (items.size() > 0) { selection = items.get(0); } } public void addElement(Object element) { listData.add(element); fireIntervalAdded(this, listData.size() - 1, listData.size() - 1); if (getSelectedItem() == null) { setSelectedItem(element); } } public Object getElementAt(int index) { return index < getSize() ? listData.get(index) : null; } public int getIndexOf(Object element) { return listData.indexOf(element); } public int getSize() { return listData.size(); } public void insertElementAt(Object element, int index) { listData.insertElementAt(element, index); fireIntervalAdded(this, index, index); } public void removeAllElements() { int size = getSize(); if (size > 0) { listData.clear(); fireIntervalRemoved(this, 0, size - 1); } selection = null; } public void removeElement(Object element) { int index = getIndexOf(element); if (index != -1) { removeElementAt(index); } } public void removeElementAt(int index) { Object removingElement = getElementAt(index); listData.remove(index); if (selection == removingElement || selection != null && selection.equals(removingElement)) { if (index == 0 && getSize() > 0) { setSelectedItem(getElementAt(0)); } else if (index > 0) { setSelectedItem(getElementAt(index - 1)); } else { setSelectedItem(null); } } fireIntervalRemoved(this, index, index); } public Object getSelectedItem() { return selection; } public void setSelectedItem(Object element) { if (element != null && !element.equals(selection) || element == null && selection != null) { selection = element; fireContentsChanged(this, -1, -1); } } }
29.909091
93
0.612048
40efeab3a87c0f9071e6b9ddc9d0f4c10b0db6dd
9,017
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.demonstrations.feature.detect.extract; import boofcv.abst.feature.detect.extract.ConfigExtract; import boofcv.abst.feature.detect.extract.NonMaxSuppression; import boofcv.abst.feature.detect.intensity.GeneralFeatureIntensity; import boofcv.abst.filter.derivative.AnyImageDerivative; import boofcv.alg.feature.detect.intensity.HessianBlobIntensity; import boofcv.alg.feature.detect.interest.GeneralFeatureDetector; import boofcv.alg.feature.detect.selector.FeatureSelectLimitIntensity; import boofcv.alg.feature.detect.selector.FeatureSelectNBest; import boofcv.alg.feature.detect.selector.SampleIntensityImage; import boofcv.alg.filter.derivative.DerivativeType; import boofcv.alg.filter.derivative.GImageDerivativeOps; import boofcv.alg.misc.ImageStatistics; import boofcv.factory.feature.detect.extract.FactoryFeatureExtractor; import boofcv.factory.feature.detect.intensity.FactoryIntensityPoint; import boofcv.gui.SelectAlgorithmAndInputPanel; import boofcv.gui.feature.FancyInterestPointRender; import boofcv.gui.image.ImagePanel; import boofcv.gui.image.ShowImages; import boofcv.gui.image.VisualizeImageData; import boofcv.io.PathLabel; import boofcv.io.UtilIO; import boofcv.io.image.ConvertBufferedImage; import boofcv.misc.BoofMiscOps; import boofcv.struct.QueueCorner; import boofcv.struct.image.GrayF32; import boofcv.struct.image.ImageGray; import georegression.struct.point.Point2D_I16; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Objects; /** * Displays a window showing the selected corner-laplace features across different scale spaces. * * @author Peter Abeles */ @SuppressWarnings({"NullAway.Init"}) public class CompareFeatureExtractorApp<T extends ImageGray<T>, D extends ImageGray<D>> extends SelectAlgorithmAndInputPanel implements GeneralExtractConfigPanel.Listener { T grayImage; Class<T> imageType; GeneralExtractConfigPanel configPanel; boolean processImage = false; BufferedImage input; BufferedImage intensityImage; BufferedImage workImage; AnyImageDerivative<T, D> deriv; GeneralFeatureIntensity<T, D> intensityAlg; int minSeparation = 5; // which image is being viewed in the GUI int viewImage = 2; int radius = 2; int numFeatures = 200; float thresholdFraction = 0.1f; FancyInterestPointRender render = new FancyInterestPointRender(); ImagePanel imagePanel; public CompareFeatureExtractorApp( Class<T> imageType, Class<D> derivType ) { super(1); this.imageType = imageType; addAlgorithm(0, "Harris", FactoryIntensityPoint.harris(radius, 0.04f, false, imageType)); addAlgorithm(0, "KLT", FactoryIntensityPoint.shiTomasi(radius, false, derivType)); addAlgorithm(0, "FAST", FactoryIntensityPoint.fast(5, 11, derivType)); addAlgorithm(0, "KitRos", FactoryIntensityPoint.kitros(derivType)); addAlgorithm(0, "Laplace Det", FactoryIntensityPoint.hessian(HessianBlobIntensity.Type.DETERMINANT, derivType)); addAlgorithm(0, "Laplace Trace", FactoryIntensityPoint.hessian(HessianBlobIntensity.Type.TRACE, derivType)); deriv = GImageDerivativeOps.createAnyDerivatives(DerivativeType.SOBEL, imageType, derivType); JPanel gui = new JPanel(); gui.setLayout(new BorderLayout()); imagePanel = new ImagePanel(); this.configPanel = new GeneralExtractConfigPanel(); configPanel.setThreshold(thresholdFraction); configPanel.setFeatureSeparation(minSeparation); configPanel.setImageIndex(viewImage); configPanel.setListener(this); gui.add(configPanel, BorderLayout.WEST); gui.add(imagePanel, BorderLayout.CENTER); setMainGUI(gui); } public void process( BufferedImage input ) { this.input = input; grayImage = ConvertBufferedImage.convertFromSingle(input, null, imageType); workImage = new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_INT_BGR); SwingUtilities.invokeLater(() -> doRefreshAll()); } @Override public void loadConfigurationFile( String fileName ) { } @Override public void refreshAll( Object[] cookies ) { setActiveAlgorithm(0, "", cookies[0]); } @Override public void setActiveAlgorithm( int indexFamily, String name, Object cookie ) { if (input == null) return; intensityAlg = (GeneralFeatureIntensity<T, D>)cookie; doProcess(); } private synchronized void doProcess() { // System.out.println("radius "+radius+" min separation "+minSeparation+" thresholdFraction "+thresholdFraction+" numFeatures "+numFeatures); deriv.setInput(grayImage); D derivX = deriv.getDerivative(true); D derivY = deriv.getDerivative(false); D derivXX = deriv.getDerivative(true, true); D derivYY = deriv.getDerivative(false, false); D derivXY = deriv.getDerivative(true, false); // todo modifying buffered images which might be actively being displayed, could mess up swing intensityAlg.process(grayImage, derivX, derivY, derivXX, derivYY, derivXY); GrayF32 intensity = intensityAlg.getIntensity(); intensityImage = VisualizeImageData.colorizeSign( intensityAlg.getIntensity(), null, ImageStatistics.maxAbs(intensity)); float max = ImageStatistics.maxAbs(intensity); float threshold = max*thresholdFraction; FeatureSelectLimitIntensity<Point2D_I16> selector = new FeatureSelectNBest<>(new SampleIntensityImage.I16()); NonMaxSuppression extractorMin = null; NonMaxSuppression extractorMax = null; ConfigExtract configExtract = new ConfigExtract(minSeparation, threshold, radius, true); if (intensityAlg.localMinimums()) { configExtract.detectMinimums = true; configExtract.detectMaximums = false; extractorMin = FactoryFeatureExtractor.nonmax(configExtract); } if (intensityAlg.localMaximums()) { configExtract.detectMinimums = false; configExtract.detectMaximums = true; extractorMax = FactoryFeatureExtractor.nonmax(configExtract); } GeneralFeatureDetector<T, D> detector = new GeneralFeatureDetector<>(intensityAlg, extractorMin, extractorMax, selector); detector.setFeatureLimit(numFeatures); detector.process(grayImage, derivX, derivY, derivXX, derivYY, derivXY); QueueCorner foundCorners = detector.getMaximums(); render.reset(); for (int i = 0; i < foundCorners.size(); i++) { Point2D_I16 p = foundCorners.get(i); render.addPoint(p.x, p.y, 3, Color.RED); } Graphics2D g2 = workImage.createGraphics(); g2.drawImage(input, 0, 0, grayImage.width, grayImage.height, null); render.draw(g2); drawImage(); } @Override public void changeInput( String name, int index ) { BufferedImage image = media.openImage(inputRefs.get(index).getPath()); if (image != null) { process(image); } } @Override public boolean getHasProcessedImage() { return processImage; } @Override public void changeImage( int index ) { this.viewImage = index; drawImage(); } private void drawImage() { SwingUtilities.invokeLater(() -> { switch (viewImage) { case 0 -> imagePanel.setImage(input); case 1 -> imagePanel.setImage(intensityImage); case 2 -> imagePanel.setImage(workImage); } BufferedImage b = Objects.requireNonNull(imagePanel.getImage()); imagePanel.setPreferredSize(new Dimension(b.getWidth(), b.getHeight())); imagePanel.repaint(); processImage = true; }); } @Override public synchronized void changeFeatureSeparation( int radius ) { minSeparation = radius; doProcess(); } @Override public synchronized void changeThreshold( double value ) { this.thresholdFraction = (float)value; doProcess(); } @Override public synchronized void changeNumFeatures( int total ) { this.numFeatures = total; doProcess(); } public static void main( String[] args ) { CompareFeatureExtractorApp app = new CompareFeatureExtractorApp(GrayF32.class, GrayF32.class); java.util.List<PathLabel> inputs = new ArrayList<>(); inputs.add(new PathLabel("shapes", UtilIO.pathExample("shapes/shapes01.png"))); inputs.add(new PathLabel("sunflowers", UtilIO.pathExample("sunflowers.jpg"))); inputs.add(new PathLabel("beach", UtilIO.pathExample("scale/beach02.jpg"))); app.setInputList(inputs); // wait for it to process one image so that the size isn't all screwed up while (!app.getHasProcessedImage()) { BoofMiscOps.sleep(10); } ShowImages.showWindow(app, "Feature Extraction", true); System.out.println("Done"); } }
32.789091
142
0.765332
290d756086af7b2031001b3cf4193f1071a46040
390
package org.apache.catalina.authenticator.jaspic; import com.oracle.svm.core.annotate.Delete; import com.oracle.svm.core.annotate.TargetClass; import org.springframework.graalvm.substitutions.OnlyIfPresent; @Delete @TargetClass(className = "org.apache.catalina.authenticator.jaspic.AuthConfigFactoryImpl", onlyWith = { OnlyIfPresent.class }) final class Target_AuthConfigFactoryImpl { }
32.5
126
0.830769
71f556c8f26f49ce29fd39c7b40311ad09fb20df
1,560
package com.appspot.dmutti.calculator.support; import java.math.*; import java.text.*; import javax.persistence.*; import javax.servlet.http.*; import org.joda.time.format.*; public class Helper { public static final DateTimeFormatter dateFormat = DateTimeFormat.forPattern("dd/MM/yyyy"); public static final DateTimeFormatter timeFormat = DateTimeFormat.forPattern("HH:mm:ss"); public static final DateTimeFormatter ligacaoFormat = DateTimeFormat.forPattern("dd/MM/yy HH'H'mm'M'ss"); public static final BigDecimal MINUTO = new BigDecimal("60"); public static EntityManager getEntityManagerFrom(HttpServletRequest req) { return (EntityManager) req.getAttribute(Constants.EntityManager.toString()); } public static NumberFormat getNumberFormat() { DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator(','); DecimalFormat df = new DecimalFormat(); df.setMinimumFractionDigits(2); df.setMaximumFractionDigits(2); df.setDecimalSeparatorAlwaysShown(true); df.setDecimalFormatSymbols(dfs); return df; } public static NumberFormat getNumberFormatDuracao() { DecimalFormatSymbols dfs = new DecimalFormatSymbols(); DecimalFormat df = new DecimalFormat(); df.setMinimumFractionDigits(0); df.setMaximumFractionDigits(0); df.setDecimalSeparatorAlwaysShown(false); df.setDecimalFormatSymbols(dfs); return df; } }
37.142857
110
0.691667
8766164160479ede928be40447b9e33e3e8febe3
962
package scrumweb.security; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import scrumweb.security.domain.Authority; import scrumweb.user.account.domain.UserAccount; import java.util.List; import java.util.stream.Collectors; public class JwtUserFactory { private JwtUserFactory() { } public static JwtUser create(UserAccount user) { return new JwtUser( user.getId(), user.getUsername(), user.getPassword(), mapToGrantedAuthorities(user.getAuthorities()), user.getEnabled() ); } private static List<GrantedAuthority> mapToGrantedAuthorities(List<Authority> authorities) { return authorities.stream() .map(authority -> new SimpleGrantedAuthority(authority.getName().name())) .collect(Collectors.toList()); } }
29.151515
96
0.673597
a40f79ae3ff974a01e6f0f01a3892d92f033fde8
8,157
/* * [New BSD License] * Copyright (c) 2011-2012, Brackit Project Team <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Brackit Project Team nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.brackit.xquery.atomic; import java.util.Arrays; import org.brackit.xquery.ErrorCode; import org.brackit.xquery.QueryException; import org.brackit.xquery.util.Whitespace; import org.brackit.xquery.xdm.Type; /** * @author Sebastian Baechle */ public class B64 extends AbstractAtomic { /* * Base64 Alphabet Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 * B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G * 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L * 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h * 50 y */ private final byte[] bytes; public B64(byte[] bytes) { this.bytes = bytes; } public B64(String str) throws QueryException { str = Whitespace.fullcollapse(str); if ((str.length() & 3) != 0) { throw new QueryException(ErrorCode.ERR_INVALID_VALUE_FOR_CAST, "Cannot cast %s to xs:base64Binary", str); } int size = 0; int length = str.length(); byte[] bytes = new byte[noOfOctets(str)]; for (int charPos = 0; charPos < length; ) { char c1 = str.charAt(charPos++); char c2 = str.charAt(charPos++); char c3 = str.charAt(charPos++); char c4 = str.charAt(charPos++); bytes[size++] = (byte) b64(str, c1); bytes[size++] = (byte) ((c3 != '=') ? b64(str, c2) : b04(str, c2)); if (c4 != '=') { bytes[size++] = (byte) b64(str, c3); bytes[size++] = (byte) b64(str, c4); } else { if (c3 != '=') { bytes[size] = (byte) b16(str, c3); } if (charPos != length) { throw new QueryException(ErrorCode.ERR_INVALID_VALUE_FOR_CAST, "Cannot cast %s to xs:base64Binary", str); } break; } } this.bytes = bytes; } private int b04(String str, char c) throws QueryException { int v; if (c == 'A') v = 0; else if (c == 'Q') v = 16; else if (c == 'g') v = 32; else if (c == 'w') v = 48; else throw new QueryException(ErrorCode.ERR_INVALID_VALUE_FOR_CAST, "Cannot cast %s to xs:base64Binary", str); return v; } private int b16(String str, char c) throws QueryException { int v; if (c == 'A') v = 0; else if (c == 'E') v = 4; else if (c == 'I') v = 8; else if (c == 'M') v = 12; else if (c == 'Q') v = 16; else if (c == 'U') v = 20; else if (c == 'Y') v = 24; else if (c == 'c') v = 28; else if (c == 'g') v = 32; else if (c == 'k') v = 36; else if (c == 'o') v = 40; else if (c == 's') v = 44; else if (c == 'w') v = 48; else if (c == '0') v = 52; else if (c == '4') v = 56; else if (c == '8') v = 60; else throw new QueryException(ErrorCode.ERR_INVALID_VALUE_FOR_CAST, "Cannot cast %s to xs:base64Binary", str); return v; } private int noOfOctets(String str) { int dataLength = str.length(); if ((dataLength > 0) && (str.charAt(dataLength - 1) == '=')) dataLength--; if ((dataLength > 0) && (str.charAt(dataLength - 1) == '=')) dataLength--; return dataLength; } private int b64(String str, char c) throws QueryException { int v; if ((c >= '0') && (c <= '9')) v = 52 + c - 48; else if ((c >= 'A') && (c <= 'Z')) v = c - 65; else if ((c >= 'a') && (c <= 'z')) v = 26 + c - 87; else if (c == '+') v = 62; else if (c == '/') v = 63; else throw new QueryException(ErrorCode.ERR_INVALID_VALUE_FOR_CAST, "Cannot cast %s to xs:base64Binary", str); return v; } @Override public Atomic asType(Type type) throws QueryException { throw new QueryException(ErrorCode.BIT_DYN_RT_NOT_IMPLEMENTED_YET_ERROR); } public byte[] getBytes() { return bytes; } @Override public int hashCode() { return Arrays.hashCode(bytes); } @Override public int cmp(Atomic atomic) throws QueryException { throw new QueryException(ErrorCode.ERR_TYPE_INAPPROPRIATE_TYPE, "Cannot compare '%s with '%s'", type(), atomic.type()); } @Override public boolean eq(Atomic atomic) throws QueryException { if (!(atomic instanceof B64)) { throw new QueryException(ErrorCode.ERR_TYPE_INAPPROPRIATE_TYPE, "Cannot compare '%s with '%s'", type(), atomic.type()); } return Arrays.equals(bytes, ((B64) atomic).bytes); } @Override public int atomicCmpInternal(Atomic atomic) { byte[] bytes2 = ((B64) atomic).bytes; for (int i = 0; i < Math.min(bytes.length, bytes2.length); i++) { if (bytes[i] != bytes2[i]) { return (bytes[i] & 255) - (bytes2[i] & 255); } } return bytes.length - bytes2.length; } @Override public int atomicCode() { return Type.B64_CODE; } @Override public String stringValue() { StringBuilder out = new StringBuilder(); for (byte aByte : bytes) { int v = aByte & 255; char c = (char) (v < 26 ? v + 65 : v < 52 ? v - 26 + 87 : v < 62 ? v - 52 + 48 : v == 62 ? '+' : '/'); out.append(c); } return out.toString(); } @Override public Type type() { return Type.B64; } @Override public boolean booleanValue() throws QueryException { throw new QueryException(ErrorCode.ERR_INVALID_ARGUMENT_TYPE, "Effective boolean value of '%s' is undefined.", type()); } // public static void main(String[] args) throws QueryException // { // char[] SYMBOLS = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', // 'J', 'K', 'L', 'M', 'N', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', // 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', // 'A', 'B', 'C', 'D', 'E', 'F'}; // B64 h = new B64("+/ \t\n1 Q \t M M 8 ="); //new Hex(new byte[]{15, // (byte) 183}); // for (int i = 0; i < SYMBOLS.length; i++) // { // System.out.println(SYMBOLS[i] + " " + ((int) SYMBOLS[i])); // } // for (int i = 0; i < SYMBOLS2.length; i++) // { // System.out.println(SYMBOLS2[i] + " " + ((int) SYMBOLS2[i])); // } // System.out.println(h.toString()); // } }
31.015209
115
0.569572
ea3ea64291ece65cf88e7d3171f4786f0b06d2bd
190
package com.github.beansoft.reatnative.idea.actions; // Just a delegate class with icon support public class JumpToLastEditAction extends com.intellij.ide.actions.JumpToLastEditAction { }
27.142857
89
0.826316
3bc3c926a3f86672f8dac3a7d819d6ca5ad28886
799
package com.mobwal.home.models.db; import androidx.annotation.Nullable; import com.google.android.gms.maps.model.LatLng; import java.io.Serializable; import java.util.Date; import java.util.UUID; public class Attachment implements Serializable { public Attachment() { id = UUID.randomUUID().toString(); d_date = new Date(); n_latitude = null; n_longitude = null; n_date = new Date().getTime(); n_distance = null; } public String id; public String f_route; public String f_point; public String f_result; public String c_name; @Nullable public Double n_latitude; @Nullable public Double n_longitude; public Date d_date; public Long n_date; @Nullable public Double n_distance; }
17.755556
49
0.665832
638e3c9cb6702e0c299e4797bde7aa2a7231b3d4
412
package com.alpha5.autoaid.repository; import com.alpha5.autoaid.model.Appointment; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.Date; import java.util.List; public interface AppointmentRepository extends JpaRepository<Appointment, Long> { List<Appointment> findAllByStaff_StaffIdAndDate(long staffId,Date date); }
27.466667
81
0.82767
76e18f7b0d0fd93f28bc7dfc976b15ff4105e355
10,598
/******************************************************************************* * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.refactoring.reorg; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.resources.IResource; import org.eclipse.jface.dialogs.IInputValidator; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.corext.refactoring.Checks; import org.eclipse.jdt.internal.corext.refactoring.rename.RenamePackageProcessor; import org.eclipse.jdt.internal.corext.refactoring.reorg.INewNameQueries; import org.eclipse.jdt.internal.corext.refactoring.reorg.INewNameQuery; import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.JavaElementLabels; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.TextFieldNavigationHandler; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; public class NewNameQueries implements INewNameQueries { //$NON-NLS-1$ private static final String INVALID_NAME_NO_MESSAGE = ""; private final Wizard fWizard; private final Shell fShell; public NewNameQueries() { fShell = null; fWizard = null; } public NewNameQueries(Wizard wizard) { fWizard = wizard; fShell = null; } public NewNameQueries(Shell shell) { fShell = shell; fWizard = null; } private Shell getShell() { Assert.isTrue(fWizard == null || fShell == null); if (fWizard != null) return fWizard.getContainer().getShell(); if (fShell != null) return fShell; return JavaPlugin.getActiveWorkbenchShell(); } @Override public INewNameQuery createNewCompilationUnitNameQuery(ICompilationUnit cu, String initialSuggestedName) { String[] keys = { BasicElementLabels.getJavaElementName(JavaCore.removeJavaLikeExtension(cu.getElementName())) }; String message = Messages.format(ReorgMessages.ReorgQueries_enterNewNameQuestion, keys); return createStaticQuery(createCompilationUnitNameValidator(cu), message, initialSuggestedName, true, getShell()); } @Override public INewNameQuery createNewResourceNameQuery(IResource res, String initialSuggestedName) { String[] keys = { BasicElementLabels.getResourceName(res) }; String message = Messages.format(ReorgMessages.ReorgQueries_enterNewNameQuestion, keys); return createStaticQuery(createResourceNameValidator(res), message, initialSuggestedName, res.getType() == IResource.FILE, getShell()); } @Override public INewNameQuery createNewPackageNameQuery(IPackageFragment pack, String initialSuggestedName) { String[] keys = { JavaElementLabels.getElementLabel(pack, JavaElementLabels.ALL_DEFAULT) }; String message = Messages.format(ReorgMessages.ReorgQueries_enterNewNameQuestion, keys); return createStaticQuery(createPackageNameValidator(pack), message, initialSuggestedName, false, getShell()); } @Override public INewNameQuery createNewPackageFragmentRootNameQuery(IPackageFragmentRoot root, String initialSuggestedName) { String[] keys = { JavaElementLabels.getElementLabel(root, JavaElementLabels.ALL_DEFAULT) }; String message = Messages.format(ReorgMessages.ReorgQueries_enterNewNameQuestion, keys); return createStaticQuery(createPackageFragmentRootNameValidator(root), message, initialSuggestedName, false, getShell()); } @Override public INewNameQuery createNullQuery() { return createStaticQuery(null); } @Override public INewNameQuery createStaticQuery(final String newName) { return new INewNameQuery() { @Override public String getNewName() { return newName; } }; } private static INewNameQuery createStaticQuery(final IInputValidator validator, final String message, final String initial, final boolean isFile, final Shell shell) { return new INewNameQuery() { @Override public String getNewName() throws OperationCanceledException { InputDialog dialog = new InputDialog(shell, ReorgMessages.ReorgQueries_nameConflictMessage, message, initial, validator) { @Override protected Control createDialogArea(Composite parent) { Control area = super.createDialogArea(parent); TextFieldNavigationHandler.install(getText()); return area; } @Override protected Control createContents(Composite parent) { Control contents = super.createContents(parent); int lastIndexOfDot = initial.lastIndexOf('.'); if (isFile && lastIndexOfDot > 0) { getText().setSelection(0, lastIndexOfDot); } return contents; } }; if (dialog.open() == Window.CANCEL) throw new OperationCanceledException(); return dialog.getValue(); } }; } private static IInputValidator createResourceNameValidator(final IResource res) { IInputValidator validator = new IInputValidator() { @Override public String isValid(String newText) { if (newText == null || "".equals(newText) || //$NON-NLS-1$ res.getParent() == //$NON-NLS-1$ null) return INVALID_NAME_NO_MESSAGE; if (res.getParent().findMember(newText) != null) return ReorgMessages.ReorgQueries_resourceWithThisNameAlreadyExists; if (!res.getParent().getFullPath().isValidSegment(newText)) return ReorgMessages.ReorgQueries_invalidNameMessage; IStatus status = res.getParent().getWorkspace().validateName(newText, res.getType()); if (status.getSeverity() == IStatus.ERROR) return status.getMessage(); if (res.getName().equalsIgnoreCase(newText)) return ReorgMessages.ReorgQueries_resourceExistsWithDifferentCaseMassage; return null; } }; return validator; } private static IInputValidator createCompilationUnitNameValidator(final ICompilationUnit cu) { IInputValidator validator = new IInputValidator() { @Override public String isValid(String newText) { if (newText == null || //$NON-NLS-1$ "".equals(//$NON-NLS-1$ newText)) return INVALID_NAME_NO_MESSAGE; String newCuName = JavaModelUtil.getRenamedCUName(cu, newText); IStatus status = JavaConventionsUtil.validateCompilationUnitName(newCuName, cu); if (status.getSeverity() == IStatus.ERROR) return status.getMessage(); RefactoringStatus refStatus; refStatus = Checks.checkCompilationUnitNewName(cu, newText); if (refStatus.hasFatalError()) return refStatus.getMessageMatchingSeverity(RefactoringStatus.FATAL); if (cu.getElementName().equalsIgnoreCase(newCuName)) return ReorgMessages.ReorgQueries_resourceExistsWithDifferentCaseMassage; return null; } }; return validator; } private static IInputValidator createPackageFragmentRootNameValidator(final IPackageFragmentRoot root) { return new IInputValidator() { IInputValidator resourceNameValidator = createResourceNameValidator(root.getResource()); @Override public String isValid(String newText) { return resourceNameValidator.isValid(newText); } }; } private static IInputValidator createPackageNameValidator(final IPackageFragment pack) { IInputValidator validator = new IInputValidator() { @Override public String isValid(String newText) { if (newText == null || //$NON-NLS-1$ "".equals(//$NON-NLS-1$ newText)) return INVALID_NAME_NO_MESSAGE; IStatus status = JavaConventionsUtil.validatePackageName(newText, pack); if (status.getSeverity() == IStatus.ERROR) return status.getMessage(); IJavaElement parent = pack.getParent(); try { if (parent instanceof IPackageFragmentRoot) { if (!RenamePackageProcessor.isPackageNameOkInRoot(newText, (IPackageFragmentRoot) parent)) return ReorgMessages.ReorgQueries_packagewithThatNameexistsMassage; } } catch (CoreException e) { return INVALID_NAME_NO_MESSAGE; } if (pack.getElementName().equalsIgnoreCase(newText)) return ReorgMessages.ReorgQueries_resourceExistsWithDifferentCaseMassage; return null; } }; return validator; } }
43.975104
170
0.64616
8c763651e2a0210f40057d514317273361d8faae
64
package org.andot.data.j2cube.dto; public class OutCubeDTO { }
12.8
34
0.765625
711a7816d4b5302e94f310f6e7b0ff807d7a69e1
20,859
/** * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. /** * Copyright © 2015 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.phenotype.service; import edu.emory.mathcs.backport.java.util.Arrays; import java.sql.SQLException; import java.util.List; import org.apache.commons.lang.StringUtils; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import uk.ac.ebi.phenotype.solr.indexer.exceptions.IndexerException; import uk.ac.ebi.phenotype.solr.indexer.beans.OntologyTermBean; /** * * @author mrelac */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:test-config.xml" }) public class HpOntologyServiceTest { @Autowired HpOntologyService instance; public HpOntologyServiceTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of populateAncestorGraph method, of class MpOntologyService. * * @throws SQLException */ //@Ignore @Test public void testPopulateAncestorGraph() throws SQLException { System.out.println("testPopulateAncestorGraph"); List<List<String>> hp151 = instance.getAncestorGraphs("HP:0000026"); String errMsg = "Expected size 3. Actual size = " + hp151.size() + "."; assertTrue(errMsg, hp151.size() >= 3); for (List<String> graphs : hp151) { switch (graphs.size()) { case 6: assertEquals("HP:0000118", graphs.get(0)); assertEquals("HP:0000119", graphs.get(1)); assertEquals("HP:0000078", graphs.get(2)); assertEquals("HP:0000080", graphs.get(3)); assertEquals("HP:0012874", graphs.get(4)); assertEquals("HP:0000025", graphs.get(5)); break; case 5: assertEquals("HP:0000118", graphs.get(0)); assertEquals("HP:0000119", graphs.get(1)); assertEquals("HP:0000078", graphs.get(2)); assertEquals("HP:0000080", graphs.get(3)); assertEquals("HP:0000135", graphs.get(4)); break; case 4: assertEquals("HP:0000118", graphs.get(0)); assertEquals("HP:0000818", graphs.get(1)); assertEquals("HP:0008373", graphs.get(2)); assertEquals("HP:0000135", graphs.get(3)); break; default: fail("Expected 4, 5, or 6 ids. Found " + graphs.size() + ". ids: " + StringUtils.join(graphs, ", ")); } } } /** * Test of getDescendentGraphs method, of class MpOntologyService. * * @throws SQLException */ //@Ignore @Test public void testGetDescendentGraphs() throws SQLException { System.out.println("testGetDescendentGraphs"); String errMsg; List<List<String>> hp0000026 = instance.getDescendentGraphs("HP:0000026"); assertEquals(0, hp0000026.size()); List<List<String>> hp0000025 = instance.getDescendentGraphs("HP:0000025"); for (List<String> graphs : hp0000025) { switch (graphs.size()) { case 6: assertEquals("HP:0008669", graphs.get(0)); assertEquals("HP:0000027", graphs.get(1)); assertEquals("HP:0011962", graphs.get(2)); assertEquals("HP:0011963", graphs.get(3)); assertEquals("HP:0011961", graphs.get(4)); assertEquals("HP:0000798", graphs.get(5)); break; case 1: assertEquals("HP:0000026", graphs.get(0)); break; case 3: assertEquals("HP:0012206", graphs.get(0)); assertEquals("HP:0012208", graphs.get(1)); assertEquals("HP:0012207", graphs.get(2)); break; default: fail ("Expected size of: 6, 1, and 3. Size was " + graphs.size()); } } } /** * Test of getSynonyms method, of class MpOntologyService. * * @throws SQLException */ //@Ignore @Test public void testGetSynonyms3Synonyms() throws SQLException { System.out.println("testGetSynonyms3Synonyms"); String[] expectedSynonymsArray = new String[] { "Absent kidney", "Renal aplasia" }; List<String> actualSynonyms = instance.getSynonyms("HP:0000104"); List<String> expectedSynonyms = Arrays.asList(expectedSynonymsArray); String errMsg = "Expected at least 2 synonyms. Actual # synonyms = " + actualSynonyms.size() + "."; assertTrue(errMsg, actualSynonyms.size() >= 2); if ( ! actualSynonyms.containsAll(expectedSynonyms)) { fail("Expected synonyms " + expectedSynonyms + ". Actual synonyms = " + StringUtils.join(actualSynonyms, ", ")); } } /** * Test top level, default level * * @throws SQLException * @throws IndexerException */ //@Ignore @Test public void testGetTopLevelNotTopDefaultLevel() throws SQLException, IndexerException { System.out.println("testGetTopLevelNotTopDefaultLevel"); String[] expectedTermsArray = { "HP:0000118" }; List<OntologyTermBean> actualTerms = instance.getTopLevel("HP:0000026"); String errMsg = "Expected 1 top level HP:0000118 but found " + joinIds(actualTerms); assertTrue(errMsg, actualTerms.size() == 1); assertEquals(expectedTermsArray[0], actualTerms.get(0).getId()); } /** * Test top level, level 1 * * @throws SQLException * @throws IndexerException */ //@Ignore @Test public void testGetTopLevelNotTopLevel1() throws SQLException, IndexerException { System.out.println("testGetTopLevelNotTopLevel1"); String[] expectedTermsArray = { "HP:0000118" }; List<OntologyTermBean> actualTerms = instance.getTopLevel("HP:0000026", 1); String errMsg = "Expected 1 top level HP:0000118 but found " + joinIds(actualTerms); assertTrue(errMsg, actualTerms.size() == 1); assertEquals(expectedTermsArray[0], actualTerms.get(0).getId()); } /** * Test top level, level 2 * * @throws SQLException * @throws IndexerException */ //@Ignore @Test public void testGetTopLevelNotTopLevel2() throws SQLException, IndexerException { System.out.println("testGetTopLevelNotTopLevel2"); String[] expectedTermsArray = { "HP:0000119", "HP:0000818" }; List<OntologyTermBean> actualTerms = instance.getTopLevel("HP:0000026", 2); List<String> expectedTerms = Arrays.asList(expectedTermsArray); int count = 0; for (OntologyTermBean actualTopLevelTerm : actualTerms) { if (expectedTerms.contains(actualTopLevelTerm.getId())) count++; } assertTrue("Expected at least 2 matching ids. Found " + count, count >= 2); } /** * Test top level, level 3 * * @throws SQLException * @throws IndexerException */ //@Ignore @Test public void testGetTopLevelNotTopLevel3() throws SQLException, IndexerException { System.out.println("testGetTopLevelNotTopLevel3"); String[] expectedTermsArray = { "HP:0000078", "HP:0008373" }; List<OntologyTermBean> actualTerms = instance.getTopLevel("HP:0000026", 3); List<String> expectedTerms = Arrays.asList(expectedTermsArray); int count = 0; for (OntologyTermBean actualTopLevelTerm : actualTerms) { if (expectedTerms.contains(actualTopLevelTerm.getId())) count++; } assertTrue("Expected at least 2 matching ids. Found " + count, count >= 2); } /** * Test top level, level 4 * * @throws SQLException * @throws IndexerException */ //@Ignore @Test public void testGetTopLevelNotTopLevel4() throws SQLException, IndexerException { System.out.println("testGetTopLevelNotTopLevel4"); String[] expectedTermsArray = { "HP:0000080", "HP:0000135" }; List<OntologyTermBean> actualTerms = instance.getTopLevel("HP:0000026", 4); List<String> expectedTerms = Arrays.asList(expectedTermsArray); int count = 0; for (OntologyTermBean actualTopLevelTerm : actualTerms) { if (expectedTerms.contains(actualTopLevelTerm.getId())) count++; } assertTrue("Expected at least 2 matching ids. Found " + count, count >= 2); } /** * Test top level, level 5 * * @throws SQLException * @throws IndexerException */ //@Ignore @Test public void testGetTopLevelNotTopLevel5() throws SQLException, IndexerException { System.out.println("testGetTopLevelNotTopLevel5"); String[] expectedTermsArray = { "HP:0012874", "HP:0000135" }; List<OntologyTermBean> actualTerms = instance.getTopLevel("HP:0000026", 5); List<String> expectedTerms = Arrays.asList(expectedTermsArray); int count = 0; for (OntologyTermBean actualTopLevelTerm : actualTerms) { if (expectedTerms.contains(actualTopLevelTerm.getId())) count++; } assertTrue("Expected at least 2 matching ids. Found " + count, count >= 2); } /** * Test top level, level 6 * * @throws SQLException * @throws IndexerException */ //@Ignore @Test public void testGetTopLevelNotTopLevel6() throws SQLException, IndexerException { System.out.println("testGetTopLevelNotTopLevel6"); String[] expectedTermsArray = { "HP:0000025" }; List<OntologyTermBean> actualTerms = instance.getTopLevel("HP:0000026", 6); List<String> expectedTerms = Arrays.asList(expectedTermsArray); int count = 0; for (OntologyTermBean actualTopLevelTerm : actualTerms) { if (expectedTerms.contains(actualTopLevelTerm.getId())) count++; } assertTrue("Expected at least 1 matching id. Found " + count, count >= 1); } /** * Test top level, from top id * * @throws SQLException * @throws IndexerException */ //@Ignore @Test public void testGetTopLevelFromTopDefaultLevel() throws SQLException, IndexerException { System.out.println("testGetTopLevelFromTopDefaultLevel"); List<OntologyTermBean> actualTerms = instance.getTopLevel("HP:0000118"); assertTrue("Expected no matching ids. Found " + actualTerms.size(), actualTerms.isEmpty()); } /** * Test top level, from top id * * @throws SQLException * @throws IndexerException */ //@Ignore @Test public void testGetTopLevelFromTopLevel1() throws SQLException, IndexerException { System.out.println("testGetTopLevelFromTopLevel1"); List<OntologyTermBean> actualTerms = instance.getTopLevel("HP:0000118", 1); assertTrue("Expected no matching ids. Found " + actualTerms.size(), actualTerms.isEmpty()); } /** * Test top level, from top id * * @throws SQLException * @throws IndexerException */ //@Ignore @Test public void testGetTopLevelFromTopLevel2() throws SQLException, IndexerException { System.out.println("testGetTopLevelFromTopLevel2"); List<OntologyTermBean> actualTerms = instance.getTopLevel("HP:0000118", 2); assertTrue("Expected no matching ids. Found " + actualTerms.size(), actualTerms.isEmpty()); } /** * Test getAncestorTerms * * Expected result: ["MP:0005397", "MP:0002396", "MP:0002429", "MP:0002123", * "MP:0005387", "MP:00000685", "MP:00000716"] */ //@Ignore @Test public void testGetAncestorTerms() { System.out.println("testGetAncestorTerms"); List<OntologyTermBean> actualTerms = instance.getAncestors("HP:0000026"); String[] expectedTermsArray = { "HP:0000118", "HP:0000119", "HP:0000078", "HP:0000080", "HP:0012874", "HP:0000025", "HP:0000135", "HP:0000818", "HP:0008373"}; List<String> expectedTerms = Arrays.asList(expectedTermsArray); int count = 0; for (OntologyTermBean actualTopLevelTerm : actualTerms) { if (expectedTerms.contains(actualTopLevelTerm.getId())) count++; } assertTrue("Expected 9 matching ids. Found " + count, count == 9); } /** * Test getParentTerms * * Expected result: ["MP:0002123", "MP:00000716"] */ //@Ignore @Test public void testGetParentTerms() { System.out.println("testGetParentTerms"); List<OntologyTermBean> actualTerms = instance.getParents("HP:0000026"); String[] expectedTermsArray = { "HP:0000025", "HP:0000135" }; List<String> expectedTerms = Arrays.asList(expectedTermsArray); int count = 0; for (OntologyTermBean actualTopLevelTerm : actualTerms) { if (expectedTerms.contains(actualTopLevelTerm.getId())) count++; } assertTrue("Expected exactly 2 matching ids. Found " + count, count == 2); } /** * Test getIntermediateTerms * * Expected result: ["MP:0005397", "MP:0002396", "MP:0002429", "MP:0002123", * "MP:0005387", "MP:00000685", "MP:00000716"] */ //@Ignore @Test public void testGetIntermediateTerms() { System.out.println("testGetIntermediateTerms"); List<OntologyTermBean> actualTerms = instance.getAncestors("HP:0000026"); String[] expectedTermsArray = { "HP:0000119", "HP:0000078", "HP:0000080", "HP:0012874", "HP:0000025", "HP:0000135", "HP:0000818", "HP:0008373"}; List<String> expectedTerms = Arrays.asList(expectedTermsArray); int count = 0; for (OntologyTermBean actualTopLevelTerm : actualTerms) { if (expectedTerms.contains(actualTopLevelTerm.getId())) count++; } assertTrue("Expected at least 8 matching ids. Found " + count, count >= 8); } /** * Test getChildTerms * * Expected result: ["HP:0008669", "HP:0000026", "HP:0012206"] */ //@Ignore @Test public void testGetChildTerms() { System.out.println("testGetChildTerms"); List<OntologyTermBean> actualTerms = instance.getChildren("HP:0000026"); assertTrue(actualTerms.isEmpty()); actualTerms = instance.getChildren("HP:0000025"); String[] expectedTermsArray = { "HP:0008669", "HP:0000026", "HP:0012206" }; String errMsg = "Expected " + StringUtils.join(expectedTermsArray, ", ") + " but found " + joinIds(actualTerms); assertEquals(errMsg, 3, actualTerms.size()); List<String> expectedTerms = Arrays.asList(expectedTermsArray); int count = 0; for (OntologyTermBean actualTerm : actualTerms) { if (expectedTerms.contains(actualTerm.getId())) count++; } assertEquals(3, count); } /** * Test getDescendentTerms * * Expected result count: 10 unique descendent terms: * ["HP:0008669", "HP:0000027", "HP:0011962", "HP:0011961", "HP:0011963", "HP:0000798", "HP:0000026", "HP:0012206", "HP:0012208", "HP:0012207"] */ //@Ignore @Test public void testGetDescendentTermsDefault() { System.out.println("testGetDescendentTermsDefault"); List<OntologyTermBean> actualTerms = instance.getDescendents("HP:0000025"); String[] expectedTermsArray = { "HP:0008669", "HP:0000027", "HP:0011962", "HP:0011963", "HP:0011961", "HP:0000798", "HP:0000026", "HP:0012206", "HP:0012208", "HP:0012207" }; String errMsg = "Expected 10 unique descendents but found " + actualTerms.size(); if (actualTerms.size() != 10) fail (errMsg); // Check them. assertEquals(expectedTermsArray[0], actualTerms.get(0).getId()); assertEquals(expectedTermsArray[1], actualTerms.get(1).getId()); assertEquals(expectedTermsArray[2], actualTerms.get(2).getId()); assertEquals(expectedTermsArray[3], actualTerms.get(3).getId()); assertEquals(expectedTermsArray[4], actualTerms.get(4).getId()); assertEquals(expectedTermsArray[5], actualTerms.get(5).getId()); assertEquals(expectedTermsArray[6], actualTerms.get(6).getId()); assertEquals(expectedTermsArray[7], actualTerms.get(7).getId()); assertEquals(expectedTermsArray[8], actualTerms.get(8).getId()); assertEquals(expectedTermsArray[9], actualTerms.get(9).getId()); } /** * Test getDescendentTermsLevel */ //@Ignore @Test public void testGetDescendentTermsWithLevels() { System.out.println("testGetDescendentTermsWithLevels"); List<OntologyTermBean> actualTerms; try { instance.getDescendents("HP:0000026", 0); fail("Expected exception: level == 0."); } catch (Exception e) { // Expected behavior. Do nothing. } actualTerms = instance.getDescendents("HP:0000025", 1); assertEquals(3, actualTerms.size()); assertEquals("HP:0008669", actualTerms.get(0).getId()); assertEquals("HP:0000026", actualTerms.get(1).getId()); assertEquals("HP:0012206", actualTerms.get(2).getId()); actualTerms = instance.getDescendents("HP:0000025", 2); assertEquals(2, actualTerms.size()); assertEquals("HP:0000027", actualTerms.get(0).getId()); assertEquals("HP:0012208", actualTerms.get(1).getId()); actualTerms = instance.getDescendents("HP:0000025", 3); assertEquals(2, actualTerms.size()); assertEquals("HP:0011962", actualTerms.get(0).getId()); assertEquals("HP:0012207", actualTerms.get(1).getId()); actualTerms = instance.getDescendents("HP:0000025", 4); assertEquals(1, actualTerms.size()); assertEquals("HP:0011963", actualTerms.get(0).getId()); actualTerms = instance.getDescendents("HP:0000025", 5); assertEquals(1, actualTerms.size()); assertEquals("HP:0011961", actualTerms.get(0).getId()); actualTerms = instance.getDescendents("HP:0000025", 6); assertEquals(1, actualTerms.size()); assertEquals("HP:0000798", actualTerms.get(0).getId()); actualTerms = instance.getDescendents("HP:0000025", 7); assertEquals(0, actualTerms.size()); actualTerms = instance.getDescendents("HP:0000025", 2000); assertTrue(actualTerms.isEmpty()); } private String joinIds(List<OntologyTermBean> terms) { String retVal = ""; for (OntologyTermBean term : terms) { if ( ! retVal.isEmpty()) retVal += ", "; retVal += term.getId(); } return retVal; } }
37.925455
124
0.602474
de13ce45045a1300f39d24772b7630d70b3572a1
1,521
package ee.telekom.workflow.graph; import java.util.Set; /** * The {@link GraphRepository} is a container of {@link Graph} definitions. */ public interface GraphRepository{ /** * Returns the {@link Graph} with the given name and the given version, * or the latest graph with the given name if no version is <code>null</code>, * or <code>null</code> if no such graph is found.<br> * The latest graph is the graph with the greatest version number. * * @param name * the graph name * @param version * the graph version * @return the {@link Graph} with the given name and the given version, or * <code>null</code> if no suitable graph is found. */ Graph getGraph( String name, Integer version ); /** * Returns all graphs with the given name ordered with decreasing version * number. * * @param name * the graph name * @return all graphs with the given name ordered with decreasing version * number. */ Set<Graph> getGraphs( String name ); /** * Returns all graphs accessible via this repository. * * @return all graphs accessible via this repository */ Set<Graph> getGraphs(); /** * Adds a graph to the repository and overwrites any previously defined * graph with identical name and version. * * @param graph * the graph to be added */ void addGraph( Graph graph ); }
29.25
83
0.608153
640b3ffe613a109b0ba1f4602765c7c9e69e2382
408
package com.paxport.cloudaudit.model; import javax.annotation.Nullable; public interface ItemMetadata { AuditItemType getType(); String getGuid(); long getTimestamp(); String getLevel(); String getModule(); String getLabel(); String getHostname(); @Nullable String getUrl(); @Nullable String getSeriesGuid(); @Nullable Long getMillisTaken(); }
13.6
37
0.661765
a0a273e6cc5d4c092c2adaa4b821ec97ad7bf6af
1,314
package com.solace.demos.cargen; import java.util.regex.Pattern; public class SolaceMessagingInfo { public static SolaceMessagingInfo getInstance() { return new SolaceMessagingInfo(); } private String msgVpnName = "default"; private String clientUsername = "default"; private String clientPassword = "default"; private String smfHost = "192.168.56.111"; public String getMsgVpnName() { return msgVpnName; } public String getClientUsername() { return clientUsername; } public String getClientPassword() { return clientPassword; } public String getSmfHost() { return smfHost; } public void parseArgs(String[] args) throws Exception { if (args.length == 0) return; for (String arg : args) { // Only split if param matches the "-param=value" regexp. if (Pattern.matches("-[\\w]+=.*", arg)) { String[] tokens = arg.split("=", 2); if (tokens[0].equals("-vpn")) { msgVpnName = tokens[1]; } else if (tokens[0].equals("-username")) { clientUsername = tokens[1]; } else if (tokens[0].equals("-password")) { clientPassword = tokens[1]; } else if (tokens[0].equals("-smfhost")) { smfHost = tokens[1]; } else { throw new Exception("Unrecognised parameter "+arg); } } } } }
19.61194
60
0.634703
5cde1c11495eaa16aabbf799a1a01a31a81ae499
3,074
package com.example.multiDatasourceDemo.config; import com.example.multiDatasourceDemo.anothermapper.AnotherMapper; import org.apache.ibatis.io.VFS; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.boot.autoconfigure.SpringBootVFS; import org.mybatis.spring.mapper.MapperFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.inject.Named; import javax.sql.DataSource; @Configuration @MapperScan("com.example.multiDatasourceDemo.mapper") public class MyBatisConfiguration { public static final String PRIMARY_SESSION_FACTORY = "primarySessionFactory"; public static final String METADATA_SESSION_FACTORY = "metadataSessionFactory"; @Bean(name = PRIMARY_SESSION_FACTORY) @Primary public SqlSessionFactoryBean primarySqlSessionFactory( @Named(DatabaseConfiguration.PRIMARY_DATASOURCE)final DataSource primaryDataSource) throws Exception{ final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(primaryDataSource); VFS.addImplClass(SpringBootVFS.class); PathMatchingResourcePatternResolver pathM3R = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(pathM3R.getResources("classpath:mapper/**/*Mapper.xml")); sqlSessionFactoryBean.setTypeAliasesPackage("com.example.multiDatasourceDemo.domain"); SqlSessionFactory sqlSessionFactory; sqlSessionFactory = sqlSessionFactoryBean.getObject(); return sqlSessionFactoryBean; } @Bean(name = METADATA_SESSION_FACTORY) public SqlSessionFactoryBean metaSqlSessionFactory( @Named(DatabaseConfiguration.METADATA_DATASOURCE) final DataSource anotherDataSource) throws Exception { final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(anotherDataSource); PathMatchingResourcePatternResolver pathM3R = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(pathM3R.getResources("classpath:anothermapper/anotherMapper.xml")); sqlSessionFactoryBean.setTypeAliasesPackage("com.example.multiDatasourceDemo.domain"); final SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject(); return sqlSessionFactoryBean; } @Bean public MapperFactoryBean<AnotherMapper> dbMapper( @Named(METADATA_SESSION_FACTORY) final SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception { MapperFactoryBean<AnotherMapper> factoryBean = new MapperFactoryBean<>(AnotherMapper.class); factoryBean.setSqlSessionFactory(sqlSessionFactoryBean.getObject()); return factoryBean; } }
51.233333
116
0.802537
9e2edb99a635b7089baa723093bbbc58825b5099
2,422
/* Programa para crear fichero (si no existe) y escribir en el, y (si existe) preguntar a el usuario a ingresar un nuevo numero y este numero sumarlo con el ultimo que existe en el archivo y que solo se guarde la respuesta. */ import java.io.*; public class Main { public static void main(String args []) { String archivo = "C:\\Users\\PC\\IdeaProjects\\QuizPractico\\src\\archivo.txt"; String linea; int resp = 0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ //para activar la escritura FileWriter fw = new FileWriter(archivo,true); BufferedWriter bw = new BufferedWriter(fw); //para preguntar con el nuevo numero System.out.print("Escriba Numero: "); String numero = br.readLine(); //para la lectura del fichero FileReader fr = new FileReader(archivo); BufferedReader bf = new BufferedReader(fr); //sentencia while para que lea el fichero hasta que la respuesta sea nula (null) while ((linea = bf.readLine()) != null){ //convertir la linea de string a int (entero) resp = Integer.parseInt(linea); //imprimir en pantalla la linea System.out.println (linea); } //convertir numero de entrada por el usuario a int int sumando = Integer.parseInt(numero); //crear int para resultado de la suma de el sumando y la linea resp int resultado = resp + sumando; // convertir resultado a string llamado respuesta para que pueda ser guardado en el fichero String respuesta = String.valueOf(resultado); // codigo para que se escribir en el fichero bw.write(respuesta); bw.write("\n"); // para cerrar la lectura y escritura bw.close(); bf.close(); //para imprimir la respuesta System.out.println(respuesta); //excepciones si no se encuentra o problemas con leer archivo } catch (FileNotFoundException e) { System.out.println("No Se Encontro Archivo"); } catch (IOException e) { System.out.println("Error con el Archivo"); } } }
35.617647
121
0.574732
70e407ee9033b306940fa59ecca24073015b3396
376
package com.kqp.ezpas.block.entity.pullerpipe; import com.kqp.ezpas.Ezpas; import net.minecraft.block.BlockState; import net.minecraft.util.math.BlockPos; public class EnderPullerPipeBlockEntity extends PullerPipeBlockEntity { public EnderPullerPipeBlockEntity(BlockPos pos, BlockState state) { super(Ezpas.ENDER_PP_BLOCK_ENTITY, pos, state, 10, 64, 1); } }
31.333333
71
0.784574
1ab6440c80863548e35f843b5ad62aa7ffc16db0
6,670
package com.ruoyi.survey.service.impl; import java.util.Date; import java.util.HashSet; import java.util.List; import com.alibaba.fastjson.JSONObject; import com.ruoyi.common.exception.CustomException; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.survey.domain.QfCreateModel; import com.ruoyi.survey.domain.QfKeyName; import com.ruoyi.survey.domain.QfUserForm; import com.ruoyi.survey.domain.vo.QfKeyNameVo; import com.ruoyi.survey.domain.vo.QfUserFormVo; import com.ruoyi.survey.domain.vo.SchoolVO; import com.ruoyi.survey.mapper.QfCreateModelMapper; import com.ruoyi.survey.mapper.QfKeyNameMapper; import com.ruoyi.survey.mapper.QfUserFormMapper; import com.ruoyi.survey.util.QfUtils; import com.ruoyi.system.mapper.SysDeptMapper; import com.ruoyi.system.mapper.SysUserMapper; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.survey.mapper.QfCreateFormMapper; import com.ruoyi.survey.domain.QfCreateForm; import com.ruoyi.survey.service.IQfCreateFormService; import org.springframework.transaction.annotation.Transactional; /** * 【请填写功能名称】Service业务层处理 * * @author Zdde丶 * @date 2020-09-06 */ @Service public class QfCreateFormServiceImpl implements IQfCreateFormService { @Autowired private QfCreateFormMapper qfCreateFormMapper; @Autowired private QfKeyNameMapper qfKeyNameMapper; @Autowired private QfUserFormMapper qfUserFormMapper; @Autowired private SysDeptMapper sysDeptMapper; @Autowired private SysUserMapper sysUserMapper; @Autowired private QfCreateModelMapper qfCreateModelMapper; /** * 查询【请填写功能名称】 * * @param id 【请填写功能名称】ID * @return 【请填写功能名称】 */ @Override public QfCreateForm selectQfCreateFormById(Long id) { return qfCreateFormMapper.selectQfCreateFormById(id); } /** * 查询【请填写功能名称】列表 * * @param qfCreateForm 【请填写功能名称】 * @return 【请填写功能名称】 */ @Override public List<QfCreateForm> selectQfCreateFormList(QfCreateForm qfCreateForm) { return qfCreateFormMapper.selectQfCreateFormList(qfCreateForm); } /** * 新增【请填写功能名称】 * * @param qfCreateForm 【请填写功能名称】 * @return 结果 */ @Override public int insertQfCreateForm(QfCreateForm qfCreateForm) { qfCreateForm.setCreateTime(DateUtils.getNowDate()); return qfCreateFormMapper.insertQfCreateForm(qfCreateForm); } /** * 修改【请填写功能名称】 * * @param qfCreateForm 【请填写功能名称】 * @return 结果 */ @Override public int updateQfCreateForm(QfCreateForm qfCreateForm) { return qfCreateFormMapper.updateQfCreateForm(qfCreateForm); } /** * 批量删除【请填写功能名称】 * * @param ids 需要删除的【请填写功能名称】ID * @return 结果 */ @Override @Transactional(rollbackFor = Exception.class) public int deleteQfCreateFormByIds(Long[] ids) { qfKeyNameMapper.deleteQfKeyNameByIds(ids); qfUserFormMapper.deleteQfUserFormByIds(ids); return qfCreateFormMapper.deleteQfCreateFormByIds(ids); } @Override @Transactional(rollbackFor = Exception.class) public int insertQuestionnaire(QfCreateForm qfCreateForm) { qfCreateForm.setStrData(QfUtils.restructureJson(qfCreateForm.getStrData())); QfKeyNameVo qfKeyNames = JSONObject.parseObject(qfCreateForm.getStrData(), QfKeyNameVo.class); int size =-1; size = qfCreateFormMapper.insertQfCreateForm(qfCreateForm); HashSet<String> set =new HashSet<>(); for (QfKeyName qfKeyName : qfKeyNames.getList()) { set.add(qfKeyName.getName()); } if (set.size()!=qfKeyNames.getList().size()){ throw new CustomException("有重复标题的数据"); } for (QfKeyName qfKeyName : qfKeyNames.getList()) { size = qfKeyNameMapper.insertQfKeyName(qfKeyName.setCreateId(qfCreateForm.getId())); } return size; } @Override public List<QfCreateForm> selectQfCreateFormByUsername(String username, QfCreateForm qfCreateForm) { List<QfCreateForm> qfCreateForms = qfCreateFormMapper.selectQfCreateFormByUsername(username, qfCreateForm); return qfCreateForms; } @Override @Transactional(rollbackFor = Exception.class) public int submitQfCreateForm(QfUserFormVo qfUserFormVo) { if (qfUserFormVo==null||qfUserFormVo.getEndTime()==null){ throw new CustomException("请设置截止时间"); } for (SchoolVO school:qfUserFormVo.getSchools()) { qfUserFormMapper.insertQfUserForm(new QfUserForm(qfUserFormVo.getCreateId(),school.getSchoolName(),school.getSchoolId())); } return qfCreateFormMapper.updateQfCreateForm(new QfCreateForm(qfUserFormVo.getCreateId(),1,qfUserFormVo.getEndTime(),new Date())); } @Override public QfCreateForm selectQfCreateFormAndUserFormReasonById(Long cid,Long sid) { return qfCreateFormMapper.selectQfCreateFormAndUserFormReasonById(cid,sid); } @Override public int withdrawQfCreateForm(QfUserFormVo qfUserFormVo) { for (SchoolVO school:qfUserFormVo.getSchools()) { QfUserForm qfUserForm = qfUserFormMapper.selectQfSchoolFormBySId(school.getSchoolId().longValue(), qfUserFormVo.getCreateId()); qfUserFormMapper.deleteQfUserFormById(qfUserForm.getId()); } return qfCreateFormMapper.updateQfCreateForm(new QfCreateForm(new Date(),qfUserFormVo.getCreateId(),0)); } @Override public int insertQuestionnaireCustom(QfCreateForm qfCreateForm, Boolean isMould) { qfCreateForm.setStrData(QfUtils.restructureJson(qfCreateForm.getStrData())); QfKeyNameVo qfKeyNames = JSONObject.parseObject(qfCreateForm.getStrData(), QfKeyNameVo.class); int size =-1; QfCreateModel qfCreateModel = new QfCreateModel(); BeanUtils.copyProperties(qfCreateForm,qfCreateModel); HashSet<String> set =new HashSet<>(); for (QfKeyName qfKeyName : qfKeyNames.getList()) { set.add(qfKeyName.getName()); } if (set.size()!=qfKeyNames.getList().size()){ throw new CustomException("问卷中的标题有重复"); } size += qfCreateFormMapper.insertQfCreateForm(qfCreateForm); for (QfKeyName qfKeyName : qfKeyNames.getList()) { size += qfKeyNameMapper.insertQfKeyName(qfKeyName.setCreateId(qfCreateForm.getId())); } if (isMould){ size+=qfCreateModelMapper.insertQfCreateModel(qfCreateModel); } return size; } }
34.381443
139
0.706897
3affb92817fed2b2183f207de7f920be77aaf513
1,999
package uk.co.mruoc.cronparser.domain; import java.util.Arrays; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.lang.System.lineSeparator; public class CronResultFormatter { public String format(CronResult result) { return toLines(result).collect(Collectors.joining(lineSeparator())); } public static Stream<String> toLines(CronResult result) { return Stream.of( formatMinutes(result), formatHours(result), formatDaysOfMonth(result), formatMonths(result), formatDaysOfWeek(result), formatCommand(result) ); } private static String formatMinutes(CronResult result) { return formatValues("minute", result::getMinutes); } private static String formatHours(CronResult result) { return formatValues("hour", result::getHours); } private static String formatDaysOfMonth(CronResult result) { return formatValues("day of month", result::getDaysOfMonth); } private static String formatMonths(CronResult result) { return formatValues("month", result::getMonths); } private static String formatDaysOfWeek(CronResult result) { return formatValues("day of week", result::getDaysOfWeek); } private static String formatCommand(CronResult result) { return formatValues("command", result.getCommand()); } private static String formatValues(String name, Supplier<int[]> values) { return formatValues(name, toString(values.get())); } private static String formatValues(String name, String values) { return String.format("%-14s%s", name, values); } private static String toString(int[] values) { return Arrays.stream(values) .sorted() .mapToObj(Integer::toString) .collect(Collectors.joining(" ")); } }
30.287879
77
0.656328
8c0f80dbca48bfd36664a139374b08e56d383f59
635
package com.br.rodrigo.pereira.sensorlogger.model.domain.data; import com.br.rodrigo.pereira.sensorlogger.model.domain.enums.UserStatus; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.EnumType; import javax.persistence.Enumerated; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class UserIdentityUpdateData { private String oldUsername; private String newUsername; private String oldPassword; private String newPassword; @Enumerated(EnumType.STRING) private UserStatus userStatus; }
26.458333
74
0.784252
e2e70b38dc6092c9c6c6db7069e085f24d4b15c5
707
package io.renren.modules.generator.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 我的挂号 * * @author chenshun * @email [email protected] * @date 2019-12-05 23:57:17 */ @Data @TableName("appointment") public class AppointmentEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 挂号信息表 */ @TableId private Integer id; /** * 病人姓名 */ private String patientName; /** * 医生姓名 */ private String doctorName; /** * 挂号费 */ private Integer cost; /** * 预约时间 */ private String appointmentTime; }
15.711111
56
0.701556
11c33ba6f364ff1983ebb1e29113d019fab5bce0
260
package com.javabasico; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Quality { enum Level { BAD, INDIFFERENT, GOOD } Level value() default Level.INDIFFERENT; }
20
44
0.788462
260506594edad5312d3032706168d2158c1f3913
2,293
package com.st.libsec; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.WindowManager.LayoutParams; /** * A helper activity class to turn on the screen * * Copyright 2019 STMicroelectronics Application 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. * * @author Jürgen Böhler */ public class WakAct extends Activity { /** * The broadcast receiver listening for a turned on screen */ private class ScrRcv extends BroadcastReceiver { /** * Called when the screen is turned on * Finishes this activity * * @param context The app context (not used here) * @param intent The intent for switched on screen (not used here) */ @Override public void onReceive(Context context, Intent intent) { finish(); // Finish this activity } } /** * Creates the helper activity to turn on the screen * * @param savedInstanceState The saved origin state */ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialize this activity getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_SHOW_WHEN_LOCKED);// Set the window flags to turn on screen registerReceiver(new ScrRcv(), new IntentFilter(Intent.ACTION_SCREEN_ON)); // Set broadcast receiver for turned on screen } }
37.590164
146
0.664195
19183736c2f2a826b12a65a820275c3f91158027
896
package io.github.elitedev.spigot.event.test; import io.github.elitedev.spigot.entity.SpigotNPC; import io.github.elitedev.spigot.entity.impl.SpigotNPCImpl_v1_8_R3; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import java.util.UUID; // Class for testing purposes only. public class InteractEvent implements Listener { @EventHandler public void onClick(PlayerInteractEvent event) { if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { return; } Player player = event.getPlayer(); Location location = event.getClickedBlock().getLocation(); SpigotNPC npc = new SpigotNPCImpl_v1_8_R3(UUID.randomUUID(), location, "npc"); npc.show(player); } }
28.903226
86
0.734375
eba252f9515df3cf53a5c086f571fc615b7a9597
1,080
package com.ibm.streamsx.rest; import java.io.IOException; import java.math.BigInteger; import com.ibm.streamsx.topology.internal.streams.InvokeCancel; class StreamsConnectionImpl extends AbstractStreamsConnection { private final String userName; StreamsConnectionImpl(String userName, String authorization, String resourcesUrl, boolean allowInsecure) throws IOException { super(authorization, resourcesUrl, allowInsecure); this.userName = userName; } @Override String getAuthorization() { return authorization; } @Override boolean cancelJob(Instance instance, String jobId) throws IOException { InvokeCancel cancelJob = new InvokeCancel( instance.getDomain().getId(), instance.getId(), new BigInteger(jobId), userName); try { return cancelJob.invoke(false) == 0; } catch (Exception e) { throw new RESTException("Unable to cancel job " + jobId + " in instance " + instance.getId(), e); } } }
29.189189
76
0.656481
ff0bf0a3f84cd086a3afda265336945c4c7175f1
2,123
/* * Copyright 2016-2020 DiffPlug * * 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.diffplug.gradle.spotless; import java.io.File; import java.io.IOException; import java.util.Collections; import org.gradle.api.Project; import org.junit.Before; import org.junit.Test; import com.diffplug.spotless.FormatterStep; import com.diffplug.spotless.LineEnding; import com.diffplug.spotless.ResourceHarness; import com.diffplug.spotless.TestProvisioner; public class FormatTaskTest extends ResourceHarness { private SpotlessTaskImpl spotlessTask; @Before public void createTask() throws IOException { Project project = TestProvisioner.gradleProject(rootFolder()); spotlessTask = project.getTasks().create("spotlessTaskUnderTest", SpotlessTaskImpl.class); spotlessTask.setLineEndingsPolicy(LineEnding.UNIX.createPolicy()); } @Test public void testLineEndings() throws Exception { File testFile = setFile("testFile").toContent("\r\n"); File outputFile = new File(spotlessTask.getOutputDirectory(), "testFile"); spotlessTask.setTarget(Collections.singleton(testFile)); Tasks.execute(spotlessTask); assertFile(outputFile).hasContent("\n"); } @Test public void testStep() throws Exception { File testFile = setFile("testFile").toContent("apple"); File outputFile = new File(spotlessTask.getOutputDirectory(), "testFile"); spotlessTask.setTarget(Collections.singleton(testFile)); spotlessTask.addStep(FormatterStep.createNeverUpToDate("double-p", content -> content.replace("pp", "p"))); Tasks.execute(spotlessTask); assertFile(outputFile).hasContent("aple"); } }
33.171875
109
0.769666
58337e7082918c8fe840ba7e754b1b91283ff52a
2,036
package me.kkuai.kuailian.adapter; import java.util.LinkedList; import java.util.List; import me.kkuai.kuailian.R; import me.kkuai.kuailian.log.Log; import me.kkuai.kuailian.log.LogFactory; import android.content.Context; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; public class BatchUploadPhotoAdapter extends BaseAdapter { private Log log = LogFactory.getLog(BatchUploadPhotoAdapter.class); private Context context; private LinkedList<String> photos = new LinkedList<String>(); private final static String uploadImage = "upload_image"; public BatchUploadPhotoAdapter(Context context) { this.context = context; photos.addFirst(uploadImage); } public LinkedList<String> getPhotos() { return photos; } public void setPhotos(LinkedList<String> photos) { this.photos = photos; } @Override public int getCount() { return photos.size(); } @Override public Object getItem(int position) { return photos.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (null == convertView) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.item_grid, parent, false); ViewHolder vh = new ViewHolder(); vh.ivPhoto = (ImageView) convertView.findViewById(R.id.iv_photo); convertView.setTag(vh); } ViewHolder vh = (ViewHolder) convertView.getTag(); if (uploadImage.equals(photos.get(position))) { vh.ivPhoto.setImageResource(R.drawable.upload_image); } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 8; vh.ivPhoto.setImageBitmap(BitmapFactory.decodeFile(photos.get(position), options)); } return convertView; } class ViewHolder { ImageView ivPhoto; } }
26.441558
104
0.761297
621a066b1ec43bf1fb759fae800df70beff75eaa
272
import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { System.out.print("> "); String s = ConvertingValues.clearSpaces(new Scanner(System.in).nextLine()); Parsing.Calculate(s); } }
27.2
84
0.632353
33607ec1a0609b9e5b3560741cdfaa2d97817b07
99
/** * The package contains the classes for the perfect work of the program. */ package sample;
24.75
73
0.707071
86df645875cf9fc261f272d79e0b54f282aa90fd
7,863
package com.protonail.leveldb.jna; import com.sun.jna.Memory; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.PointerByReference; public class LevelDB implements AutoCloseable { protected LevelDBNative.LevelDB levelDB; public LevelDB(String levelDBDirectory, LevelDBOptions options) { options.checkOptionsOpen(); PointerByReference error = new PointerByReference(); levelDB = LevelDBNative.leveldb_open(options.options, levelDBDirectory, error); LevelDBNative.checkError(error); } public void close() { checkDatabaseOpen(); LevelDBNative.leveldb_close(levelDB); levelDB = null; } public byte[] get(byte[] key, LevelDBReadOptions readOptions) { checkDatabaseOpen(); readOptions.checkReadOptionsOpen(); PointerByReference resultLengthPointer = new PointerByReference(); PointerByReference result; long resultLength; PointerByReference error = new PointerByReference(); if (Native.POINTER_SIZE == 8) { long keyLength = key != null ? key.length : 0; result = LevelDBNative.leveldb_get(levelDB, readOptions.readOptions, key, keyLength, resultLengthPointer, error); LevelDBNative.checkError(error); resultLength = resultLengthPointer.getPointer().getLong(0); } else { int keyLength = key != null ? key.length : 0; result = LevelDBNative.leveldb_get(levelDB, readOptions.readOptions, key, keyLength, resultLengthPointer, error); LevelDBNative.checkError(error); resultLength = resultLengthPointer.getPointer().getInt(0); } byte[] resultAsByteArray = null; if (result != null) { resultAsByteArray = result.getPointer().getByteArray(0, (int) resultLength); LevelDBNative.leveldb_free(result.getPointer()); } return resultAsByteArray; } public void put(byte[] key, byte[] value, LevelDBWriteOptions writeOptions) { checkDatabaseOpen(); writeOptions.checkWriteOptionsOpen(); PointerByReference error = new PointerByReference(); if (Native.POINTER_SIZE == 8) { long keyLength = key != null ? key.length : 0; long valueLength = value != null ? value.length : 0; LevelDBNative.leveldb_put(levelDB, writeOptions.writeOptions, key, keyLength, value, valueLength, error); } else { int keyLength = key != null ? key.length : 0; int valueLength = value != null ? value.length : 0; LevelDBNative.leveldb_put(levelDB, writeOptions.writeOptions, key, keyLength, value, valueLength, error); } LevelDBNative.checkError(error); } public void write(LevelDBWriteBatch writeBatch, LevelDBWriteOptions writeOptions) { checkDatabaseOpen(); writeOptions.checkWriteOptionsOpen(); PointerByReference error = new PointerByReference(); LevelDBNative.leveldb_write(levelDB, writeOptions.writeOptions, writeBatch.writeBatch, error); LevelDBNative.checkError(error); } public void delete(byte[] key, LevelDBWriteOptions writeOptions) { checkDatabaseOpen(); writeOptions.checkWriteOptionsOpen(); PointerByReference error = new PointerByReference(); if (Native.POINTER_SIZE == 8) { long keyLength = key != null ? key.length : 0; LevelDBNative.leveldb_delete(levelDB, writeOptions.writeOptions, key, keyLength, error); } else { int keyLength = key != null ? key.length : 0; LevelDBNative.leveldb_delete(levelDB, writeOptions.writeOptions, key, keyLength, error); } LevelDBNative.checkError(error); } public String property(String property) { checkDatabaseOpen(); return LevelDBNative.leveldb_property_value(levelDB, property); } public long[] approximateSizes(Range ...ranges) { checkDatabaseOpen(); if (ranges.length == 0) return new long[0]; Memory startKeys = new Memory(ranges.length * Pointer.SIZE); Memory limitKeys = new Memory(ranges.length * Pointer.SIZE); for (int i = 0; i < ranges.length; i++) { int startKeyLength = ranges[i].getStartKey().length; Memory startKeyMemory = new Memory(startKeyLength); startKeyMemory.write(0, ranges[i].getStartKey(), 0, startKeyLength); startKeys.setPointer(i * Pointer.SIZE, startKeyMemory); int limitKeyLength = ranges[i].getLimitKey().length; Memory limitKeyMemory = new Memory(limitKeyLength); limitKeyMemory.write(0, ranges[i].getLimitKey(), 0, limitKeyLength); limitKeys.setPointer(i * Pointer.SIZE, limitKeyMemory); } Pointer sizes = new Memory(ranges.length * Native.getNativeSize(Long.TYPE)); if (Native.POINTER_SIZE == 8) { long[] startLengths = new long[ranges.length]; long[] limitLengths = new long[ranges.length]; for (int i = 0; i < ranges.length; i++) { startLengths[i] = ranges[i].getStartKey().length; limitLengths[i] = ranges[i].getLimitKey().length; } LevelDBNative.leveldb_approximate_sizes(levelDB, ranges.length, startKeys, startLengths, limitKeys, limitLengths, sizes); } else { int[] startLengths = new int[ranges.length]; int[] limitLengths = new int[ranges.length]; for (int i = 0; i < ranges.length; i++) { startLengths[i] = ranges[i].getStartKey().length; limitLengths[i] = ranges[i].getLimitKey().length; } LevelDBNative.leveldb_approximate_sizes(levelDB, ranges.length, startKeys, startLengths, limitKeys, limitLengths, sizes); } return sizes.getLongArray(0, ranges.length); } public void compactRange(byte[] startKey, byte[] limitKey) { checkDatabaseOpen(); if (Native.POINTER_SIZE == 8) { long startKeyLength = startKey != null ? startKey.length : 0; long limitKeyLength = limitKey != null ? limitKey.length : 0; LevelDBNative.leveldb_compact_range(levelDB, startKey, startKeyLength, limitKey, limitKeyLength); } else { int startKeyLength = startKey != null ? startKey.length : 0; int limitKeyLength = limitKey != null ? limitKey.length : 0; LevelDBNative.leveldb_compact_range(levelDB, startKey, startKeyLength, limitKey, limitKeyLength); } } public LevelDBSnapshot createSnapshot() { final LevelDBNative.Snapshot snapshot = LevelDBNative.leveldb_create_snapshot(levelDB); return new LevelDBSnapshot(levelDB, snapshot); } public static void repair(String levelDBDirectory, LevelDBOptions options) { options.checkOptionsOpen(); PointerByReference error = new PointerByReference(); LevelDBNative.leveldb_repair_db(options.options, levelDBDirectory, error); LevelDBNative.checkError(error); } public static void destroy(String levelDBDirectory, LevelDBOptions options) { options.checkOptionsOpen(); PointerByReference error = new PointerByReference(); LevelDBNative.leveldb_destroy_db(options.options, levelDBDirectory, error); LevelDBNative.checkError(error); } public static int majorVersion() { return LevelDBNative.leveldb_major_version(); } public static int minorVersion() { return LevelDBNative.leveldb_minor_version(); } protected void checkDatabaseOpen() { if (levelDB == null) { throw new LevelDBException("LevelDB database was closed."); } } }
38.925743
133
0.651024
2b1ee8d1c43dbd3dff8adf673028da6edba465d4
7,183
/* Generated SBE (Simple Binary Encoding) message codec */ package sbe.msg; import uk.co.real_logic.sbe.codec.java.CodecUtil; import uk.co.real_logic.agrona.DirectBuffer; @SuppressWarnings("all") public class OrderViewDecoder { public static final int BLOCK_LENGTH = 49; public static final int TEMPLATE_ID = 93; public static final int SCHEMA_ID = 1; public static final int SCHEMA_VERSION = 0; private final OrderViewDecoder parentMessage = this; private DirectBuffer buffer; protected int offset; protected int limit; protected int actingBlockLength; protected int actingVersion; public int sbeBlockLength() { return BLOCK_LENGTH; } public int sbeTemplateId() { return TEMPLATE_ID; } public int sbeSchemaId() { return SCHEMA_ID; } public int sbeSchemaVersion() { return SCHEMA_VERSION; } public String sbeSemanticType() { return ""; } public int offset() { return offset; } public OrderViewDecoder wrap( final DirectBuffer buffer, final int offset, final int actingBlockLength, final int actingVersion) { this.buffer = buffer; this.offset = offset; this.actingBlockLength = actingBlockLength; this.actingVersion = actingVersion; limit(offset + actingBlockLength); return this; } public int encodedLength() { return limit - offset; } public int limit() { return limit; } public void limit(final int limit) { buffer.checkLimit(limit); this.limit = limit; } public static int securityIdId() { return 1; } public static String securityIdMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public static int securityIdNullValue() { return -2147483648; } public static int securityIdMinValue() { return -2147483647; } public static int securityIdMaxValue() { return 2147483647; } public int securityId() { return CodecUtil.int32Get(buffer, offset + 0, java.nio.ByteOrder.LITTLE_ENDIAN); } public static int clientOrderIdId() { return 2; } public static String clientOrderIdMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public static byte clientOrderIdNullValue() { return (byte)0; } public static byte clientOrderIdMinValue() { return (byte)32; } public static byte clientOrderIdMaxValue() { return (byte)126; } public static int clientOrderIdLength() { return 20; } public byte clientOrderId(final int index) { if (index < 0 || index >= 20) { throw new IndexOutOfBoundsException("index out of range: index=" + index); } return CodecUtil.charGet(buffer, this.offset + 4 + (index * 1)); } public static String clientOrderIdCharacterEncoding() { return "UTF-8"; } public int getClientOrderId(final byte[] dst, final int dstOffset) { final int length = 20; if (dstOffset < 0 || dstOffset > (dst.length - length)) { throw new IndexOutOfBoundsException("dstOffset out of range for copy: offset=" + dstOffset); } CodecUtil.charsGet(buffer, this.offset + 4, dst, dstOffset, length); return length; } public static int orderIdId() { return 3; } public static String orderIdMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public static int orderIdNullValue() { return -2147483648; } public static int orderIdMinValue() { return -2147483647; } public static int orderIdMaxValue() { return 2147483647; } public int orderId() { return CodecUtil.int32Get(buffer, offset + 24, java.nio.ByteOrder.LITTLE_ENDIAN); } public static int submittedTimeId() { return 4; } public static String submittedTimeMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public static long submittedTimeNullValue() { return 0xffffffffffffffffL; } public static long submittedTimeMinValue() { return 0x0L; } public static long submittedTimeMaxValue() { return 0xfffffffffffffffeL; } public long submittedTime() { return CodecUtil.uint64Get(buffer, offset + 28, java.nio.ByteOrder.LITTLE_ENDIAN); } public static int priceId() { return 5; } public static String priceMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } private final PriceDecoder price = new PriceDecoder(); public PriceDecoder price() { price.wrap(buffer, offset + 36); return price; } public static int orderQuantityId() { return 6; } public static String orderQuantityMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public static int orderQuantityNullValue() { return -2147483648; } public static int orderQuantityMinValue() { return -2147483647; } public static int orderQuantityMaxValue() { return 2147483647; } public int orderQuantity() { return CodecUtil.int32Get(buffer, offset + 44, java.nio.ByteOrder.LITTLE_ENDIAN); } public static int sideId() { return 7; } public static String sideMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public SideEnum side() { return SideEnum.get(CodecUtil.uint8Get(buffer, offset + 48)); } }
20.760116
106
0.590839
f28cd5e17b481c750c629b6190431164c7885225
138
package pl.wojcik.taskwithmongo.model.request; import lombok.Data; @Data public class SendRequest { private Integer magic_number; }
15.333333
46
0.782609
e03dc426dc9780880dcb7ccfa077c7e18e7f5e9d
8,364
package com.mgu.jogo.parser; import org.apache.commons.lang3.CharUtils; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.List; /** * Breaks up a given <code>String</code> of characters into named * tokens. * * @author Markus Günther <[email protected]> */ public class Lexer { private static final char EOF = (char) -1; private static final List<Character> WHITESPACE = Arrays.asList(' ', '\t', '\n', ','); private static final List<Character> OPERATORS = Arrays.asList('+', '-', '*', '/', '^', '<', '>', '='); private final String input; private int index = 0; private char currentCharacter; public Lexer(final String input) { this.input = input.trim(); if (StringUtils.isEmpty(input)) { this.currentCharacter = EOF; } else { this.index = 1; this.currentCharacter = input.charAt(0); if (!isValidCharacter()) { throw new LexerException("Unable to break stream of characters into separate tokens because of an unrecognized character."); } } } private boolean isValidCharacter() { return isWhitespace() || isColon() || isAlphanumeric() || isBracketRight() || isBracketLeft() || isOperator() || isBraceLeft() || isBraceRight(); } private boolean isOperator() { return OPERATORS.stream().filter(c -> c == this.currentCharacter).findAny().isPresent(); } private boolean isEof() { return this.currentCharacter == EOF; } public Token nextToken() { if (isEof()) { return Token.TOKEN_EOF; } while (isWhitespace()) { consume(); } if (isEqualsSign()) { consume(); // if we have two '=' in succession, we return the equality // operator otherwise the equals sign used for assignments if (isEqualsSign()) { consume(); return Token.TOKEN_EQUALITY_OPERATOR; } else { return Token.TOKEN_EQUALS_SIGN; } } if (isPlusOperator()) { consume(); return Token.TOKEN_ADD_OPERATOR; } if (isMinusOperator()) { consume(); return Token.TOKEN_MIN_OPERATOR; } if (isMultiplicationOperator()) { consume(); return Token.TOKEN_MUL_OPERATOR; } if (isDivisionOperator()) { consume(); return Token.TOKEN_DIV_OPERATOR; } if (isPowerOperator()) { consume(); return Token.TOKEN_POW_OPERATOR; } if (isLargerThanOperator()) { consume(); return Token.TOKEN_LARGER_THAN_OPERATOR; } if (isSmallerThanOperator()) { consume(); return Token.TOKEN_SMALLER_THAN_OPERATOR; } if (isColon()) { if (noMoreCharacters()) { throw new LexerException("Expecting more characters after ':'."); } consume(); if (!isAlpha()) { throw new LexerException("Expecting alpha-numeric characters after ':'."); } return Token.TOKEN_COLON; } if (isBraceLeft()) { consume(); return Token.TOKEN_BRACE_LEFT; } if (isBraceRight()) { consume(); return Token.TOKEN_BRACE_RIGHT; } if (isBracketLeft()) { consume(); return Token.TOKEN_BRACKET_LEFT; } if (isBracketRight()) { consume(); return Token.TOKEN_BRACKET_RIGHT; } if (isNumeric()) { return Token.number(readNumber()); } if (isAlpha()) { return Token.characters(readCharacters()); } throw new LexerException("Unable to break stream of characters into separate tokens because of an unrecognized character."); } private boolean noMoreCharacters() { return this.index >= this.input.length(); } private boolean isWhitespace() { return WHITESPACE .stream() .anyMatch(c -> c == this.currentCharacter); } private boolean matchesCharacterToken(final Token token) { return token.value().toCharArray()[0] == this.currentCharacter; } private boolean isColon() { return matchesCharacterToken(Token.TOKEN_COLON); } private boolean isEqualsSign() { return matchesCharacterToken(Token.TOKEN_EQUALS_SIGN); } private boolean isPlusOperator() { return matchesCharacterToken(Token.TOKEN_ADD_OPERATOR); } private boolean isMinusOperator() { return matchesCharacterToken(Token.TOKEN_MIN_OPERATOR); } private boolean isMultiplicationOperator() { return matchesCharacterToken(Token.TOKEN_MUL_OPERATOR); } private boolean isDivisionOperator() { return matchesCharacterToken(Token.TOKEN_DIV_OPERATOR); } private boolean isPowerOperator() { return matchesCharacterToken(Token.TOKEN_POW_OPERATOR); } private boolean isLargerThanOperator() { return matchesCharacterToken(Token.TOKEN_LARGER_THAN_OPERATOR); } private boolean isSmallerThanOperator() { return matchesCharacterToken(Token.TOKEN_SMALLER_THAN_OPERATOR); } private boolean isBraceLeft() { return matchesCharacterToken(Token.TOKEN_BRACE_LEFT); } private boolean isBraceRight() { return matchesCharacterToken(Token.TOKEN_BRACE_RIGHT); } private boolean isBracketLeft() { return matchesCharacterToken(Token.TOKEN_BRACKET_LEFT); } private boolean isBracketRight() { return matchesCharacterToken(Token.TOKEN_BRACKET_RIGHT); } private boolean isNumeric() { return CharUtils.isAsciiNumeric(this.currentCharacter); } private String readNumber() { final StringBuilder buffer = new StringBuilder(); buffer.append(this.currentCharacter); boolean detectedTokenBoundary = false; while (!noMoreCharacters()) { consume(); if (isWhitespace()) { detectedTokenBoundary = true; break; } if (!isNumeric()) { detectedTokenBoundary = true; break; } buffer.append(this.currentCharacter); } if (!detectedTokenBoundary) { consume(); // consumes the last character that we have read, before breaking the while } return buffer.toString(); } private boolean isAlpha() { return CharUtils.isAsciiAlpha(this.currentCharacter); } private boolean isAlphanumeric() { return CharUtils.isAsciiAlphanumeric(this.currentCharacter); } private String readCharacters() { final StringBuilder buffer = new StringBuilder(); buffer.append(this.currentCharacter); boolean detectedTokenBoundary = false; while (!noMoreCharacters()) { consume(); if (isWhitespace()) { detectedTokenBoundary = true; break; } if (!isAlphanumeric()) { detectedTokenBoundary = true; break; } buffer.append(this.currentCharacter); } if (!detectedTokenBoundary) { consume(); // consumes the last character that we have read, before breaking the while } return buffer.toString(); } private void consume() { if (!noMoreCharacters()) { this.currentCharacter = this.input.charAt(this.index); } else { this.currentCharacter = EOF; } this.index++; } public static void main(String[] args) { //final String program = "forward 100\n\n fd 200 pd penup pendown"; final String program = "[[\n"; final Lexer lexer = new Lexer(program); Token currentToken = lexer.nextToken(); while (!(Token.TOKEN_EOF.equals(currentToken))) { System.out.println(currentToken); currentToken = lexer.nextToken(); } } }
28.352542
153
0.579507
229d8cc320e722c0cfd6b65e9477c36d18280830
5,785
package com.crazicrafter1.crutils.refl; import com.crazicrafter1.crutils.ReflectionUtil; import org.bukkit.inventory.ItemStack; import java.lang.reflect.Method; public class Mirror { static Class<?> CLASS_CraftItemStack; static Class<?> CLASS_ItemStack; static Class<?> CLASS_NBTTagCompound; static Class<?> CLASS_NBTBase; static Class<?> CLASS_NBTTagList; static Method METHOD_asNMSCopy; static Method METHOD_asCraftMirror; static Method METHOD_getTag; static Method METHOD_setTag; static Method METHOD_set; static Method METHOD_setInt; static Method METHOD_setDouble; static Method METHOD_setString; static Method METHOD_getString; //static Method METHOD_add; static { try { CLASS_CraftItemStack = ReflectionUtil.getCraftClass("inventory.CraftItemStack"); METHOD_asNMSCopy = ReflectionUtil.getMethod(CLASS_CraftItemStack, "asNMSCopy", ItemStack.class); CLASS_ItemStack = METHOD_asNMSCopy.getReturnType(); METHOD_asCraftMirror = ReflectionUtil.getMethod(CLASS_CraftItemStack, "asCraftMirror", CLASS_ItemStack); // NMS ItemStack has an instance method to get tag // get it // 1.18.1 // NBTTagCompound s() try { METHOD_getTag = ReflectionUtil.getMethod(CLASS_ItemStack, "getTag"); } catch (Exception e) { METHOD_getTag = ReflectionUtil.getMethod(CLASS_ItemStack, "s"); } CLASS_NBTTagCompound = METHOD_getTag.getReturnType(); // 1.18.1 // void c(@Nullable NBTTagCompound nbttagcompound) try { METHOD_setTag = ReflectionUtil.getMethod(CLASS_ItemStack, "setTag", CLASS_NBTTagCompound); } catch (Exception e) { METHOD_setTag = ReflectionUtil.getMethod(CLASS_ItemStack, "c", CLASS_NBTTagCompound); } //static final Class<?> CLASS_NBTBase = ReflectionUtil.getMethod(CLASS_NBTTagCompound,"get").getReturnType(); CLASS_NBTBase = CLASS_NBTTagCompound.getInterfaces()[0]; // 1.8.1 // NBTTagList c(String var0, int var1) try { CLASS_NBTTagList = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "getList", String.class, int.class).getReturnType(); } catch (Exception e) { CLASS_NBTTagList = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "c", String.class, int.class).getReturnType(); } // 1.18.1 // NBTBase a(String var0, NBTBase var1) try { METHOD_set = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "set", String.class, CLASS_NBTBase); METHOD_setInt = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "setInt", String.class, int.class); METHOD_setDouble = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "setDouble", String.class, double.class); METHOD_setString = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "setString", String.class, String.class); METHOD_getString = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "getString", String.class); } catch (Exception e) { METHOD_set = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "a", String.class, CLASS_NBTBase); METHOD_setInt = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "a", String.class, int.class); METHOD_setDouble = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "a", String.class, double.class); METHOD_setString = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "a", String.class, String.class); METHOD_getString = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "l", String.class); } //METHOD_add = ReflectionUtil.getMethod(CLASS_NBTTagList, "add", CLASS_NBTBase); } catch (Exception e) { e.printStackTrace(); } } /* static final Class<?> CLASS_CraftItemStack = ReflectionUtil.getCraftClass("inventory.CraftItemStack"); static final Method METHOD_asNMSCopy = ReflectionUtil.getMethod(CLASS_CraftItemStack, "asNMSCopy", ItemStack.class); static final Class<?> CLASS_ItemStack = METHOD_asNMSCopy.getReturnType(); static final Method METHOD_asCraftMirror = ReflectionUtil.getMethod(CLASS_CraftItemStack, "asCraftMirror", CLASS_ItemStack); // NMS ItemStack has an instance method to get tag // get it static final Method METHOD_getTag = ReflectionUtil.getMethod(CLASS_ItemStack, "getTag"); static final Class<?> CLASS_NBTTagCompound = METHOD_getTag.getReturnType(); static final Method METHOD_setTag = ReflectionUtil.getMethod(CLASS_ItemStack, "setTag", CLASS_NBTTagCompound); //static final Class<?> CLASS_NBTBase = ReflectionUtil.getMethod(CLASS_NBTTagCompound,"get").getReturnType(); static final Class<?> CLASS_NBTBase = CLASS_NBTTagCompound.getInterfaces()[0]; static final Class<?> CLASS_NBTTagList = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "getList", String.class, int.class).getReturnType(); static final Method METHOD_set = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "set", String.class, CLASS_NBTBase); static final Method METHOD_setInt = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "setInt", String.class, int.class); static final Method METHOD_setDouble = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "setDouble", String.class, int.class); static final Method METHOD_setString = ReflectionUtil.getMethod(CLASS_NBTTagCompound, "setString", String.class, int.class); static final Method METHOD_add = ReflectionUtil.getMethod(CLASS_NBTTagList, "add", int.class, CLASS_NBTBase); */ }
43.496241
144
0.694036
5cd21448ed16acb3da14f45cf8a5bdec3ec3e195
6,826
/** * Copyright (C) 2016 Cambridge Systematics, 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.onebusaway.admin.service.bundle.task.model; import java.io.Serializable; import org.onebusaway.csv_entities.schema.annotations.CsvField; import org.onebusaway.gtfs.model.AgencyAndId; import org.onebusaway.gtfs.model.Route; import org.onebusaway.gtfs.serialization.mappings.DefaultAgencyIdFieldMappingFactory; import org.onebusaway.gtfs.serialization.mappings.EntityFieldMappingFactory; import org.onebusaway.gtfs.serialization.mappings.TripAgencyIdFieldMappingFactory; public class ArchivedTrip implements Serializable { private static final long serialVersionUID = 2L; private String agencyId; private String id; private String route_agencyId; private String route_id; private String serviceId_agencyId; private String serviceId_id; private String tripShortName; private String tripHeadsign; private String routeShortName; private String directionId; private String blockId; private String shapeId_agencyId; private String shapeId_id; private int wheelchairAccessible = 0; private Integer gtfsBundleInfoId; //@Deprecated //private int tripBikesAllowed = 0; /** * 0 = unknown / unspecified, 1 = bikes allowed, 2 = bikes NOT allowed */ //private int bikesAllowed = 0; // Custom extension for KCM to specify a fare per-trip //private String fareId; public ArchivedTrip() { } public String getAgencyId() { return agencyId; } public void setAgencyId(String agencyId) { this.agencyId = agencyId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRoute_agencyId() { return route_agencyId; } public void setRoute_agencyId(String route_agencyId) { this.route_agencyId = route_agencyId; } public String getRoute_id() { return route_id; } public void setRoute_id(String route_id) { this.route_id = route_id; } public String getServiceId_agencyId() { return serviceId_agencyId; } public void setServiceId_agencyId(String serviceId_agencyId) { this.serviceId_agencyId = serviceId_agencyId; } public String getServiceId_id() { return serviceId_id; } public void setServiceId_id(String serviceId_id) { this.serviceId_id = serviceId_id; } public String getTripShortName() { return tripShortName; } public void setTripShortName(String tripShortName) { this.tripShortName = tripShortName; } public String getTripHeadsign() { return tripHeadsign; } public void setTripHeadsign(String tripHeadsign) { this.tripHeadsign = tripHeadsign; } public String getRouteShortName() { return routeShortName; } public void setRouteShortName(String routeShortName) { this.routeShortName = routeShortName; } public String getDirectionId() { return directionId; } public void setDirectionId(String directionId) { this.directionId = directionId; } public String getBlockId() { return blockId; } public void setBlockId(String blockId) { this.blockId = blockId; } public String getShapeId_agencyId() { return shapeId_agencyId; } public void setShapeId_agencyId(String shapeId_agencyId) { this.shapeId_agencyId = shapeId_agencyId; } public String getShapeId_id() { return shapeId_id; } public void setShapeId_id(String shapeId_id) { this.shapeId_id = shapeId_id; } public int getWheelchairAccessible() { return wheelchairAccessible; } public void setWheelchairAccessible(int wheelchairAccessible) { this.wheelchairAccessible = wheelchairAccessible; } public Integer getGtfsBundleInfoId() { return gtfsBundleInfoId; } public void setGtfsBundleInfoId(Integer gtfsBundleInfoId) { this.gtfsBundleInfoId = gtfsBundleInfoId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + agencyId.hashCode(); result = prime * result + id.hashCode(); result = prime * result + route_agencyId.hashCode(); result = prime * result + route_id.hashCode(); result = prime * result + serviceId_agencyId.hashCode(); result = prime * result + serviceId_id.hashCode(); result = prime * result + tripShortName.hashCode(); result = prime * result + tripHeadsign.hashCode(); result = prime * result + routeShortName.hashCode(); result = prime * result + directionId.hashCode(); result = prime * result + blockId.hashCode(); result = prime * result + shapeId_agencyId.hashCode(); result = prime * result + shapeId_id.hashCode(); result = prime * result + wheelchairAccessible; result = prime * result + gtfsBundleInfoId; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof ArchivedTrip)) { return false; } ArchivedTrip other = (ArchivedTrip) obj; if (gtfsBundleInfoId != other.gtfsBundleInfoId) { return false; } else if (!agencyId.equals(other.agencyId)) { return false; } else if (!id.equals(other.id)) { return false; } else if (!route_agencyId.equals(other.route_agencyId)) { return false; } else if (!route_id.equals(other.route_id)) { return false; } else if (!serviceId_agencyId.equals(other.serviceId_agencyId)) { return false; } else if (!serviceId_id.equals(other.serviceId_id)) { return false; } else if (!tripShortName.equals(other.tripShortName)) { return false; } else if (!tripHeadsign.equals(other.tripHeadsign)) { return false; } else if (!routeShortName.equals(other.routeShortName)) { return false; } else if (!directionId.equals(other.directionId)) { return false; } else if (!blockId.equals(other.blockId)) { return false; } else if (!shapeId_agencyId.equals(other.shapeId_agencyId)) { return false; } else if (!shapeId_id.equals(other.shapeId_id)) { return false; } else if (wheelchairAccessible != other.wheelchairAccessible) { return false; } return true; } }
23.138983
85
0.701143
a23a5f666dcfb7bb91dfa8bc4eeee4572f16f5a0
1,304
package com.asiainfo.designpattern.architecture.servicelocator; /** * TODO * * @author zq * @date 2018年4月19日 下午5:13:12 * Copyright: 北京亚信智慧数据科技有限公司 */ public class ServiceLocatorTest { public static void main(String[] args) { // app init AppContext context = init(); // service locator init ServiceLocator.setAppContext(context); // byName Service service = ServiceLocator.getBean("nameService", Service.class); service.perform(); // byType service = ServiceLocator.getBean(MyService.class); service.perform(); } static AppContext init() { AppContext context = new AppContext(); context.addBean(new MyService()); context.addBean(new NameService()); return context; } interface Service { void perform(); } static class MyService implements Service { @Override public void perform() { System.out.println("MyService perform"); } } static class NameService implements Service { @Override public void perform() { System.out.println("NameService perform"); } } }
25.076923
80
0.558282
9266e65a42e3ce73be0e48b8e9eee42837844a70
971
package com.movies.moviesapp.mapper; import com.movies.moviesapp.controller.response.WrappedActorListResponse; import com.movies.moviesapp.entity.Actor; import com.movies.moviesapp.util.mapper.CreateMapper; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class ActorListWrappedActorListResponseCreateMapper implements CreateMapper<List<Actor>, WrappedActorListResponse> { private final ModelMapper modelMapper; @Autowired public ActorListWrappedActorListResponseCreateMapper(ModelMapper modelMapper) { this.modelMapper = modelMapper; } @Override public WrappedActorListResponse map(List<Actor> from) { final WrappedActorListResponse response = new WrappedActorListResponse("OK","Fetched actors", from); from.forEach(System.out::println); return response; } }
28.558824
123
0.787848
35e7e7990449cca79007f1c7e5ca33d370a22efa
573
/* * Copyright 2020, Yahoo Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE file in project root for terms. */ package com.yahoo.elide.async.models; /** * ENUM of supported result types. */ public enum ResultType { JSON(FileExtensionType.JSON), CSV(FileExtensionType.CSV); private final FileExtensionType fileExtensionType; ResultType(FileExtensionType fileExtensionType) { this.fileExtensionType = fileExtensionType; } public FileExtensionType getFileExtensionType() { return fileExtensionType; } }
22.92
54
0.720768