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
e5def60d23dbca9d325ee7dff31fee8fcc7ebeed
1,070
package hashTable; import java.util.HashMap; import java.util.List; /** * Created by cuixiaodao on 11/07/2017 * for leetCode problem: * https://leetcode.com/problems/employee-importance/description/ */ class Employee { // It's the unique id of each node; // unique id of this employee public int id; // the importance value of this employee public int importance; // the id of direct subordinates public List<Integer> subordinates; }; public class EmployeeImportance { public int getImportance(List<Employee> employees, int id) { HashMap<Integer, Employee> empMap = new HashMap<>(employees.size() / 2 * 3); for (Employee emp : employees) empMap.put(emp.id, emp); return getImportance(empMap, id); } private int getImportance(HashMap<Integer, Employee> empMap, int id) { Employee cur = empMap.get(id); int importance = cur.importance; for (int subId : cur.subordinates) importance += getImportance(empMap, subId); return importance; } }
27.435897
84
0.660748
4f03615856e7f7a51c5a4b8001cbf542a3d5b0d1
18,024
package pro.taskana; import pro.taskana.exceptions.InvalidArgumentException; import pro.taskana.exceptions.NotAuthorizedException; /** * WorkitemQuery for generating dynamic sql. */ public interface WorkbasketQuery extends BaseQuery<WorkbasketSummary, WorkbasketQueryColumnName> { /** * Add your ids to your query. The ids are compared to the ids of workbaskets with the IN operator. * * @param id * the id as Strings * @return the query */ WorkbasketQuery idIn(String... id); /** * Add your keys to your query. The keys are compared case-insensitively to the keys of workbaskets with the IN * operator. * @param key * the keys as Strings * @return the query */ WorkbasketQuery keyIn(String... key); /** * Add keys to your query. The keys are compared case-insensitively to the keys of workbaskets with the SQL LIKE * operator. You may add a wildcard like '%' to search generically. If you specify multiple keys they are connected * with an OR operator, this is, the query searches workbaskets whose keys are like key1 or like key2, etc. * * @param key * the keys as Strings * @return the query */ WorkbasketQuery keyLike(String... key); /** * Add your names to your query. The names are compared case-insensitively to the names of workbaskets * * @param name * the names as Strings * @return the query */ WorkbasketQuery nameIn(String... name); /** * Add names to your query. The names are compared case-insensitively to the names of workbaskets with the SQL LIKE * operator. You may add a wildcard like '%' to search generically. If you specify multiple names, they are * connected with an OR operator, this is, the query searches workbaskets whose names are like name1 or like name2, * etc. * * @param name * the names as Strings * @return the query */ WorkbasketQuery nameLike(String... name); /** * Add search strings to your query that are searched case-insensitively in the key and name fields of workbaskets. * You may add a wildcard like '%' to search generically. If you specify multiple keys they are connected with an OR * operator, this is, the query searches workbaskets whose keys are like string1 or whose names are like string1 or * whose keys are like string2 or whose names are like string2, etc... * * @param searchString * the seach strings * @return the query */ WorkbasketQuery keyOrNameLike(String... searchString); /** * Add your domains to your query. * * @param domain * the domains as Strings * @return the query */ WorkbasketQuery domainIn(String... domain); /** * Add your types to your query. * * @param type * the types * @return the query */ WorkbasketQuery typeIn(WorkbasketType... type); /** * Add the time intervals within which the workbasket was created to your query. For each time interval, the * database query will search for workbaskets whose created timestamp is after or at the interval's begin and before * or at the interval's end. If more than one interval is specified, the query will connect them with the OR * keyword. If either begin or end of an interval are null, these values will not be specified in the query. * * @param intervals * - the TimeIntervals within which the workbasket was created * @return the query */ WorkbasketQuery createdWithin(TimeInterval... intervals); /** * Add the time intervals within which the workbasket was modified to your query. For each time interval, the * database query will search for workbaskets whose created timestamp is after or at the interval's begin and before * or at the interval's end. If more than one interval is specified, the query will connect them with the OR * keyword. If either begin or end of an interval are null, these values will not be specified in the query. * * @param intervals * - the TimeIntervals within which the workbasket was created * @return the query */ WorkbasketQuery modifiedWithin(TimeInterval... intervals); /** * Add your description to your query. It will be compared case-insensitively to the descriptions of workbaskets * using the LIKE operator. You may use a wildcard like '%' to search generically. If you specify multiple arguments * they are combined with the OR keyword. * * @param description * your description * @return the query */ WorkbasketQuery descriptionLike(String... description); /** * Add the owners to your query. * * @param owners * the owners as String * @return the query */ WorkbasketQuery ownerIn(String... owners); /** * Add the owners for pattern matching to your query. It will be compared in SQL with the LIKE operator. You may use * a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with the OR * keyword. * * @param owners * the owners as Strings * @return the query */ WorkbasketQuery ownerLike(String... owners); /** * Setting up the permission which should be granted on the result workbaskets and the users which should be * checked. READ permission will always be checked by default.<br> * The AccessIds and the given permission will throw a Exception if they would be NULL. * * @param permission * which should be used for results. * @param accessIds * Users which sould be checked for given permissions on workbaskets. * @return the current query object. * @throws InvalidArgumentException * when permission OR the accessIds are NULL. * @throws NotAuthorizedException * if the current user is not member of role BUSINESS_ADMIN or ADMIN */ WorkbasketQuery accessIdsHavePermission(WorkbasketPermission permission, String... accessIds) throws InvalidArgumentException, NotAuthorizedException; /** * Add condition to query if the caller (one of the accessIds of the caller) has the given permission on the * workbasket. * * @return the updated query. * @param permission * the permission for the query condition. */ WorkbasketQuery callerHasPermission(WorkbasketPermission permission); /** * Sort the query result by name. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByName(SortDirection sortDirection); /** * Sort the query result by key. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByKey(SortDirection sortDirection); /** * Sort the query result by description. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByDescription(SortDirection sortDirection); /** * Sort the query result by owner. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByOwner(SortDirection sortDirection); /** * Sort the query result by type. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByType(SortDirection sortDirection); /** * Sort the query result by domain. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByDomain(SortDirection sortDirection); /** * Add the domains for pattern matching to your query. It will be compared in SQL with the LIKE operator. You may * use a wildcard like % to specify the pattern. If you specify multiple arguments they are combined with the OR * keyword. * * @param domain * the domains of workbaskets as Strings * @return the query */ WorkbasketQuery domainLike(String... domain); /** * Sort the query result by custom property 1. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByCustom1(SortDirection sortDirection); /** * Sort the query result by custom property 2. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByCustom2(SortDirection sortDirection); /** * Sort the query result by custom property 3. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByCustom3(SortDirection sortDirection); /** * Sort the query result by custom property 4. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByCustom4(SortDirection sortDirection); /** * Sort the query result by organization level 1. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByOrgLevel1(SortDirection sortDirection); /** * Sort the query result by organization level 2. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByOrgLevel2(SortDirection sortDirection); /** * Sort the query result by organization level 3. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByOrgLevel3(SortDirection sortDirection); /** * Sort the query result by organization level 4. * * @param sortDirection * Determines whether the result is sorted in ascending or descending order. If sortDirection is null, * the result is sorted in ascending order * @return the query */ WorkbasketQuery orderByOrgLevel4(SortDirection sortDirection); /** * Add the 1st custom property to your query. * * @param custom1 * the 1st custom property as String * @return the query */ WorkbasketQuery custom1In(String... custom1); /** * Add the 1st custom property for pattern matching to your query. It will be compared in SQL with the LIKE * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are * combined with the OR keyword. * * @param custom1 * the 1st custom property of workbaskets as Strings * @return the query */ WorkbasketQuery custom1Like(String... custom1); /** * Add the 2nd custom property to your query. * * @param custom2 * the 2nd custom property as String * @return the query */ WorkbasketQuery custom2In(String... custom2); /** * Add the 2nd custom property for pattern matching to your query. It will be compared in SQL with the LIKE * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are * combined with the OR keyword. * * @param custom2 * the 2nd custom property of workbaskets as Strings * @return the query */ WorkbasketQuery custom2Like(String... custom2); /** * Add the 3rd custom property to your query. * * @param custom3 * the 3rd custom property as String * @return the query */ WorkbasketQuery custom3In(String... custom3); /** * Add the 3rd custom property for pattern matching to your query. It will be compared in SQL with the LIKE * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are * combined with the OR keyword. * * @param custom3 * the 3rd custom property of workbaskets as Strings * @return the query */ WorkbasketQuery custom3Like(String... custom3); /** * Add the 4th custom property to your query. * * @param custom4 * the 4th custom property as String * @return the query */ WorkbasketQuery custom4In(String... custom4); /** * Add the 4th custom property for pattern matching to your query. It will be compared in SQL with the LIKE * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are * combined with the OR keyword. * * @param custom4 * the 4th custom property of workbaskets as Strings * @return the query */ WorkbasketQuery custom4Like(String... custom4); /** * Add the 1st organization level to your query. * * @param orgLevel1 * the 1st organization level as String * @return the query */ WorkbasketQuery orgLevel1In(String... orgLevel1); /** * Add the 1st organization level for pattern matching to your query. It will be compared in SQL with the LIKE * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are * combined with the OR keyword. * * @param orgLevel1 * the 1st organization level as Strings * @return the query */ WorkbasketQuery orgLevel1Like(String... orgLevel1); /** * Add the 2nd organization level to your query. * * @param orgLevel2 * the 2nd organization level as String * @return the query */ WorkbasketQuery orgLevel2In(String... orgLevel2); /** * Add the 2nd organization level for pattern matching to your query. It will be compared in SQL with the LIKE * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are * combined with the OR keyword. * * @param orgLevel2 * the 2nd organization level as Strings * @return the query */ WorkbasketQuery orgLevel2Like(String... orgLevel2); /** * Add the 3rd organization level to your query. * * @param orgLevel3 * the 3rd organization level as String * @return the query */ WorkbasketQuery orgLevel3In(String... orgLevel3); /** * Add the 3rd organization level for pattern matching to your query. It will be compared in SQL with the LIKE * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are * combined with the OR keyword. * * @param orgLevel3 * the 3rd organization level as Strings * @return the query */ WorkbasketQuery orgLevel3Like(String... orgLevel3); /** * Add the 4th organization level to your query. * * @param orgLevel4 * the 4th organization level as String * @return the query */ WorkbasketQuery orgLevel4In(String... orgLevel4); /** * Add the 4th organization level for pattern matching to your query. It will be compared in SQL with the LIKE * operator. You may use a wildcard like % to specify the pattern. If you specify multiple arguments they are * combined with the OR keyword. * * @param orgLevel4 * the 4th organization level as Strings * @return the query */ WorkbasketQuery orgLevel4Like(String... orgLevel4); /** * Add to your query if the Workbasket shall be marked for deletion. * * @param markedForDeletion * a simple flag showing if the workbasket is marked for deletion * @return the query */ WorkbasketQuery markedForDeletion(boolean markedForDeletion); }
36.412121
120
0.646471
ebbcd4d7beb91cc0f39f64acdc5452e64b1bd9e0
3,795
/* * 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.flowable.editor.language; import static org.assertj.core.api.Assertions.assertThat; import java.io.InputStream; import org.flowable.bpmn.model.BoundaryEvent; import org.flowable.bpmn.model.BpmnModel; import org.flowable.bpmn.model.GraphicInfo; import org.flowable.editor.language.json.converter.BpmnJsonConverter; import org.junit.jupiter.api.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; /** * Created by David Pardo */ public class BoundaryEventGraphicInfoTest extends AbstractConverterTest { private static final String TIMER_BOUNDERY_ID = "sid-4F284555-6D97-4F67-A926-C96F552A4404"; private static final String USER_TASK_ID = "sid-6A39AD39-C7BB-4D92-896B-CBF37D5D449B"; @Test public void graphicInfoOfBoundaryEventShouldRemainTheSame() throws Exception { BpmnModel model = readJsonFile(); validate(model); model = convertToJsonAndBack(model); validate(model); } @Test public void dockerInfoShouldRemainIntact() throws Exception { InputStream stream = this.getClass().getClassLoader().getResourceAsStream(getResource()); JsonNode model = new ObjectMapper().readTree(stream); BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(model); model = new BpmnJsonConverter().convertToJson(bpmnModel); validate(model); } protected void validate(JsonNode model) { ArrayNode node = (ArrayNode) model.path("childShapes"); JsonNode boundaryEventNode = null; for (JsonNode shape : node) { String resourceId = shape.path("resourceId").asText(); if (TIMER_BOUNDERY_ID.equals(resourceId)) { boundaryEventNode = shape; } } //validate docker nodes Double x = boundaryEventNode.path("dockers").get(0).path("x").asDouble(); Double y = boundaryEventNode.path("dockers").get(0).path("y").asDouble(); //the modeler does not store a mathematical correct docker point. assertThat(x).isEqualTo(50.0); assertThat(y).isEqualTo(80.0); } protected void validate(BpmnModel model) { BoundaryEvent event = (BoundaryEvent) model.getFlowElement(TIMER_BOUNDERY_ID); assertThat(event.getAttachedToRefId()).isEqualTo(USER_TASK_ID); //check graphicinfo boundary GraphicInfo giBoundary = model.getGraphicInfo(TIMER_BOUNDERY_ID); assertThat(giBoundary.getX()).isEqualTo(334.2201675394047); assertThat(giBoundary.getY()).isEqualTo(199.79587432571776); assertThat(giBoundary.getHeight()).isEqualTo(31.0); assertThat(giBoundary.getWidth()).isEqualTo(31.0); //check graphicinfo task GraphicInfo giTaskOne = model.getGraphicInfo(USER_TASK_ID); assertThat(giTaskOne.getX()).isEqualTo(300.0); assertThat(giTaskOne.getY()).isEqualTo(135.0); assertThat(giTaskOne.getWidth()).isEqualTo(100.0); assertThat(giTaskOne.getHeight()).isEqualTo(80.0); } @Override protected String getResource() { return "test.boundaryeventgraphicinfo.json"; } }
38.333333
97
0.709091
8cbcc3215bb56b8f1d8f289fc53c3b0c8e87376a
3,915
/* * Copyright 2019 The Hekate Project * * The Hekate Project 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 io.hekate.cluster.internal; import io.hekate.cluster.ClusterFilter; import io.hekate.cluster.ClusterTopology; import io.hekate.cluster.ClusterView; import io.hekate.cluster.event.ClusterEventListener; import io.hekate.cluster.event.ClusterEventType; import io.hekate.core.internal.util.ArgAssert; import io.hekate.util.format.ToString; import io.hekate.util.format.ToStringIgnore; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; public class FilteredClusterView implements ClusterView { @ToStringIgnore private final ClusterView parent; @ToStringIgnore private final ClusterFilter filter; private ClusterTopology topology; public FilteredClusterView(ClusterView parent, ClusterFilter filter) { assert parent != null : "Parent view is null."; assert filter != null : "Filter is null."; this.filter = filter; this.parent = parent; } @Override public ClusterView filterAll(ClusterFilter newFilter) { ArgAssert.notNull(newFilter, "Filter"); return new FilteredClusterView(this, newFilter); } @Override public ClusterTopology topology() { ClusterTopology parentTopology = parent.topology(); ClusterTopology cached = this.topology; if (cached == null || cached.version() < parentTopology.version()) { this.topology = cached = parentTopology.filterAll(filter); } return cached; } @Override public void addListener(ClusterEventListener listener) { ArgAssert.notNull(listener, "Listener"); parent.addListener(new FilteredClusterListener(filter, listener, Collections.emptySet())); } @Override public void addListener(ClusterEventListener listener, ClusterEventType... eventTypes) { ArgAssert.notNull(listener, "Listener"); Set<ClusterEventType> eventTypesSet; if (eventTypes != null && eventTypes.length > 0) { eventTypesSet = EnumSet.copyOf(Arrays.asList(eventTypes)); } else { eventTypesSet = Collections.emptySet(); } parent.addListener(new FilteredClusterListener(filter, listener, eventTypesSet)); } @Override public void removeListener(ClusterEventListener listener) { parent.removeListener(new FilteredClusterListener(filter, listener, Collections.emptySet())); } @Override public CompletableFuture<ClusterTopology> futureOf(Predicate<ClusterTopology> predicate) { return parent.futureOf(topology -> predicate.test(topology.filterAll(filter))); } @Override public boolean awaitFor(Predicate<ClusterTopology> predicate) { return parent.awaitFor(topology -> predicate.test(topology.filterAll(filter))); } @Override public boolean awaitFor(Predicate<ClusterTopology> predicate, long timeout, TimeUnit timeUnit) { return parent.awaitFor(topology -> predicate.test(topology.filterAll(filter))); } @Override public String toString() { // Update cache. topology(); return ToString.format(this); } }
32.090164
101
0.714432
5ac899b3489390bcbc5f4e39ad6b4aa4e229cd5d
904
package com.nitorcreations.willow.sshagentauth; import static com.nitorcreations.willow.sshagentauth.SSHUtil.printBase64Binary; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.jcraft.jsch.Identity; public abstract class AbstractSSHAuthentication implements SSHAuthentication { private static Logger logger = Logger.getLogger(AbstractSSHAuthentication.class.getCanonicalName()); public String getSshSignatures(byte[] sign, List<Identity> identities) { StringBuilder ret = new StringBuilder(); for (Identity id : identities) { try { byte[] sig = id.getSignature(sign); if (sig != null) { ret.append(" ").append(printBase64Binary(sig)); } } catch (Exception t) { logger.log(Level.FINE, "Failed to add signature: " + t.getMessage()); } } return ret.toString(); } }
28.25
102
0.701327
3575153bb499942960fe6889b65e603e2fc2416b
2,542
package com.airmap.geofencingsdkexample.util; import android.support.annotation.Nullable; import android.support.v7.util.DiffUtil; import com.airmap.geofencingsdk.status.GeofencingStatus; import java.util.List; public class DiffStatusCallback extends DiffUtil.Callback { @Nullable private List<GeofencingStatus> oldStatuses; @Nullable private List<GeofencingStatus> newStatuses; public DiffStatusCallback(@Nullable List<GeofencingStatus> oldStatuses, @Nullable List<GeofencingStatus> newStatuses) { this.oldStatuses = oldStatuses; this.newStatuses = newStatuses; } @Override public int getOldListSize() { return oldStatuses != null ? oldStatuses.size() : 0; } @Override public int getNewListSize() { return newStatuses != null ? newStatuses.size() : 0; } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { if (oldStatuses == null || newStatuses == null) { return false; } if (oldStatuses.get(oldItemPosition).airspace == null || newStatuses.get(newItemPosition).airspace == null) { return false; } return oldStatuses.get(oldItemPosition).airspace.equals(newStatuses.get(newItemPosition).airspace); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { if (oldStatuses == null || newStatuses == null) { return false; } GeofencingStatus oldStatus = oldStatuses.get(oldItemPosition); GeofencingStatus newStatus = newStatuses.get(newItemPosition); if (oldStatus.airspace == null || newStatus.airspace == null) { return false; } // check airspace matches if (!oldStatus.airspace.equals(newStatus.airspace)) { return false; } // check status hasn't changed if (oldStatus.level != newStatus.level) { return false; } if (oldStatus.proximity == null && newStatus.proximity == null) { return true; } // check proximity hasn't changed return oldStatus.proximity != null && newStatus.proximity != null && oldStatus.proximity.equals(newStatus.proximity); } @Nullable @Override public Object getChangePayload(int oldItemPosition, int newItemPosition) { // Implement method if you're going to use ItemAnimator return super.getChangePayload(oldItemPosition, newItemPosition); } }
30.261905
125
0.662077
14f0dec6dc4708d8e9b0d5207316bd3a015560e8
397
package sigmobile.sigapp.sigproc; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import sigmobile.sigapp.R; public class NotificationView extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification_view); } }
26.466667
64
0.738035
ea4eb26e6a5712e452fed4a06499c3ff4d16d898
452
package net; import net.aE2; import net.asJ; import net.minecraft.client.model.ModelBiped; import net.optifine.PlayerConfiguration; public class hE { public static void a(ModelBiped var0, asJ var1, float var2, float var3) { aE2.a(var0, var1, var2, var3); } public static PlayerConfiguration a(asJ var0) { return aE2.a(var0); } public static void a(String var0, PlayerConfiguration var1) { aE2.a(var0, var1); } }
21.52381
76
0.692478
e799de4fc6c93098e802090c1ef871a3463b5cd3
1,191
/** * Copyright (c) 2011 Terracotta, Inc. * Copyright (c) 2011 Oracle and/or its affiliates. * * All rights reserved. Use is subject to license terms. */ /** This package contains event listener interfaces. These may be registered for callback notification of the cache events. The specific interface should be implemented for each event type a callback is desired on. <p/> Event notifications occur synchronously in the line of execution of the calling thread. The calling thread blocks until the listener has completed execution or thrown a {@link CacheEntryListenerException}. <p/> Listeners are invoked <strong>after</strong> the cache is updated. If the listener throws an {@link CacheEntryListenerException} this will propagate back to the caller but it does not affect the cache update as it already completed before the listener was called. If the cache is transactional, transactions must commit <strong>before</strong> listeners are called. If an exception is thrown by a listener this does not affect the transaction as the transaction has already completed. <p/> @author Greg Luck @author Yannis Cosmadopoulos @since 1.0 */ package javax.cache.event;
41.068966
118
0.775819
448a5d5ec11f15c0b109238bcddd6d30d802b9b7
2,526
/* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/StringPart.java,v 1.11 2004/04/18 23:51:37 jsdever Exp $ * $Revision: 480424 $ * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ * * ==================================================================== * * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package com.android.internal.http.multipart; public class StringPart extends com.android.internal.http.multipart.PartBase { public StringPart(java.lang.String name, java.lang.String value, java.lang.String charset) { super((java.lang.String)null,(java.lang.String)null,(java.lang.String)null,(java.lang.String)null); throw new RuntimeException("Stub!"); } public StringPart(java.lang.String name, java.lang.String value) { super((java.lang.String)null,(java.lang.String)null,(java.lang.String)null,(java.lang.String)null); throw new RuntimeException("Stub!"); } protected void sendData(java.io.OutputStream out) throws java.io.IOException { throw new RuntimeException("Stub!"); } protected long lengthOfData() { throw new RuntimeException("Stub!"); } public void setCharSet(java.lang.String charSet) { throw new RuntimeException("Stub!"); } public static final java.lang.String DEFAULT_CHARSET = "US-ASCII"; public static final java.lang.String DEFAULT_CONTENT_TYPE = "text/plain"; public static final java.lang.String DEFAULT_TRANSFER_ENCODING = "8bit"; }
57.409091
232
0.72407
9e6bac6d68a1bcd4f7da6a5071cb30340f64566e
3,420
package driver; import backend.CodeGenManager; import frontend.SysYLexer; import frontend.SysYParser; import frontend.Visitor; import ir.MyModule; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.logging.Logger; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.tree.ParseTree; import pass.PassManager; import util.Mylogger; /** * 编译器驱动部分 */ public class CompilerDriverRaw { /** * @param args:从命令行未处理直接传过来的参数 */ private static Logger logger; public static void run(String[] args) { Mylogger.init(); Config config = Config.getInstance(); PassManager pm = PassManager.getPassManager(); var cmds = Arrays.asList(args); String source = null; String target = null; var iter = cmds.iterator(); iter.next(); // ignore [compiler] while (iter.hasNext()) { String cmd = iter.next(); if (cmd.equals("-o")) { target = iter.next(); continue; } if (cmd.equals("-O2")) { Config.getInstance().isO2 = true; } if (cmd.endsWith(".sy")) { source = cmd; } } // Config.getInstance().isO2 = false; assert source != null; assert target != null; try { Mylogger.init(); CharStream input = CharStreams.fromFileName(source); SysYLexer lexer = new SysYLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); SysYParser parser = new SysYParser(tokens); ParseTree tree = parser.program(); MyModule.getInstance().init(); Visitor visitor = new Visitor(/* OptionsTable table */); visitor.visit(tree); pm.openedPasses_.add("bbPredSucc"); pm.openedPasses_.add("Mem2reg"); pm.openedPasses_.add("RegAlloc"); pm.openedPasses_.add("gvngcm"); pm.openedPasses_.add("interproceduralAnalysis"); if (Config.getInstance().isO2) { // pm.openedPasses_.add("gvlocalize"); pm.openedPasses_.add("branchOptimization"); pm.openedPasses_.add("emitllvm"); pm.openedPasses_.add("deadcodeemit"); pm.openedPasses_.add("funcinline"); pm.openedPasses_.add("interproceduraldce"); pm.openedPasses_.add("markConstantArray"); pm.openedPasses_.add("ListScheduling"); pm.openedPasses_.add("Peephole"); pm.openedPasses_.add("CondExec"); pm.openedPasses_.add("loopInfoFullAnalysis"); pm.openedPasses_.add("LCSSA"); pm.openedPasses_.add("loopUnroll"); pm.openedPasses_.add("constantLoopUnroll"); pm.openedPasses_.add("MergeMachineBlock"); pm.openedPasses_.add("redundantLoop"); pm.openedPasses_.add("loopIdiom"); pm.openedPasses_.add("loopMergeLastBreak"); pm.openedPasses_.add("promotion"); pm.openedPasses_.add("loopFusion"); } pm.runIRPasses(MyModule.getInstance()); CodeGenManager cgm = CodeGenManager.getInstance(); cgm.load(MyModule.getInstance()); cgm.MachineCodeGeneration(); pm.runMCPasses(CodeGenManager.getInstance()); File f = new File(target); FileWriter fw = new FileWriter(f); fw.append(cgm.genARM()); fw.append("@ver: final-1"); fw.close(); } catch (IOException e) { e.printStackTrace(); } } }
28.983051
62
0.65117
07f404bd6fcbcb834bd9ed8cdc3971b74190173e
1,716
package com.wealth.wealthusers.controller; import com.wealth.wealthusers.common.LogUtil; import com.wealth.wealthusers.common.MyUtil; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; @RestController public class RootController { @GetMapping("/") private String root () { return "Welcome User!!!!"; } int i = 1; @GetMapping("/latencyCheck") private String latencyCheck() { System.out.println("latency check ... started"); MyUtil.sleepForSomeTime(); System.out.println("latency check ... completed") ; return "latencyCheck success"; } @GetMapping("/errorCheck") private String errorCheck() { System.out.println("error check ... started"); if (i==1) { i = 2 ; throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Not Found .......", new Exception("")); } else if (i==2) { i = 3; throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Bad Request .......", new Exception("")); } else if (i==3) { i = 4; throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "Bad Gateway ......", new Exception("")); } else if (i==4) { i = 5; throw new ResponseStatusException(HttpStatus.CONFLICT, "Conflict .....", new Exception("")); } else if (i==5) { i = 6; throw new ResponseStatusException(HttpStatus.GATEWAY_TIMEOUT, "Gateway timeout .......", new Exception("")); } else { i = 1; } return "errorCheck success"; } }
30.105263
120
0.596154
31db27a75d0bdbc70dee2119a9be475211a44fe3
2,704
package com.huaweicloud.sdk.dli.v1; import com.huaweicloud.sdk.core.ClientBuilder; import com.huaweicloud.sdk.core.HcClient; import com.huaweicloud.sdk.core.invoker.AsyncInvoker; import com.huaweicloud.sdk.dli.v1.model.*; import java.util.concurrent.CompletableFuture; public class DliAsyncClient { protected HcClient hcClient; public DliAsyncClient(HcClient hcClient) { this.hcClient = hcClient; } public static ClientBuilder<DliAsyncClient> newBuilder() { return new ClientBuilder<>(DliAsyncClient::new); } /** 创建队列 该API用于创建队列,该队列将会绑定用户指定的计算资源。 * * @param CreateQueueRequest 请求对象 * @return CompletableFuture<CreateQueueResponse> */ public CompletableFuture<CreateQueueResponse> createQueueAsync(CreateQueueRequest request) { return hcClient.asyncInvokeHttp(request, DliMeta.createQueue); } /** 创建队列 该API用于创建队列,该队列将会绑定用户指定的计算资源。 * * @param CreateQueueRequest 请求对象 * @return AsyncInvoker<CreateQueueRequest, CreateQueueResponse> */ public AsyncInvoker<CreateQueueRequest, CreateQueueResponse> createQueueAsyncInvoker(CreateQueueRequest request) { return new AsyncInvoker<CreateQueueRequest, CreateQueueResponse>(request, DliMeta.createQueue, hcClient); } /** 删除队列 该API用于删除指定队列。 说明: 若指定队列正在执行任务,则不允许删除。 * * @param DeleteQueueRequest 请求对象 * @return CompletableFuture<DeleteQueueResponse> */ public CompletableFuture<DeleteQueueResponse> deleteQueueAsync(DeleteQueueRequest request) { return hcClient.asyncInvokeHttp(request, DliMeta.deleteQueue); } /** 删除队列 该API用于删除指定队列。 说明: 若指定队列正在执行任务,则不允许删除。 * * @param DeleteQueueRequest 请求对象 * @return AsyncInvoker<DeleteQueueRequest, DeleteQueueResponse> */ public AsyncInvoker<DeleteQueueRequest, DeleteQueueResponse> deleteQueueAsyncInvoker(DeleteQueueRequest request) { return new AsyncInvoker<DeleteQueueRequest, DeleteQueueResponse>(request, DliMeta.deleteQueue, hcClient); } /** 查询所有队列 该API用于列出该project下所有的队列。 * * @param ListQueuesRequest 请求对象 * @return CompletableFuture<ListQueuesResponse> */ public CompletableFuture<ListQueuesResponse> listQueuesAsync(ListQueuesRequest request) { return hcClient.asyncInvokeHttp(request, DliMeta.listQueues); } /** 查询所有队列 该API用于列出该project下所有的队列。 * * @param ListQueuesRequest 请求对象 * @return AsyncInvoker<ListQueuesRequest, ListQueuesResponse> */ public AsyncInvoker<ListQueuesRequest, ListQueuesResponse> listQueuesAsyncInvoker(ListQueuesRequest request) { return new AsyncInvoker<ListQueuesRequest, ListQueuesResponse>(request, DliMeta.listQueues, hcClient); } }
38.084507
118
0.752219
e990437786609ad95cd9e7d79dda7327c4101c15
2,234
/** * Project: Blume * * Blume is a simple interface for producing ANSI 8-bit and 24-bit colored text with * foreground and background color options and various display attributes. * * @file OSIncompatibilityException.java * @version 1.1.0 * * @author Allen Vanderlinde * @date 6/28/2018 * * @copyright * * MIT License * * Copyright (c) 2018 Allen Vanderlinde * * 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 blume; /** * Blume exception thrown when a Blume operation is performed * on an incompatible operating system. */ @SuppressWarnings("serial") public class OSIncompatibilityException extends Exception { /** * Prints a basic stack trace with no special message. */ @Override public void printStackTrace() { super.printStackTrace(); } /** * Prints a stack trace with a special message first about incompatibility. * * @param msg */ public void printStackTrace( String msg ) { StackTraceElement[] trace = super.getStackTrace(); System.out.println( this.toString() + ": " + msg ); for ( int i = 0; i < trace.length; i++ ) { System.out.println( "\t" + trace[i] ); } } }
34.369231
130
0.704118
9feb2239bbc3e0b9cd4093bdb4005ed84263922d
1,389
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.stunner.core.graph.processing.index.bounds; public interface BoundsIndexer<C, T> { /** * Builds a index of all the visible graph elements bounds for a given context ( usually a canvas or canvas handler ). */ BoundsIndexer<C, T> build( C context ); /** * Return the graph element at the given x,y cartesian coordinate. */ T getAt( double x, double y ); /** * Determines a rectangle area which area is given as: * - the top left position of the graph element found nearer to this position. * - the bottom right position of the graph element found nearer to this position. */ double[] getTrimmedBounds(); /** * Destroy this index. */ void destroy(); }
31.568182
122
0.688985
a14e1abec54b54f6f269ea7e073fe32e51d58844
6,386
/* * Copyright 2020 OPPO ESA Stack 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 esa.restlight.core.interceptor; import esa.restlight.core.DeployContext; import esa.restlight.core.config.RestlightOptions; import esa.restlight.core.util.InterceptorUtils; import esa.restlight.server.route.Mapping; import esa.restlight.server.route.Route; import esa.restlight.server.util.PathMatcher; import java.util.Arrays; import static esa.restlight.core.interceptor.HandlerInterceptor.PATTERN_FOR_ALL; class HandlerInterceptorWrap extends AbstractInterceptorWrap<HandlerInterceptor> { private final InterceptorPredicate predicate; private final int affinity; HandlerInterceptorWrap(HandlerInterceptor interceptor, DeployContext<? extends RestlightOptions> ctx, Route route) { super(interceptor); final Mapping mapping = route.mapping(); final String[] includes = InterceptorUtils.parseIncludesOrExcludes(ctx.options().getContextPath(), interceptor.includes()); final String[] excludes = InterceptorUtils.parseIncludesOrExcludes(ctx.options().getContextPath(), interceptor.excludes()); this.affinity = parseAffinity(mapping, includes, excludes); if (this.affinity < 0) { this.predicate = InterceptorPredicate.NEVER; } else if (this.affinity == 0) { this.predicate = InterceptorPredicate.ALWAYS; } else { this.predicate = new InterceptorPathPredicate(includes, excludes); } } private int parseAffinity(Mapping mapping, String[] includes, String[] excludes) { String[] patterns; // public static Affinity matchToPattern(InterceptorPathPredicate predicate, String[] patterns) { if (mapping.path() == null || (patterns = mapping.path()).length == 0) { return DETACHED; } else if (isMatchAll(includes, excludes)) { // ignore always matching predicate return ATTACHED; } else if (isMatchEmpty(includes, excludes)) { // ignore empty matching return DETACHED; } else if (certainlyMatchAll(patterns, excludes)) { // rule out if excludes will match to these patterns certainly return DETACHED; } else if (((excludes == null || excludes.length == 0) || neverIntersect(excludes, patterns)) && certainlyMatchAll(patterns, includes)) { // excludes must be empty, because excludes may contains a pattern that would be matched to the route // pattern. eg. route pattern: fo?, includes: fo?, excludes: foo // this includes will certainly match to these patterns. return ATTACHED; } else if (neverIntersect(includes, patterns)) { return DETACHED; } else { // we think it is expensive to match a request to a interceptor while this interceptor // is not always matched to this handler and there's pattern paths in includes or excludes int affinity = 1; if (includes != null) { for (String include : includes) { affinity += computeAffinity(include); } } if (excludes != null) { for (String exclude : excludes) { if (PathMatcher.isPattern(exclude)) { affinity += computeAffinity(exclude); } } } return affinity; } } private static boolean isMatchAll(String[] includes, String[] excludes) { return (excludes == null || excludes.length == 0) && (includes == null || containsAll(includes)); } private static boolean isMatchEmpty(String[] includes, String[] excludes) { return (includes != null && includes.length == 0) || (excludes != null && containsAll(excludes)); } private static boolean containsAll(String[] arr) { for (String include : arr) { if (PATTERN_FOR_ALL.equals(include)) { return true; } } return false; } private boolean neverIntersect(String[] includes, String[] patterns) { // rule out if includes will never match to these patterns certainly if (includes != null && includes.length > 0) { for (String include : includes) { if (Arrays.stream(patterns) .noneMatch(pattern -> PathMatcher.isPotentialIntersect(include, pattern))) { return true; } } } return false; } private boolean certainlyMatchAll(String[] patterns, String[] target) { boolean result = false; if (target != null && target.length > 0) { for (String value : target) { if (Arrays.stream(patterns) .allMatch(pattern -> PathMatcher.certainlyIncludes(value, pattern))) { result = true; } } } return result; } private int computeAffinity(String include) { int affinity = 0; if (PathMatcher.isPattern(include)) { affinity += 4; } // every wildcard char plus 2 affinity(affinity gonna to be lower) affinity += include.chars().map(c -> { if (PathMatcher.isWildcardChar((char) c)) { return 2; } return 0; }).sum(); return affinity; } @Override public InterceptorPredicate predicate() { return predicate; } @Override public int affinity() { return affinity; } }
37.564706
113
0.595991
4534dfc68410ea0e054808f35021da519967401e
2,592
/* * Copyright 2016 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling; import java.io.File; import java.io.IOException; import java.util.*; /** * @author Ivan Habernal */ public class Step7cReasonExplorer { @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { String inputDir = args[0]; Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); // for generating ConvArgStrict use this String prefix = "no-eq_DescendingScoreArgumentPairListSorter"; List<String> allReasons = new ArrayList<>(); Iterator<File> iterator = files.iterator(); while (iterator.hasNext()) { File file = iterator.next(); if (!file.getName().startsWith(prefix)) { iterator.remove(); } } for (File file : files) { List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools .getXStream().fromXML(file); for (AnnotatedArgumentPair argumentPair : argumentPairs) { String goldLabel = argumentPair.getGoldLabel(); // get gold reason statistics for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) { String label = assignment.getValue(); if (goldLabel.equals(label)) { allReasons.add(assignment.getReason()); } } } } // reproducibility Random r = new Random(1234); Collections.shuffle(allReasons, r); List<String> reasons = allReasons.subList(0, 200); Collections.sort(reasons); for (int i = 0; i < reasons.size(); i++) { System.out.printf(Locale.ENGLISH, "%d\t%s%n", i, reasons.get(i)); } } }
31.609756
104
0.623843
a451905b07cb1bfd2565517cbf9ce2ac28e1fb5d
819
package HackerblockPractise; // **************** total import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Elitmus_RollNoQuestion { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String arr = sc.nextLine(); //using String split function String[] words = arr.split(" "); System.out.println(Arrays.toString(words)); int n=arr.length(); sum(arr, n); } public static void sum(String arr, int n) { Collections.sort(arr); int min = Integer.MAX_VALUE; for (int i = 0; i < n - 1; i++) { int cmin = Math.abs(arr[i] - arr[i + 1]); min = Math.min(min, cmin); } if (min == 1) { System.out.println("yes"); } else { System.out.println("no"); } } }
22.75
52
0.579976
4fbc7ebe3f284bf15f94b7f4674a1f7fa381c4e9
5,094
package net.modificationstation.sltest.mixin; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.Minecraft; import net.minecraft.client.render.WorldRenderer; import net.minecraft.client.texture.TextureManager; import net.minecraft.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @Environment(EnvType.CLIENT) @Mixin(WorldRenderer.class) public class MixinWorldRenderer { @Shadow private TextureManager textureManager; @Shadow private Level level; @Shadow private Minecraft client; // @Inject(method = "renderSky(F)V", at = @At("HEAD"), cancellable = true) // private void endSky(float f, CallbackInfo ci) { // GL11.glDisable(GL11.GL_FOG); // GL11.glDisable(GL11.GL_ALPHA_TEST); // GL11.glEnable(GL11.GL_BLEND); // GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); // //RenderHelper.disableLighting(); // GL11.glDepthMask(false); // this.textureManager.bindTexture(this.textureManager.getTextureId("/assets/sltest/textures/skybox/sky6.png")); // Tessellator var21 = Tessellator.INSTANCE; // // for (int var22 = 0; var22 < 6; ++var22) { // GL11.glPushMatrix(); // // if (var22 == 1) { // this.textureManager.bindTexture(this.textureManager.getTextureId("/assets/sltest/textures/skybox/sky1.png")); // GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F); // } // // if (var22 == 2) { // this.textureManager.bindTexture(this.textureManager.getTextureId("/assets/sltest/textures/skybox/sky4.png")); // GL11.glRotatef(-90.0F, 1.0F, 0.0F, 0.0F); // } // // if (var22 == 3) { //// this.textureManager.bindTexture(this.textureManager.getTextureId("/assets/sltest/textures/skybox/sky2.png")); //// this.textureManager.bindTexture(this.textureManager.getTextureId(ExpandableTextureAtlas.STATION_GUI_ITEMS.spritesheet)); //// ((CustomAtlasProvider) ItemListener.testItem).getAtlas().of(ItemListener.testItem.getTexturePosition(0)).bindAtlas(); //// Atlases.getStationJsonModels().bindAtlas(); // this.textureManager.bindTexture(StationRenderAPI.getBakedModelManager().getAtlas(Atlases.GAME_ATLAS_TEXTURE).getGlId()); // GL11.glRotatef(180.0F, 1.0F, 0.0F, 0.0F); // } // // if (var22 == 4) { // this.textureManager.bindTexture(this.textureManager.getTextureId("/assets/sltest/textures/skybox/sky3.png")); // GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F); // } // // if (var22 == 5) { // this.textureManager.bindTexture(this.textureManager.getTextureId("/assets/sltest/textures/skybox/sky5.png")); // GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F); // } // // var21.start(); // //var21.colour(2631720); // //var21.colour(0xffffff); // // /*Vec3f light = level.method_279(client.viewEntity, f); // float l = (float) ((light.x + light.y + light.z) / 3); // var21.colour(l, l, l);*/ // // float light = level.dimension.lightTable[15 - level.field_202]; // var21.colour(light, light, light); // // if (var22 == 2) { // var21.vertex(-100.0D, -100.0D, -100.0D, 0.0D, 0.0D); // var21.vertex(-100.0D, -100.0D, 100.0D, 0.0D, -1.0D); // var21.vertex(100.0D, -100.0D, 100.0D, -1.0D, -1.0D); // var21.vertex(100.0D, -100.0D, -100.0D, -1.0D, 0.0D); // } else if (var22 == 3 || var22 == 5) { // var21.vertex(-100.0D, -100.0D, -100.0D, 1.0D, 0.0D); // var21.vertex(-100.0D, -100.0D, 100.0D, 0.0D, 0.0D); // var21.vertex(100.0D, -100.0D, 100.0D, 0.0D, 1.0D); // var21.vertex(100.0D, -100.0D, -100.0D, 1.0D, 1.0D); // } else if (var22 == 4) { // var21.vertex(-100.0D, -100.0D, -100.0D, 0.0D, 1.0D); // var21.vertex(-100.0D, -100.0D, 100.0D, 1.0D, 1.0D); // var21.vertex(100.0D, -100.0D, 100.0D, 1.0D, 0.0D); // var21.vertex(100.0D, -100.0D, -100.0D, 0.0D, 0.0D); // } else { // var21.vertex(-100.0D, -100.0D, -100.0D, 0.0D, 0.0D); // var21.vertex(-100.0D, -100.0D, 100.0D, 0.0D, 1.0D); // var21.vertex(100.0D, -100.0D, 100.0D, 1.0D, 1.0D); // var21.vertex(100.0D, -100.0D, -100.0D, 1.0D, 0.0D); // } //// var21.pos(-100.0D, -100.0D, -100.0D); //// var21.pos(-100.0D, -100.0D, 100.0D); //// var21.pos(100.0D, -100.0D, 100.0D); //// var21.pos(100.0D, -100.0D, -100.0D); // var21.draw(); // GL11.glPopMatrix(); // } // GL11.glEnable(GL11.GL_FOG); // GL11.glEnable(GL11.GL_ALPHA_TEST); // GL11.glDepthMask(true); // ci.cancel(); // } }
46.309091
140
0.559678
de9d0a827b2eff16d5140e98371b0190e1c3433b
613
package proyecto.cursos.spring.repository; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import proyecto.cursos.spring.entity.CursosModel; public interface CursosRepository extends CrudRepository<CursosModel, Integer> { @Query(value = "SELECT c FROM CursosModel c WHERE c.nomCurso = ?1") public List<CursosModel> buscarCursosPorNomCurso(String nomCurso); @Query(value = "SELECT c FROM CursosModel c WHERE c.nomCurso like CONCAT(?1, '%')") public List<CursosModel> buscarCursosLikeNomCurso(String nomCurso); }
30.65
84
0.797716
e797472a4f877844c6d40e7e4232f929a465d633
1,035
package com.compomics.spectrawl.gui.event; import com.google.common.base.Joiner; import java.util.List; /** * * @author Niels Hulstaert */ public class MessageEvent { private String messageTitle; private String message; private int messageType; public MessageEvent(String messageTitle, String message, int messageType) { this.messageTitle = messageTitle; this.message = message; this.messageType = messageType; } public MessageEvent(String messageTitle, List<String> messages, int messageType) { this.messageTitle = messageTitle; Joiner joiner = Joiner.on("\n"); String concatenatedMessage = joiner.join(messages); this.message = concatenatedMessage; this.messageType = messageType; } public String getMessageTitle() { return messageTitle; } public String getMessage() { return message; } public int getMessageType() { return messageType; } }
24.642857
87
0.642512
639b8e5f7bf2f74f7f422a2de116e5372da6addc
5,151
package com.bei.yd.ui.main.model.iml; import android.content.Context; import com.bei.yd.api.IApiConfig; import com.bei.yd.ui.main.api.MainFragmentApi; import com.bei.yd.ui.main.bean.AreaBean; import com.bei.yd.ui.main.bean.MainBean; import com.bei.yd.ui.main.bean.MainItemNewOrderBean; import com.bei.yd.ui.main.bean.UserInfoBean; import com.bei.yd.ui.main.model.MainModel; import com.bei.yd.ui.main.presenter.iml.MainPresenterImpl; import com.bei.yd.utils.RestAdapterUtils; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import static com.bei.yd.api.IApiConfig.BASE_URL; /** * 精彩景点 * MVP模式--->M模型 * * @author: yujin on 16/4/25. */ public class MainModelImpl implements MainModel, IApiConfig { private Context mContext; /** * MVP---> P层引用 */ private MainPresenterImpl mPresenter; public MainModelImpl(Context context, MainPresenterImpl presenter) { this.mContext = context; this.mPresenter = presenter; } /** * 新建工单 */ @Override public void addNewWO(String arae, String account, String address, String phone, Subscriber<MainBean> callback) { MainFragmentApi api = RestAdapterUtils.getRestAPI(BASE_URL, MainFragmentApi.class); api.addNewWorkOrder(arae, account, address, phone) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(callback); } /** * 新建故障工单 */ @Override public void addFixWO(String arae, String account, String address, String phone, Subscriber<MainBean> callback) { MainFragmentApi api = RestAdapterUtils.getRestAPI(BASE_URL, MainFragmentApi.class); api.addFixWorkOrder(arae, account, address, phone) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(callback); } /** * 获取全部工单 */ @Override public void getAllNewWOList(String role, String account, int pageIndex, Subscriber<MainItemNewOrderBean> callback) { MainFragmentApi api = RestAdapterUtils.getRestAPI(BASE_URL, MainFragmentApi.class); api.getAllNewWorkOrderList(role, account, pageIndex, PAGESIZE) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(callback); } @Override public void login(String userName, String passWord, Subscriber<UserInfoBean> callback) { MainFragmentApi api = RestAdapterUtils.getRestAPI(BASE_URL, MainFragmentApi.class); api.login(userName, passWord) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(callback); } @Override public void getArea(Subscriber<AreaBean> callback) { MainFragmentApi api = RestAdapterUtils.getRestAPI(BASE_URL, MainFragmentApi.class); api.getArae() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(callback); } @Override public void statisticsWorkOrderList(String role, String account, int pageIndex, String area, String account_u, String phone, String dispatchtime, String taketime, String installtime, String overtime, String dispatchwarning, String installwarning, String visitwarning, String repeatnum, String iscancel, String isend, Subscriber<MainItemNewOrderBean> callback) { MainFragmentApi api = RestAdapterUtils.getRestAPI(BASE_URL, MainFragmentApi.class); api.statisticsWorkOrderList(role, account, pageIndex, PAGESIZE, area, account_u, phone, dispatchtime, taketime, installtime, overtime, dispatchwarning, installwarning, visitwarning,repeatnum,iscancel,isend) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(callback); } @Override public void statisticsSingleFault(String role, String account, int pageIndex, String area, String account_u, String phone, String dispatchtime, String taketime, String installtime, String overtime, String dispatchwarning, String installwarning, String visitwarning, String repeatnum, String iscancel, String isend, String dispatchwarning1, String dispatchwarning2, String dispatchtime21, String dispatchtime22, Subscriber<MainItemNewOrderBean> callback) { MainFragmentApi api = RestAdapterUtils.getRestAPI(BASE_URL, MainFragmentApi.class); api.statisticsSingleFault(role, account, pageIndex, PAGESIZE, area, account_u, phone, dispatchtime, taketime, installtime, overtime, dispatchwarning, installwarning, visitwarning,repeatnum,iscancel,isend,dispatchwarning1,dispatchwarning2,dispatchtime21,dispatchtime22) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(callback); } //@Override public void login(String ){ // Subscriber<MainItemNewOrderBean> callback) { // MainFragmentApi api = RestAdapterUtils.getRestAPI(BASE_URL, MainFragmentApi.class); // api.getAllNewWorkOrderList(role, account,pageIndex,PAGESIZE) // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(callback); //} }
39.930233
110
0.736944
8cb9ff4dc4a15e9b0f2b8498668046573ebb5e8b
5,874
package com.jnape.palatable.lambda.lens.lenses; import com.jnape.palatable.lambda.functions.builtin.fn2.Filter; import com.jnape.palatable.lambda.lens.Lens; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import static com.jnape.palatable.lambda.functions.builtin.fn2.Eq.eq; import static com.jnape.palatable.lambda.functions.builtin.fn2.Map.map; import static com.jnape.palatable.lambda.functions.builtin.fn2.ToCollection.toCollection; import static com.jnape.palatable.lambda.lens.Lens.lens; import static com.jnape.palatable.lambda.lens.Lens.simpleLens; import static com.jnape.palatable.lambda.lens.functions.View.view; import static com.jnape.palatable.lambda.lens.lenses.OptionalLens.unLiftA; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; /** * Lenses that operate on {@link Map}s. */ public final class MapLens { private MapLens() { } /** * A lens that focuses on a copy of a Map. Useful for composition to avoid mutating a map reference. * * @param <K> the key type * @param <V> the value type * @return a lens that focuses on copies of maps */ public static <K, V> Lens.Simple<Map<K, V>, Map<K, V>> asCopy() { return simpleLens(HashMap::new, (__, copy) -> copy); } /** * A lens that focuses on a value at a key in a map, as an {@link Optional}. * * @param k the key to focus on * @param <K> the key type * @param <V> the value type * @return a lens that focuses on the value at key, as an {@link Optional} */ public static <K, V> Lens<Map<K, V>, Map<K, V>, Optional<V>, V> valueAt(K k) { return lens(m -> Optional.ofNullable(m.get(k)), (m, v) -> { m.put(k, v); return m; }); } /** * A lens that focuses on a value at a key in a map, falling back to <code>defaultV</code> if the value is missing. * * @param k the key to focus on * @param defaultValue the default value to use in case of a missing value at key * @param <K> the key type * @param <V> the value type * @return a lens that focuses on the value at the key */ @SuppressWarnings("unchecked") public static <K, V> Lens.Simple<Map<K, V>, V> valueAt(K k, V defaultValue) { return unLiftA(valueAt(k), defaultValue)::apply; } /** * A lens that focuses on the keys of a map. * * @param <K> the key type * @param <V> the value type * @return a lens that focuses on the keys of a map */ public static <K, V> Lens.Simple<Map<K, V>, Set<K>> keys() { return simpleLens(Map::keySet, (m, ks) -> { Set<K> keys = m.keySet(); keys.retainAll(ks); ks.removeAll(keys); ks.forEach(k -> m.put(k, null)); return m; }); } /** * A lens that focuses on the values of a map. In the case of updating the map, only the entries with a value listed * in the update collection of values are kept. * * @param <K> the key type * @param <V> the value type * @return a lens that focuses on the values of a map */ public static <K, V> Lens.Simple<Map<K, V>, Collection<V>> values() { return simpleLens(Map::values, (m, vs) -> { Set<V> valueSet = new HashSet<>(vs); Set<K> matchingKeys = m.entrySet().stream() .filter(kv -> valueSet.contains(kv.getValue())) .map(Map.Entry::getKey) .collect(toSet()); m.keySet().retainAll(matchingKeys); return m; }); } /** * A lens that focuses on the inverse of a map (keys and values swapped). In the case of multiple equal values * becoming keys, the last one wins. * * @param <K> the key type * @param <V> the value type * @return a lens that focuses on the inverse of a map */ public static <K, V> Lens.Simple<Map<K, V>, Map<V, K>> inverted() { return simpleLens(m -> { Map<V, K> inverted = new HashMap<>(); m.entrySet().forEach(entry -> inverted.put(entry.getValue(), entry.getKey())); return inverted; }, (m, im) -> { m.clear(); m.putAll(view(inverted(), im)); return m; }); } /** * A lens that focuses on a map while mapping its values with the mapping function. * * @param fn the mapping function * @param <K> the key type * @param <V> the unfocused map value type * @param <V2> the focused map value type * @return a lens that focuses on a map while mapping its values */ public static <K, V, V2> Lens.Simple<Map<K, V>, Map<K, V2>> mappingValues(Function<? super V, ? extends V2> fn) { return Lens.simpleLens(m -> m.entrySet().stream().collect(toMap(Map.Entry::getKey, kv -> fn.apply(kv.getValue()))), (s, b) -> { //todo: remove this madness upon arrival of either invertible functions or Iso<V,V2> Set<K> retainKeys = Filter.<Map.Entry<K, V>>filter(kv -> eq(fn.apply(kv.getValue()), b.get(kv.getKey()))) .andThen(map(Map.Entry::getKey)) .andThen(toCollection(HashSet::new)) .apply(s.entrySet()); Map<K, V> copy = new HashMap<>(s); copy.keySet().retainAll(retainKeys); return copy; }); } }
38.644737
140
0.57031
2c0a629067be5ddf991098c06b6a09550b31a8f5
1,824
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.slicer; import javax.annotation.Nonnull; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiSubstitutor; import com.intellij.usages.TextChunk; import com.intellij.usages.UsagePresentation; import com.intellij.util.Processor; import consulo.ui.image.Image; /** * User: cdr */ public class SliceDereferenceUsage extends SliceUsage { public SliceDereferenceUsage(@Nonnull PsiElement element, @Nonnull SliceUsage parent, @Nonnull PsiSubstitutor substitutor) { super(element, parent, substitutor, 0, ""); } @Override public void processChildren(@Nonnull Processor<SliceUsage> processor) { // no children } @Nonnull @Override public UsagePresentation getPresentation() { final UsagePresentation presentation = super.getPresentation(); return new UsagePresentation() { @Override @Nonnull public TextChunk[] getText() { return presentation.getText(); } @Override @Nonnull public String getPlainText() { return presentation.getPlainText(); } @Override public Image getIcon() { return presentation.getIcon(); } @Override public String getTooltipText() { return "Variable dereferenced"; } }; } }
23.088608
123
0.730811
5022eedc5c8c487c56df577759b6dbd881857973
955
package com.imperva.ddc.core.exceptions; /** * Created by gabi.beyo on 3/6/2016. */ public class ProtocolException extends BaseException { private String reason = "Protocol Exception can be caused by malconfigured port address. Usually Port 389 is used for non-secured connections and Port 636 for secured connections"; public ProtocolException(String error, Throwable innerException){ super(error,innerException); } public ProtocolException(Throwable innerException){ super(innerException); } public ProtocolException(String error){ super(error); } public ProtocolException(String error, String reason, Throwable innerException){ super(error,innerException); this.setReason(reason); } public ProtocolException(String error, String reason){ super(error); this.setReason(reason); } public String getReason() { return reason; } }
26.527778
184
0.696335
0e60bf324d965972305471c095f5f6cba163fffe
3,027
/* Copyright 2022 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.kubernetes.client.openapi.models; import io.kubernetes.client.fluent.VisitableBuilder; public class V1ResourceRequirementsBuilder extends V1ResourceRequirementsFluentImpl<V1ResourceRequirementsBuilder> implements VisitableBuilder< V1ResourceRequirements, io.kubernetes.client.openapi.models.V1ResourceRequirementsBuilder> { public V1ResourceRequirementsBuilder() { this(false); } public V1ResourceRequirementsBuilder(Boolean validationEnabled) { this(new V1ResourceRequirements(), validationEnabled); } public V1ResourceRequirementsBuilder( io.kubernetes.client.openapi.models.V1ResourceRequirementsFluent<?> fluent) { this(fluent, false); } public V1ResourceRequirementsBuilder( io.kubernetes.client.openapi.models.V1ResourceRequirementsFluent<?> fluent, java.lang.Boolean validationEnabled) { this(fluent, new V1ResourceRequirements(), validationEnabled); } public V1ResourceRequirementsBuilder( io.kubernetes.client.openapi.models.V1ResourceRequirementsFluent<?> fluent, io.kubernetes.client.openapi.models.V1ResourceRequirements instance) { this(fluent, instance, false); } public V1ResourceRequirementsBuilder( io.kubernetes.client.openapi.models.V1ResourceRequirementsFluent<?> fluent, io.kubernetes.client.openapi.models.V1ResourceRequirements instance, java.lang.Boolean validationEnabled) { this.fluent = fluent; fluent.withLimits(instance.getLimits()); fluent.withRequests(instance.getRequests()); this.validationEnabled = validationEnabled; } public V1ResourceRequirementsBuilder( io.kubernetes.client.openapi.models.V1ResourceRequirements instance) { this(instance, false); } public V1ResourceRequirementsBuilder( io.kubernetes.client.openapi.models.V1ResourceRequirements instance, java.lang.Boolean validationEnabled) { this.fluent = this; this.withLimits(instance.getLimits()); this.withRequests(instance.getRequests()); this.validationEnabled = validationEnabled; } io.kubernetes.client.openapi.models.V1ResourceRequirementsFluent<?> fluent; java.lang.Boolean validationEnabled; public io.kubernetes.client.openapi.models.V1ResourceRequirements build() { V1ResourceRequirements buildable = new V1ResourceRequirements(); buildable.setLimits(fluent.getLimits()); buildable.setRequests(fluent.getRequests()); return buildable; } }
36.035714
100
0.779319
47598119c2d402c336e56c84503811c7770df572
2,831
/** * Copyright 2021 SPeCS. * * 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. under the License. */ package org.specs.MicroBlaze.instruction; import pt.up.fe.specs.binarytranslation.instruction.operand.AOperand; import pt.up.fe.specs.binarytranslation.instruction.operand.AOperandProperties; import pt.up.fe.specs.binarytranslation.instruction.operand.OperandAccessType; import pt.up.fe.specs.binarytranslation.instruction.operand.OperandDataSize; import pt.up.fe.specs.binarytranslation.instruction.operand.OperandDataType; import pt.up.fe.specs.binarytranslation.instruction.operand.OperandProperties; import pt.up.fe.specs.binarytranslation.instruction.operand.OperandType; import pt.up.fe.specs.binarytranslation.instruction.register.ExecutedImmediate; import pt.up.fe.specs.binarytranslation.instruction.register.ExecutedRegister; public class MicroBlazeOperand extends AOperand { private MicroBlazeOperand(OperandProperties props, ExecutedRegister readReg) { super(props, readReg); } /* * Copy constructor */ private MicroBlazeOperand(MicroBlazeOperand other) { super(other); } /* * public copy method */ @Override public MicroBlazeOperand copy() { return new MicroBlazeOperand(this); } public static MicroBlazeOperand newReadRegister(ExecutedRegister readReg) { var props = new AOperandProperties(readReg.getAsmField(), "r", "", OperandType.REGISTER, OperandAccessType.READ, OperandDataType.SCALAR_INTEGER, OperandDataSize.WORD); return new MicroBlazeOperand(props, readReg); } public static MicroBlazeOperand newWriteRegister(ExecutedRegister writeReg) { var props = new AOperandProperties(writeReg.getAsmField(), "r", "", OperandType.REGISTER, OperandAccessType.WRITE, OperandDataType.SCALAR_INTEGER, OperandDataSize.WORD); return new MicroBlazeOperand(props, writeReg); } public static MicroBlazeOperand newImmediate(ExecutedImmediate immVal) { var props = new AOperandProperties(immVal.getAsmField(), "0x", "", OperandType.IMMEDIATE, OperandAccessType.READ, OperandDataType.SCALAR_INTEGER, OperandDataSize.WORD); return new MicroBlazeOperand(props, immVal); } }
41.632353
118
0.740021
797c9ef0ecced1cf78f5a3f5e853368d47993de6
4,696
package com.edu.uj.sk.btcg.logic; import java.util.Iterator; import java.util.List; import java.util.Optional; import org.apache.commons.lang.StringUtils; import com.google.common.collect.Lists; public class Tokenizer { private static List<String> operators = Lists.newArrayList(">=", "<=", "==", "&&", "||", "!", "<", ">", "&", "|", "=", "!="); private static List<String> incorrectCharacters = Lists.newArrayList( ".", " ", "<", ">", "(", ")", "&", "%", "@", "#", "$", "^", "*", ",", "/", "?", ";", "[", "]", "{", "}", "\\", "|", "~", "`", "\"", "'", "!", "-" ); private static List<String> keywords = Lists.newArrayList( "return", "if", "class", "int", "double", "char", "String", "float", "Integer", "Double", "Float", "boolean", "Boolean", "switch", "case", "throws", "thorw", "for", "do", "volatile", "synchronized", "extends", "implements", "private", "public", "protected", "assert", "interface", "final", "static", "void", "instanceof" ); private Tokenizer() { } public static Tokenizer create() { return new Tokenizer(); } /** * Tokenize given expression * * @param expression nullable * @return Iterator of tokens */ Iterator<String> tokenize(String expression) { return new It(expression); } /** * Check if token is one of: * ">=", "<=", "==", "&&", * "||", "!", "<", ">", "&", "|", "=" * * @param token * @return true if token is an operator */ public boolean isOperator(String token) { return operators.contains(token); } /** * Check if token is left bracket ('(') * * @param token * @return true if token is a left bracket */ public boolean isLeftBracket(String token) { return "(".equals(token); } /** * Check if token is right bracket (')') * * @param token nullable * @return true if token is a right bracket */ public boolean isRightBracket(String token) { return ")".equals(token); } /** * Check if token is a number * * @param token * @return true if token is a number false otherwise, false if token is null */ public boolean isNumber(String token) { if (token == null) return false; return token.matches("^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$"); } /** * Check if given token is a variable * * @param token nullable * @return true if token is a variable */ public boolean isVariable(String token) { if (StringUtils.isBlank(token)) return false; if (token.matches("^[0-9].*")) return false; for (String c : incorrectCharacters) { if (token.contains(c)) return false; } if (isNumber(token)) return false; if (isOperator(token)) return false; if ("null".equals(token)) return false; for (String keyword : keywords) { if (keyword.equals(token)) return false; } return true; } /** * Check if BooleanExpressionNode holds a variable * * @param expressionNode * @return true if BooleanExpressionNode holds a variable */ public boolean isVarialbe(Optional<BooleanExpressionNode> expressionNode) { if (!expressionNode.isPresent()) return false; String value = expressionNode.get().getValue(); return isVariable(value); } private class It implements Iterator<String> { private String expression; public It(String expression) { if (StringUtils.isBlank(expression)) this.expression = ""; else { this.expression = expression.trim(); } } @Override public boolean hasNext() { return !expression.isEmpty(); } @Override public String next() { String token = ""; String first = getFirstCharacter(); if (isLeftBracket(first) || isRightBracket(first)) { token = first; } else if (operators.contains(first)) { token = first; String firstTwo = getFirstTwoCharacters(); if (operators.contains(firstTwo)) { token = firstTwo; } } else { int i = 0; String currentLetter = ""; while (true) { if (i >= expression.length()) break; currentLetter = expression.substring(i, ++i); if (isTokenEnd(currentLetter)) break; token += currentLetter; } } expression = expression.substring(token.length()).trim(); return token.trim(); } private String getFirstCharacter() { return expression.substring(0, 1); } private String getFirstTwoCharacters() { return expression.substring(0, 2); } private boolean isTokenEnd(String c) { if (c.equals(" ")) return true; if (operators.contains(c)) return true; if ("(".equals(c)) return true; if (")".equals(c)) return true; if (";".equals(c)) return true; return false; } } }
22.796117
83
0.596678
b86b1ca2050779be6e12bcb72660238a00e45ee9
284
package models; import java.util.List; public class EnvelopeDeProdutos { private List<Produto> produtos; public EnvelopeDeProdutos(List<Produto> produtos) { this.produtos = produtos; } public List<Produto> getProdutos() { return produtos; } }
16.705882
55
0.672535
11e82e65df2f2e2e4f5820a7d57e2d2bc3f9ccfb
3,627
package com.simibubi.create.content.contraptions.itemAssembly; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.simibubi.create.content.contraptions.processing.ProcessingOutput; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.util.GsonHelper; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.registries.ForgeRegistryEntry; public class SequencedAssemblyRecipeSerializer extends ForgeRegistryEntry<RecipeSerializer<?>> implements RecipeSerializer<SequencedAssemblyRecipe> { public SequencedAssemblyRecipeSerializer() {} protected void writeToJson(JsonObject json, SequencedAssemblyRecipe recipe) { JsonArray nestedRecipes = new JsonArray(); JsonArray results = new JsonArray(); json.add("ingredient", recipe.getIngredient().toJson()); recipe.getSequence().forEach(i -> nestedRecipes.add(i.toJson())); recipe.resultPool.forEach(p -> results.add(p.serialize())); json.add("transitionalItem", recipe.transitionalItem.serialize()); json.add("sequence", nestedRecipes); json.add("results", results); json.addProperty("loops", recipe.loops); } protected SequencedAssemblyRecipe readFromJson(ResourceLocation recipeId, JsonObject json) { SequencedAssemblyRecipe recipe = new SequencedAssemblyRecipe(recipeId, this); recipe.ingredient = Ingredient.fromJson(json.get("ingredient")); recipe.transitionalItem = ProcessingOutput.deserialize(GsonHelper.getAsJsonObject(json, "transitionalItem")); int i = 0; for (JsonElement je : GsonHelper.getAsJsonArray(json, "sequence")) recipe.getSequence().add(SequencedRecipe.fromJson(je.getAsJsonObject(), recipe, i++)); for (JsonElement je : GsonHelper.getAsJsonArray(json, "results")) recipe.resultPool.add(ProcessingOutput.deserialize(je)); if (GsonHelper.isValidNode(json, "loops")) recipe.loops = GsonHelper.getAsInt(json, "loops"); return recipe; } protected void writeToBuffer(FriendlyByteBuf buffer, SequencedAssemblyRecipe recipe) { recipe.getIngredient().toNetwork(buffer); buffer.writeVarInt(recipe.getSequence().size()); recipe.getSequence().forEach(sr -> sr.writeToBuffer(buffer)); buffer.writeVarInt(recipe.resultPool.size()); recipe.resultPool.forEach(sr -> sr.write(buffer)); recipe.transitionalItem.write(buffer); buffer.writeInt(recipe.loops); } protected SequencedAssemblyRecipe readFromBuffer(ResourceLocation recipeId, FriendlyByteBuf buffer) { SequencedAssemblyRecipe recipe = new SequencedAssemblyRecipe(recipeId, this); recipe.ingredient = Ingredient.fromNetwork(buffer); int size = buffer.readVarInt(); for (int i = 0; i < size; i++) recipe.getSequence().add(SequencedRecipe.readFromBuffer(buffer)); size = buffer.readVarInt(); for (int i = 0; i < size; i++) recipe.resultPool.add(ProcessingOutput.read(buffer)); recipe.transitionalItem = ProcessingOutput.read(buffer); recipe.loops = buffer.readInt(); return recipe; } public final void write(JsonObject json, SequencedAssemblyRecipe recipe) { writeToJson(json, recipe); } @Override public final SequencedAssemblyRecipe fromJson(ResourceLocation id, JsonObject json) { return readFromJson(id, json); } @Override public final void toNetwork(FriendlyByteBuf buffer, SequencedAssemblyRecipe recipe) { writeToBuffer(buffer, recipe); } @Override public final SequencedAssemblyRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf buffer) { return readFromBuffer(id, buffer); } }
40.3
111
0.783568
ffb611310c46b59b77c13aa4cc23a5920e59135c
1,153
package ca.cb.cc.cv; import android.content.Context; import android.graphics.Paint; import android.graphics.Typeface; import android.support.v4.util.LruCache; import android.text.TextPaint; import android.text.style.MetricAffectingSpan; //Copy pasted code public for custom font public class TypefaceSpan extends MetricAffectingSpan { private static final LruCache<String, Typeface> TYPEFACE_CACHE = new LruCache<String, Typeface>(12); private final Typeface typeface; public TypefaceSpan(Context context, String typefaceName) { Typeface t = TYPEFACE_CACHE.get(typefaceName); if (t == null) { t = Typeface.createFromAsset(context.getApplicationContext() .getAssets(), String.format("fonts/%s", typefaceName)); TYPEFACE_CACHE.put(typefaceName, t); } typeface = t; } @Override public void updateMeasureState(TextPaint p) { p.setTypeface(typeface); p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG); } @Override public void updateDrawState(TextPaint tp) { tp.setTypeface(typeface); tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG); } }
26.813953
73
0.718994
02bdc91a887feb1c223aa626e50011910f2f97c0
9,654
/* * Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.j_spaces.core.admin; import com.gigaspaces.internal.cluster.SpaceClusterInfo; import com.gigaspaces.internal.server.space.IClusterInfoChangedListener; import com.gigaspaces.internal.utils.StringUtils; import com.j_spaces.core.Constants; import com.j_spaces.core.JSpaceAttributes; import com.j_spaces.kernel.JSpaceUtilities; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.rmi.UnmarshalException; import java.util.Arrays; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * This structure contains all information about space configuration. <code>SpaceConfig</code> * builds inside of Server and transfered to the side of client. * * @author Igor Goldenberg * @version 1.0 * @see com.j_spaces.core.admin.IRemoteJSpaceAdmin#getConfig() **/ public class SpaceConfig extends JSpaceAttributes implements IClusterInfoChangedListener { private String _spaceName; private String _containerName; private String _fullSpaceName; private String _schemaPath = ""; private final ConcurrentMap extraProperties = new ConcurrentHashMap<String, Object>(); private static final long serialVersionUID = 1L; private static final int SERIAL_VERSION = 1; /** * */ public SpaceConfig() { super(); } /** * Creates SpaceConfig with the provided space name. * * @param spaceName the space name * @param containerName container owner name */ public SpaceConfig(String spaceName, String containerName) { _spaceName = spaceName; _containerName = containerName; _fullSpaceName = JSpaceUtilities.createFullSpaceName(_containerName, _spaceName); } /** * Creates SpaceConfig with the provided space name, using the given {@link java.util.Properties * Properties}. * * @param spaceName the space name * @param prop properties for the SpaceConfig * @param containerName container owner name * @param schemaPath path to space schema file */ public SpaceConfig(String spaceName, Properties prop, String containerName, String schemaPath) { super(prop); _spaceName = spaceName; _containerName = containerName; _schemaPath = schemaPath; _fullSpaceName = JSpaceUtilities.createFullSpaceName(_containerName, _spaceName); } @Override public SpaceConfig clone() { return (SpaceConfig) super.clone(); } /** * Returns the space name. * * @return the space name */ public String getSpaceName() { return _spaceName; } /** * Set the space name. * * @param spaceName the new space name */ public void setSpaceName(String spaceName) { _spaceName = spaceName; } public String getFullSpaceName() { return _fullSpaceName; } /** * Returns space schema file path * * @return path to space schema file ( including host IP address ) */ public String getSchemaPath() { return _schemaPath; } /** * Sets space schema file path * * @param schemaName path to space schema file ( including host IP address ) */ public void setSchemaPath(String schemaName) { _schemaPath = schemaName; } /** * {@inheritDoc} */ @Override public String getProperty(String key) { return super.getProperty(prepareProperty(key)); } @Override public String getProperty(String key, String defaultValue) { return super.getProperty(prepareProperty(key), defaultValue); } /** * {@inheritDoc} */ @Override public Object setProperty(String key, String value) { return super.setProperty(prepareProperty(key), value); } /** * Prepare a property adding the space name before the key. * * @param key is Xpath as following: Constants.SPACE_CONFIG_PREFIX + key * @return key with space name at the beginning of X path */ private String prepareProperty(String key) { if (!key.startsWith(Constants.SPACE_CONFIG_PREFIX)) { return key; } return (_fullSpaceName + '.' + key); } /** * Returns the property without using the space name. * * @param key the property key. * @return the value in this property list with the specified key value. */ public String getPropertyFromSuper(String key) { return super.getProperty(key); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\n\t ============================================================\n"); sb.append("\n\t Space configuration for space \"" + _fullSpaceName + "\" \n"); sb.append("\n\t ============================================================\n"); sb.append("\n\t DCache configuration \n\t "); sb.append(getDCacheProperties()); sb.append('\n'); sb.append("\n\t Cluster Info -\t"); sb.append(getClusterInfo()); sb.append('\n'); sb.append("\n\t Filters configuration -\t"); sb.append(Arrays.toString(getFiltersInfo())); sb.append('\n'); sb.append("\n\t Custom properties -\t "); StringUtils.appendProperties(sb, getCustomProperties()); sb.append('\n'); sb.append("\n---------------------------------------------------------------------------------------- \n"); sb.append("Space configuration elements for space < "); sb.append(_fullSpaceName); sb.append(" >"); sb.append("\n---------------------------------------------------------------------------------------- \n\n"); StringUtils.appendProperties(sb, this); return sb.toString(); } @Override public synchronized boolean containsKey(Object key) { //This method is implemented in such way ( by calling to getProperty()) //because method super.containsKey() does not affect for elements that //were added NOT by setProperty() method, but were added by calling //to constructor new Properties( prop ) String preparedKey = prepareProperty(key.toString()); return super.getProperty(preparedKey) == null ? false : true; } /** * Return container owner name * * @return container name */ public String getContainerName() { return _containerName; } @Override public void afterClusterInfoChange(SpaceClusterInfo clusterInfo) { this.setClusterInfo(clusterInfo); } /* Bit map for serialization */ private interface BitMap { byte _SPACENAME = 1 << 0; byte _CONTAINERNAME = 1 << 1; byte _FULLSPACENAME = 1 << 2; byte _SCHEMAPATH = 1 << 3; } private byte buildFlags() { byte flags = 0; if (_spaceName != null) flags |= BitMap._SPACENAME; if (_containerName != null) flags |= BitMap._CONTAINERNAME; if (_fullSpaceName != null) flags |= BitMap._FULLSPACENAME; if (_schemaPath != null) flags |= BitMap._SCHEMAPATH; return flags; } public ConcurrentMap getExtraProperties() { return extraProperties; } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); int version = in.readInt(); if (version != SERIAL_VERSION) throw new UnmarshalException("Class [" + getClass().getName() + "] received version [" + version + "] does not match local version [" + SERIAL_VERSION + "]. Please make sure you are using the same product version on both ends."); final byte flags = in.readByte(); if (flags == 0) return; if ((flags & BitMap._SPACENAME) != 0) _spaceName = (String) in.readObject(); if ((flags & BitMap._CONTAINERNAME) != 0) _containerName = (String) in.readObject(); if ((flags & BitMap._FULLSPACENAME) != 0) _fullSpaceName = (String) in.readObject(); if ((flags & BitMap._SCHEMAPATH) != 0) _schemaPath = (String) in.readObject(); } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeInt(SERIAL_VERSION); final byte flags = buildFlags(); out.writeByte(flags); if (flags == 0) return; if (_spaceName != null) { out.writeObject(_spaceName); } if (_containerName != null) { out.writeObject(_containerName); } if (_fullSpaceName != null) { out.writeObject(_fullSpaceName); } if (_schemaPath != null) { out.writeObject(_schemaPath); } } }
30.647619
241
0.614357
408d5b7f59708f2dfc4e2c9eaf9e2e1948119679
10,066
package com.hue.model.persist; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.Optional; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.InjectableValues.Std; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.Sets; import com.hue.model.Datasource; import com.hue.model.Dimension; import com.hue.model.Join; import com.hue.model.Measure; import com.hue.model.Project; import com.hue.model.Table; import com.hue.services.ServiceException; public class ProjectServices { private static final Logger logger = LoggerFactory.getLogger(ProjectServices.class.getName()); private static ProjectServices instance = null; private static ObjectMapper mapper; private final HueConfig config = new HueConfig(); private final Set<Schema> schemas = Sets.newConcurrentHashSet(); protected ProjectServices() { } public static ProjectServices getInstance() { if(instance == null) { instance = new ProjectServices(); mapper = new ObjectMapper(); mapper.registerModule(new HueSerDeModule()); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.enable(JsonParser.Feature.ALLOW_COMMENTS); mapper.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); mapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES); } return instance; } public HueConfig getConfig() { return config; } public Optional<Schema> getSchema(String projectName) { return schemas.stream().filter(s -> s.getProject().getName().equalsIgnoreCase(projectName)).findFirst(); } public Set<Schema> getSchemas(){ return schemas; } public void loadProjects() throws IOException { schemas.clear(); Files.list(FileSystems.getDefault() .getPath(config.getProjectsDirectory())) .map(p -> new File(p.toString()) ) .filter(f -> f.isDirectory() && PersistUtils.isValidProject(f.getName())) .forEach(f -> { try { logger.info("loading project " + f.getName()); File pjJson = new File(f.getPath()+"/project.json"); Project p = mapper.readValue(pjJson, Project.class); p.setFile(f); p.setName(f.getName()); Schema s = new Schema(p); schemas.add(s); loadDatasources(s); loadExpressibles(s); } catch (IOException e) { logger.error("Could not load project in " + f.getPath() + " \n" + e.getMessage()); e.printStackTrace(); } }); } private void loadDatasources(Schema s) throws IOException { logger.info("loading datasources from " + s.getProject().getFile().getPath()); Files.list(s.getProject().getFile().toPath()) .map(p -> new File(p.toString()) ) .filter(f -> { if(f.getName().equalsIgnoreCase("dimensions") || f.getName().equalsIgnoreCase("measures") || f.getName().equalsIgnoreCase("project.json")) { return false; } if(!f.isDirectory()) { logger.info("skipping " + f.getName() + ". Not a datasource directory."); return false; }else if(!PersistUtils.isValidDatasource(s.getProject().getName(), f.getName())){ logger.info("skipping " + f.getName() + ". Missing datasource.json file."); return false; }else { return true; } }).forEach(f -> { try { logger.info("loading datasource file " + f.getName() + " in project " + s.getProject().getName()); File pjJson = new File(f.getPath()+"/datasource.json"); Datasource ds = mapper.readValue(pjJson, Datasource.class); ds.setFile(f); ds.setName(f.getName()); s.addDatasource(ds); loadTables(s,ds); loadJoins(s,ds); logger.info("finished loading datasource " + ds.getName()); } catch (IOException e) { logger.error("Could not load project in " + f.getPath() + " \n" + e.getMessage()); } }); } private void loadTables(Schema s, Datasource ds) throws IOException { try { Files.list(FileSystems.getDefault().getPath(ds.getFile().toPath().toString(),"tables")) .map(p -> new File(p.toString()) ) .filter(p -> p.getName().toLowerCase().endsWith(".json")) .forEach(f -> { logger.info("\tloading table file " + f.getName() + " for ds " + ds.getName()); try { Table t = mapper.readValue(f, Table.class); t.setFile(f); String[] parts = f.getName().split("\\."); if(parts.length==2) { t.setName(parts[0]); }else if(parts.length>2) { t.setName(parts[parts.length-2]); } logger.info("\t\t- table name: " + t.getName()); s.addTable(ds, t); logger.info("\tsucceeded"); } catch (IOException e) { logger.error("\tfailed - " + e.getMessage()); } }); } catch (IOException e) { logger.warn("no tables found for " + ds.getName() + "\n" + e.getMessage()); Files.createDirectories(FileSystems.getDefault().getPath(ds.getFile().toPath().toString(),"tables")); } } private void loadJoins(Schema s, Datasource ds) throws IOException { Std inj = new InjectableValues.Std().addValue("schema", s); inj.addValue("datasource", ds); try { Files.list(FileSystems.getDefault().getPath(ds.getFile().toPath().toString(),"joins")) .map(p -> new File(p.toString()) ) .filter(p -> p.getName().toLowerCase().endsWith(".json")) .forEach(f -> { logger.info("\tloading join file " + f.getName() + " for ds " + ds.getName()); try { Join j = mapper.setInjectableValues(inj).readValue(f, Join.class); j.setFile(f); logger.info("\t\t- join: " + j.getName()); s.addJoin(ds, j); logger.info("\tsucceeded"); } catch (IOException e) { logger.error("\tfailed - " + e.getMessage()); } }); } catch (IOException e) { logger.warn("no joins found for " + ds.getName() + "\n" + e.getMessage()); Files.createDirectories(FileSystems.getDefault().getPath(ds.getFile().toPath().toString(),"joins")); } } private void loadExpressibles(Schema s) throws IOException { Std inj = new InjectableValues.Std().addValue("schema", s); logger.info("loading dimensions from " + s.getProject().getFile().getPath()); try { Files.list(FileSystems.getDefault().getPath(s.getProject().getFile().toPath().toString(),"dimensions")) .map(p -> new File(p.toString()) ) .filter(p -> p.getName().toLowerCase().endsWith(".json")) .forEach(f -> { logger.info("\tloading dimension file " + f.getName() + " for project " + s.getProject().getName()); try { Dimension d = mapper.setInjectableValues(inj).readValue(f, Dimension.class); d.setFile(f); d.setName(f.getName().split("\\.")[0]); logger.info("\t\t- dimension: " + d.getName()); s.addDimension(d); logger.info("\tsucceeded"); } catch (IOException e) { logger.error("\tfailed - " + e.getMessage()); } }); } catch (IOException e) { logger.warn("no dimensions found for " + s.getProject().getName() + "\n" + e.getMessage()); Files.createDirectories(FileSystems.getDefault().getPath(s.getProject().getFile().toPath().toString(),"dimensions")); } logger.info("finished loading dimensions from " + s.getProject().getFile().getPath()); logger.info("loading measures from " + s.getProject().getFile().getPath()); try { Files.list(FileSystems.getDefault().getPath(s.getProject().getFile().toPath().toString(),"measures")) .map(p -> new File(p.toString()) ) .filter(p -> p.getName().toLowerCase().endsWith(".json")) .forEach(f -> { logger.info("\tloading measure file " + f.getName() + " for project " + s.getProject().getName()); try { Measure d = mapper.setInjectableValues(inj).readValue(f, Measure.class); d.setFile(f); d.setName(f.getName().split("\\.")[0]); logger.info("\t\t- meaure: " + d.getName()); s.addMeasure(d); logger.info("\tsucceeded"); } catch (IOException e) { logger.error("\tfailed - " + e.getMessage()); } }); } catch (IOException e) { logger.warn("no measures found for " + s.getProject().getName() + "\n" + e.getMessage()); Files.createDirectories(FileSystems.getDefault().getPath(s.getProject().getFile().toPath().toString(),"measures")); } logger.info("finished loading measures from " + s.getProject().getFile().getPath()); } public void save(Schema s, Datasource datasource, Table t) throws ServiceException { try { if(t.getFile() == null) { t.setFile(new File(datasource.getFile().toString()+"/tables/"+ String.join(".", t.getPhysicalNameSegments()) +".json")); } mapper.writeValue(t.getFile(), t); } catch (IOException e) { throw new ServiceException("Unable to save: \n" + e.getMessage()); } } public void save(Schema s, Datasource datasource, Join j) throws ServiceException { try { if(j.getFile() == null) { j.setFile(new File(datasource.getFile().toString()+"/joins/"+ j.getName() +".json")); } mapper.writeValue(j.getFile(), j); } catch (IOException e) { throw new ServiceException("Unable to save: \n" + e.getMessage()); } } public void save(Schema s, Dimension d) throws ServiceException { try { if(d.getFile() == null) { d.setFile(new File(s.getProject().getFile().toString()+"/dimensions/"+ d.getName() +".json")); } mapper.writeValue(d.getFile(), d); } catch (IOException e) { throw new ServiceException("Unable to save: \n" + e.getMessage()); } } public void save(Schema s, Measure msr) throws ServiceException { try { if(msr.getFile() == null) { msr.setFile(new File(s.getProject().getFile().toString()+"/measures/"+ msr.getName() +".json")); } mapper.writeValue(msr.getFile(), msr); } catch (IOException e) { throw new ServiceException("Unable to save: \n" + e.getMessage()); } } }
35.822064
124
0.643155
2a87cb082231708dcbfde43f0494529be9db63a9
525
package org.testcontainers.images.builder.dockerfile.traits; import org.testcontainers.images.builder.dockerfile.statement.SingleArgumentStatement; import org.testcontainers.utility.DockerImageName; public interface FromStatementTrait<SELF extends FromStatementTrait<SELF> & DockerfileBuilderTrait<SELF>> { default SELF from(String dockerImageName) { new DockerImageName(dockerImageName).assertValid(); return ((SELF) this).withStatement(new SingleArgumentStatement("FROM", dockerImageName)); } }
37.5
107
0.8
bdd8f43a593c6455920e4426bd6750addebd18b6
430
package me.maximumpower55.mecha; import me.maximumpower55.mecha.data.recipe.InfusingRecipe; import net.minecraft.core.Registry; public class ModRecipeSerializers { public static final InfusingRecipe.Serializer INFUSING_RECIPE_SERIALIZER = new InfusingRecipe.Serializer(); public static void register() { Registry.register(Registry.RECIPE_SERIALIZER, MechaMod.id("infuser"), INFUSING_RECIPE_SERIALIZER); } }
33.076923
111
0.795349
e2ec82a776c71b85b30daa3adb4f5c1615c0d5fe
2,219
package game.world; import static java.lang.Math.*; import static util.MathUtil.*; import static game.world.World.*; import game.block.*; import java.util.*; import game.entity.*; import game.item.*; import game.world.StatMode.StatResult; public class PvPMode extends GameMode{ private static final long serialVersionUID=1844677L; private static double[] prob_of_energy={ 0.30, 0.20, 0.20, 0.20, 0.10, }; @Override public boolean forceOnline(){return true;} private transient StatResult result=null; public StatResult getStat(){ if(result==null){ result=StatMode.restore("v2.dat"); } return result; } int getWorldWidth(){return 256;} double[] getWeatherProb(){ return prob_of_energy; } int resourceRate(){ return 8; } void newWorld(World world){} long time=0; void update(Chunk chunk){ if(World.cur.time>time){ time=World.cur.time; int online_cnt=0; for(Player pl:World.cur.getPlayers()){ if(pl.online)++online_cnt; } if(online_cnt>0) for(Player pl:World.cur.getPlayers()){ if(pl.online) if(rnd()<0.005/online_cnt){ double rx=World.cur.getRelX(pl.x); if(rx>0&&rx<1){ new GoldParticle().drop(pl.x+rnd_gaussion(),rnd(pl.y-pl.height(),World.cur.getMaxY()+1)); } } } } } @Override void initPlayer(Player player){ super.initPlayer(player); player.money=0; } public void onPlayerDead(Player w){ w.dropArmor(); double x=Math.max(0,w.getPrice(getStat())); x=((x/1e3)/(1+x/1e3))*(0.3*x); Item i1=new GoldParticle(); Item i2=new Gold(); Item i3=new GoldBlock(); double p1=i1.getPrice(getStat(),false); double p2=i2.getPrice(getStat(),false); double p3=i3.getPrice(getStat(),false); int n3=Math.max(0,Math.min(99,(int)(x/p3))); x-=p3*n3; int n2=Math.max(0,Math.min(99,(int)(x/p2))); x-=p2*n2; int n1=Math.max(0,Math.min(99,(int)(x/p1))); x-=p1*n1; w.money-=p1*n1+p2*n2+p3*n3; if(n1>0)i1.drop(w.x,w.y,n1); if(n2>0)i2.drop(w.x,w.y,n2); if(n3>0)i3.drop(w.x,w.y,n3); if(w.money<0){ w.forceSell(getStat()); } } public void onZombieDead(Zombie w){} public void onPlayerRespawn(Player player){ super.onPlayerRespawn(player); randomRespawn(player); } }
21.543689
95
0.658405
b5b9c4b65862fd846d35153db0e480c016984fe3
1,390
/** * Copyright (c) 2020 kedacom * OpenATC is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. **/ package com.openatc.agent.model; //import com.kedacom.openatc.kdagent.utils.JsonbType; import lombok.Data; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import javax.persistence.*; import java.util.Date; @Data @Entity @Table(name = "t_permission") //@TypeDef(name = "JsonbType", typeClass = JsonbType.class) public class Permission { @Id @GeneratedValue private int id; @Column private String permission_code; @Column private String description; @Column private short status; @Column(nullable = false) private String ext_infos; @Temporal(TemporalType.TIMESTAMP) @CreationTimestamp @Column(nullable = false) private Date create_time; @UpdateTimestamp @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false) private Date update_time; }
25.272727
87
0.730935
9f6db7d7623c1165e4753f11881f21805b76f185
2,855
package com.sohu.cache.util; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.sohu.cache.entity.DbOperate; import com.sohu.cache.entity.InstanceInfo; import com.sohu.cache.entity.InstanceStats; import sun.misc.BASE64Encoder; /** * jackson转换工具 * @author leifu * @Date 2016年3月23日 * @Time 上午10:47:57 */ public class JsonUtil { private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class); // 采用jackson private static ObjectMapper mapper = new ObjectMapper(); /** * 将对象转换为json * * @param entity * @return */ public static String toJson(Object entity) { if (entity == null) { return null; } try { return mapper.writeValueAsString(entity); } catch (IOException e) { logger.error("parse entity=" + entity + " to json error!", e); } return null; } /** * 从json解析出对象 * * @param <T> * @param content * @param valueType * @return */ public static <T> T fromJson(String content, Class<T> valueType) { if (content == null) { return null; } try { return mapper.readValue(content, valueType); } catch (IOException e) { logger.error("parse content=" + content + " error!", e); } return null; } public static <T> T fromJson(String content, TypeReference<T> valueType) { if (content == null) { return null; } try { return mapper.readValue(content, valueType); } catch (IOException e) { logger.error("parse content=" + content + " error!", e); } return null; } private static ObjectMapper getObjectMapper() { return mapper; } public static ObjectNode createObjectNode() { return getObjectMapper().createObjectNode(); } public static ArrayNode createArrayNode() { return getObjectMapper().createArrayNode(); } /* public static void main(String[] args) { InstanceStats infor = new InstanceStats(); infor.setIp("192.1121"); DbOperate op = new DbOperate("1", "2", infor); byte[] bytes = SearializeUtil.toByteArray(op); DbOperate op2 = (DbOperate)SearializeUtil.toObject(bytes); RedisQueueHelper.getInstance().push(op); DbOperate op2 = (DbOperate) RedisQueueHelper.getInstance().pop(); InstanceStats infor2 = (InstanceStats) op2.getParameter(); System.out.println(((InstanceStats)op2.getParameter()).getIp()); }*/ }
27.451923
81
0.619615
19cbfcedc3c8bc430aaeef6b66750b6f32e0e2c1
3,664
package server; import java.lang.ClassNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.io.EOFException; import java.lang.Thread; import utils.Buffer; import utils.PriorityBuffer; import utils.Log; import utils.Matrix; import utils.NetworkNode; import utils.Request; import org.joda.time.DateTime; import org.joda.time.Duration; import org.joda.time.Interval; /** This class represent a simple server that computes the power of a matrix M by and an exposant e */ public class SimpleServer extends NetworkNode { private ServerSocket socketServer = null; private Socket socket = null; private ObjectInputStream inputStream = null; private ObjectOutputStream outputStream = null; private int BUFFER_SIZE = 1000; private PriorityBuffer<Request> buffer = new PriorityBuffer<Request>(BUFFER_SIZE); private boolean receiveFinished = false; private long computeTime = 0L; /** Constructor @port : The port of the server */ public SimpleServer(String port) { this.setPort(port); } private Thread t = new Thread(new Runnable() { public void run() { outputStream = getSocketOutputStream(socket); int sleepTime = 0; Request r; try{ while ((r=buffer.take()) !=null) { r.setServerProcessingTimeStamp(new DateTime()); long startComputeTime = computeTime; Matrix response = compute( r.getMatrix() , r.getExposant() ); r.setCalculationTime(computeTime - startComputeTime); Request dataToSend = r; dataToSend.setMatrix(response); dataToSend.setServerSendingTimeStamp(new DateTime()); Log.print("Sending request #" + r.getId()); send( dataToSend , outputStream); } send( null, outputStream); } catch (InterruptedException e){ Log.error("Interrupeted while waiting"); } } }); /** This method start the simple server (single thread). Its wait far a connection and then it add the coming request to the queue */ public void start() { Log.print("Server - start()"); try { socketServer = new ServerSocket(this.getPort()); socket = socketServer.accept(); } catch (IOException e) { Log.error("Server start() - Cannot connect sockets"); } Log.print("Connection established : " + socketServer.getLocalSocketAddress()); inputStream = getSocketInputStream(socket); t.start(); int i = 1; while (true) { Request r = receive(inputStream); if(r != null){ r.setServerReceivingTimeStamp(new DateTime()); } else { Log.print("All the data were received..."); receiveFinished = true; break; } Log.print("Request received: #" + r.getId()); if( ! buffer.add(r) ) { Log.print("Buffer is full"); } r = null; i++; } try{ t.join(); } catch (InterruptedException e){ Log.error("Unable to join receiving thread"); } Log.print("Server - end start()"); } /** This method stop the server and close all the stream */ public void stop() { try { outputStream.close(); inputStream.close(); socketServer.close(); socket.close(); } catch (IOException e) { Log.error("IOException - Server.stop()"); e.printStackTrace(); } Log.print("Server - end stop()"); } /** This method process a request client */ private Matrix compute(Matrix m, int exposant) { long startTime = System.nanoTime(); Matrix result = new Matrix(m.matrixPowered(exposant), m.getSize()); computeTime += (System.nanoTime() - startTime); return result; } }
25.09589
86
0.672489
1c130caa61fcda8dd892f45779a3839c7f962934
1,703
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lealone.sql; import java.util.Set; import org.lealone.db.Session; import org.lealone.db.value.Value; public interface IExpression { interface Evaluator { IExpression optimizeExpression(Session session, IExpression e); Value getExpressionValue(Session session, IExpression e, Object data); } int getType(); String getSQL(); IExpression optimize(Session session); Value getValue(Session session); String getAlias(); String getTableName(); String getSchemaName(); int getDisplaySize(); String getColumnName(); long getPrecision(); int getNullable(); boolean isAutoIncrement(); int getScale(); String getSQL(boolean isDistributed); IExpression getNonAliasExpression(); boolean isConstant(); void getDependencies(Set<?> dependencies); void getColumns(Set<?> columns); }
24.328571
78
0.719906
0e6f132aa025509b64c074b6da121d01eea29366
263
package com.fanxb.bookmark.common.entity.po; import lombok.Data; /** * 类功能简述: * 类功能详述: * * @author fanxb * @date 2019/7/9 14:47 */ @Data public class Url { private int userId; private String method; private String url; private int type; }
13.842105
44
0.65019
c621370eb97270fe2a2c6cd85fac62721ff4adaa
1,013
package com.tokelon.toktales.tools.assets.files; import java.io.File; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import com.tokelon.toktales.tools.assets.annotation.ParentIdentifiers; public class FileParentResolver implements IParentResolver<File> { private final Map<Object, File> parentIdentifierMap; public FileParentResolver(Object parentIdentifier, File parent) { parentIdentifierMap = new HashMap<>(); parentIdentifierMap.put(parentIdentifier, parent); } @Inject public FileParentResolver(@ParentIdentifiers Map<Object, File> parentIdentifierMap) { this.parentIdentifierMap = parentIdentifierMap; } @Override public File resolve(File relative, Object parentIdentifier) { File file = parentIdentifierMap.get(parentIdentifier); return file == null ? null : new File(file, relative.getPath()); } @Override public boolean canResolve(File relative, Object parentIdentifier) { return parentIdentifierMap.containsKey(parentIdentifier); } }
25.974359
86
0.787759
a35f3aa3ceb6795d35eb08703a473c18fcfc98d4
11,646
/** * Track class that creates a Linked List of trains in tracks */ public class Track { private Train head; private Train tail; private Train cursor; private Track next; private Track prev; private int trackNumber; private int numTrains; private int transferTime; private double utilizationRate; /** * Default constructor w/o parameters */ public Track() { this.head = null; this.tail = null; this.cursor = null; this.next = null; this.prev = null; this.numTrains = 0; this.transferTime = 0; } /** * Default constructor w/ parameter * @param trackNumber * Integer input of track number */ public Track(int trackNumber) { this.head = null; this.tail = null; this.cursor = null; this.next = null; this.prev = null; this.numTrains = 0; this.transferTime = 0; this.trackNumber = trackNumber; } /** * Adds a train to a track * @param newTrain * Input type of train * @throws NullPointerException * If no trains exist * @throws TrainAlreadyExistsException * If a train with the same number already exists * @throws OverLapException * If a train's schedule overlaps with another arranged schedule */ public void addTrain(Train newTrain) throws NullPointerException, TrainAlreadyExistsException, OverLapException { Train temp = this.head; while (temp != null) { if (temp.equals(newTrain)) { throw new TrainAlreadyExistsException(); } else if (newTrain.getArrivalTime() >= temp.getArrivalTime() && newTrain.getArrivalTime() <= temp.getArrivalTime() + temp.getTransferTime()) { throw new OverLapException(); } temp = temp.getNext(); } numTrains++; this.transferTime += newTrain.getTransferTime(); if (this.head == null) { this.head = newTrain; this.cursor = this.head; return; } if (this.cursor.getNext() == null) { this.cursor.setNext(newTrain); this.cursor.getNext().setPrev(this.cursor); this.cursor = this.cursor.getNext(); return; } newTrain.setNext(this.cursor.getNext()); newTrain.setPrev(this.cursor.getPrev()); this.cursor.getNext().setPrev(newTrain); this.cursor.setNext(newTrain); this.cursor = newTrain; } /** * Prints information about the selected train node (where the cursor is) */ public void printSelectedTrain() { String format = "Selected Train:\n" + " Train Number: %i\n" + " Train Destination: &s\n" + " Arrival Time: %04d\n" + " Departure Time: %s"; System.out.format(format, this.cursor.getTrainNumber(), this.cursor.getDestination(), this.cursor.getArrivalTime(), departureTime(this.cursor)); } /** * Removes train from the list * @return * Train that is in the cursor to be removed * @throws EmptyTrainException * There are no trains * @throws EmptyTrackException * There are no tracks */ public Train removeSelectedTrain() throws EmptyTrainException, EmptyTrackException { // // NullPointerSection if (this.head == null) throw new EmptyTrainException(); if (this.numTrains == 0) throw new EmptyTrackException(); numTrains--; Train removeTrain = this.cursor; if (this.cursor == this.head && this.cursor.getNext() == null) { // // First Link this.head = null; this.cursor = null; return removeTrain; } if (this.cursor == this.head && this.cursor.getNext() != null) { this.cursor = this.cursor.getNext(); this.cursor.setPrev(null); this.head = this.cursor; return removeTrain; } if (this.cursor.getNext() == null && this.cursor.getPrev() != null) { // Last Link this.cursor = this.cursor.getPrev(); this.cursor.setNext(null); return removeTrain; } this.cursor.getNext().setPrev(this.cursor.getPrev()); // Middle Links this.cursor.getPrev().setNext(this.cursor.getNext()); this.cursor = this.cursor.getNext(); return removeTrain; } /** * Selects the next train node * @return * True if the next train can be selected * @throws NoNextTrainException * If there is no next train on the track * */ public boolean selectNextTrain() throws NoNextTrainException { if (this.cursor.getNext() == null) throw new NoNextTrainException(); this.cursor = this.cursor.getNext(); return true; } /** * Select the previous train node * @return * True if there is a train behind * @throws NoPrevTrainException * If there are no more trains behind */ public boolean selectPrevTrain() throws NoPrevTrainException { if (this.cursor.getPrev() == null) throw new NoPrevTrainException(); this.cursor = this.cursor.getPrev(); return true; } /** * Writes the Track class as a string * @return * String containing train nodes in track */ public String toString() { String all = ""; Train tempCursor = this.head; String trainsFormat = "%-11s%-17s%-26s%-17s%-14s\n"; System.out.println(String.format(trainsFormat, "Selected", "Train " + "Number", "Destination", "Arrival Time", "Transfer Time")); while (tempCursor != null) { String[] trainInfo = tempCursor.toString2().split(","); if (tempCursor.equals(this.cursor)) { System.out.println(String.format(trainsFormat, "*", trainInfo[0], trainInfo[1], trainInfo[2], departureTime(tempCursor))); all += String.format(trainsFormat, "*", trainInfo[0], trainInfo[1], trainInfo[2], departureTime(tempCursor)); } else { System.out.println(String.format(trainsFormat, "", trainInfo[0], trainInfo[1], trainInfo[2], departureTime(tempCursor))); all += String.format(trainsFormat, "", trainInfo[0], trainInfo[1], trainInfo[2], departureTime(tempCursor)); } tempCursor = tempCursor.getNext(); } return all; } /** * Attempts to write arrival + departure as a 24h time * @param t * The train to write the departure time * @return * String of the train's departure time */ public String departureTime(Train t) { String format = "%04d"; int transferTime = t.getTransferTime(); int arrivalTime = t.getArrivalTime(); int minutes = (arrivalTime % 100) + transferTime; int hoursAdd = transferTime / 60; int newHours = ((arrivalTime / 100) + hoursAdd) % 24; int hours = newHours * 100; int mins = minutes % 60; return (String.format(format, (hours + mins))); } /** * Gets utilization rate * @return * Double of utilizationRate */ // Getters public double getUtilizationRate() { return (this.transferTime / 1440.0); } /** * Gets Track Number * @return * Integer of track number */ public int getTrackNumber() { return trackNumber; } /** * Gets the next track node * @return * Object of type Track */ public Track getNext() { return next; } /** * Gets the previous track node * @return * Object of type Track */ public Track getPrev() { return prev; } /** * Gets the current cursor of the train node * @return * Object of type Train */ public Train getCursor() { return cursor; } /** * Gets the head of the train node * @return * Object of type Train */ public Train getHead() { return head; } /** * Gets the tail of the train node * @return * Object of type Train */ public Train getTail() { return tail; } /** * Gets the number of trains in the track * @return * Integer of the number of trains */ public int getNumTrains() { return numTrains; } /** * Gets the transfer time * @return * Integer value of transfer time */ public int getTransferTime() { return transferTime; } // Setters /** * Sets the cursor of the Train node * @param cursor * Object of type Train */ public void setCursor(Train cursor) { this.cursor = cursor; } /** * Sets what the train head node is * @param head * Object of type Train */ public void setHead(Train head) { this.head = head; } /** * Sets the next track node * @param next * Object of type Track */ public void setNext(Track next) { this.next = next; } /** * Sets the previous track node * @param prev * Object of type Track */ public void setPrev(Track prev) { this.prev = prev; } /** * Sets the tail of the train node * @param tail * Object of type Train */ public void setTail(Train tail) { this.tail = tail; } /** * Sets the track number * @param trackNumber * Integer of track number */ public void setTrackNumber(int trackNumber) { this.trackNumber = trackNumber; } /** * Sets the utilization rate * @param utilizationRate * Double value of the rate */ public void setUtilizationRate(double utilizationRate) { this.utilizationRate = utilizationRate; } /** * Sets the number of train in the track * @param numTrains * Integer value of number of trains */ public void setNumTrains(int numTrains) { this.numTrains = numTrains; } /** * Sets the transfer time of the train node * @param transferTime * Integer value of the transfer time */ public void setTransferTime(int transferTime) { this.transferTime = transferTime; } } /** * Exception class if there is no next train node */ class NoNextTrainException extends Exception { public NoNextTrainException() {} } /** * Exception class if there is no previous train node */ class NoPrevTrainException extends Exception { public NoPrevTrainException() {} } /** * Exception class if there is a train with the same train number already added */ class TrainAlreadyExistsException extends Exception { public TrainAlreadyExistsException() {} } /** * Exception class if there are no trains added */ class EmptyTrainException extends Exception { public EmptyTrainException() {} } /** * Exception class if there are no tracks added */ class EmptyTrackException extends Exception { public EmptyTrackException() {} } /** * Exception class if there is a overlap in time of a train's arrival time */ class OverLapException extends Exception { public OverLapException() {} }
27.662708
91
0.573158
69c178c8cdf8c7400b8889a3d867c83bb5cf384b
2,574
package com.sunnsoft.sloa.db.dao; import com.sunnsoft.sloa.db.vo.Tag; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.gteam.db.dao.BaseDAO; import java.util.List; // Generated by Hibernate Tools 3.4.0.CR1,modified by llade /** * Home object for domain model class Tag. * @see com.sunnsoft.sloa.db.vo.Tag * @author Hibernate Tools * @author llade */ @SuppressWarnings("unchecked") public class TagDAOImpl extends BaseDAO implements TagDAO { private static final Log log = LogFactory.getLog(TagDAO.class); public Tag findById( Long id) { if(log.isDebugEnabled()){ log.debug("getting Tag instance with id: " + id); } try { Tag instance = (Tag) getHibernateTemplate() .get("com.sunnsoft.sloa.db.vo.Tag", id); if(log.isDebugEnabled()){ if (instance==null) { log.debug("get successful, no instance found"); } else { log.debug("get successful, instance found"); } } return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public void save(Tag transientInstance) { if(log.isDebugEnabled()){ log.debug("saving Tag instance"); } try { getHibernateTemplate().save(transientInstance); if(log.isDebugEnabled()){ log.debug("save successful"); } } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Tag persistentInstance) { if(log.isDebugEnabled()){ log.debug("deleting Tag instance"); } try { getHibernateTemplate().delete(persistentInstance); if(log.isDebugEnabled()){ log.debug("delete successful"); } } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { if(log.isDebugEnabled()){ log.debug("finding Tag instance with property: " + propertyName + ", value: " + value); } try { String queryString = "from Tag as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } }
28.6
90
0.573815
7b3f357e1c0e9e10d60f8db3d851b1b3aaff1eb8
558
package org.apache.poi.ss.usermodel; import org.apache.poi.ss.util.CellAddress; public interface Comment { CellAddress getAddress(); String getAuthor(); ClientAnchor getClientAnchor(); int getColumn(); int getRow(); RichTextString getString(); boolean isVisible(); void setAddress(int i, int i2); void setAddress(CellAddress cellAddress); void setAuthor(String str); void setColumn(int i); void setRow(int i); void setString(RichTextString richTextString); void setVisible(boolean z); }
16.411765
50
0.689964
488a7d22c39e38676042b44c18d27e1b0464aa9c
3,070
package cn.laoshini.dk.generator.id; import javax.sql.DataSource; import org.springframework.beans.BeansException; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.support.incrementer.AbstractColumnMaxValueIncrementer; import org.springframework.jdbc.support.incrementer.AbstractIdentityColumnMaxValueIncrementer; import org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer; import org.springframework.jdbc.support.incrementer.SqlServerMaxValueIncrementer; import cn.laoshini.dk.common.SpringContextHolder; import cn.laoshini.dk.constant.DBTypeEnum; import cn.laoshini.dk.dao.SqlBuilder; import cn.laoshini.dk.exception.BusinessException; import cn.laoshini.dk.exception.DaoException; /** * 使用数据库表实现id自增器 * * @author fagarine */ class ColumnIdIncrementer implements IDbIdIncrementer { private AbstractColumnMaxValueIncrementer columnIncrementer; ColumnIdIncrementer(String columnName) { DataSource dataSource; try { dataSource = SpringContextHolder.getBean(DataSource.class); } catch (BeansException e) { throw new DaoException("rdb.not.init", "找不到DataSource对象,无法通过数据库表实现id自增器"); } DBTypeEnum dbType = SqlBuilder.getDBType(); String tableName = IdIncrementerConstant.ID_INCREMENTER_TABLE; switch (dbType) { case MYSQL: columnIncrementer = new MySQLMaxValueIncrementer(dataSource, tableName, columnName); break; case SQL_SERVER: columnIncrementer = new SqlServerMaxValueIncrementer(dataSource, tableName, columnName); break; default: columnIncrementer = new DefaultColumnIncrementer(dataSource, tableName, columnName); break; } columnIncrementer.setCacheSize(cacheSize()); } @Override public String idName() { return columnIncrementer.getColumnName(); } @Override public long nextId() { try { return columnIncrementer.nextLongValue(); } catch (DataAccessException e) { throw new BusinessException("id.next.fail", "通过关系数据库实现id自增失败:" + columnIncrementer.getColumnName(), e); } } @Override public int cacheSize() { // 默认缓存量为100 return IdIncrementerConstant.RELATION_DB_CACHE_SIZE; } private final class DefaultColumnIncrementer extends AbstractIdentityColumnMaxValueIncrementer { DefaultColumnIncrementer(DataSource dataSource, String incrementerName, String columnName) { super(dataSource, incrementerName, columnName); } @Override protected String getIncrementStatement() { return "insert into " + getIncrementerName() + "(" + getColumnName() + " ) values(" + getIdentityStatement() + ")"; } @Override protected String getIdentityStatement() { return "SELECT MAX(" + getColumnName() + ") FROM " + getIncrementerName(); } } }
33.736264
120
0.688274
7f0f150f68c26e1a111da92092ab392647b260ff
2,960
/** * JBoss, Home of Professional Open Source * Copyright Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.aerogear.todo.fragments; import org.jboss.aerogear.android.pipeline.Pipe; import org.jboss.aerogear.todo.R; import org.jboss.aerogear.todo.ToDoApplication; import org.jboss.aerogear.todo.activities.TodoActivity; import org.jboss.aerogear.todo.activities.TodoActivity.Lists; import org.jboss.aerogear.todo.callback.SaveCallback; import org.jboss.aerogear.todo.data.Tag; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class TagFormFragment extends Fragment { private final Tag tag; public TagFormFragment() { tag = new Tag(); } public TagFormFragment(Tag tag) { this.tag = tag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.form, null); final TextView title = (TextView) view.findViewById(R.id.title); final EditText name = (EditText) view.findViewById(R.id.name); final Button buttonSave = (Button) view.findViewById(R.id.buttonSave); final Button buttonCancel = (Button) view .findViewById(R.id.buttonCancel); title.setText(getResources().getString(R.string.tags)); if (tag.getId() != null) { buttonSave.setText(R.string.update); } name.setText(tag.getTitle()); buttonSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (name.getText().toString().length() < 1) { name.setError("Please enter a title"); return; } tag.setTitle(name.getText().toString()); @SuppressWarnings("unchecked") Pipe<Tag> pipe = ((ToDoApplication) getActivity() .getApplication()).getPipeline().get("tags", TagFormFragment.this, getActivity().getApplicationContext()); pipe.save(tag, new SaveCallback<Tag>(Lists.TAG)); } }); buttonCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ((TodoActivity) getActivity()).showList(Lists.TAG); } }); return view; } }
30.515464
112
0.740203
2937ef229369661260a9c778ab7070d14b11237b
4,271
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Database; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import Classes.LearningGoal; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; /** * * @author Vegard */ public class LearningGoalDb extends Database { private static final String GET_MODULE_ID = "select module_id from Module where module_name = ?"; private static final String ADD_LEARN_GOAL = "insert into LearningGoal values (default, ?, ?, ?)"; private static final String GET_LEARN_GOALS = "select * from LearningGoal"; private static final String EDIT_LEARN_GOALS = "update LearningGoal set learn_goal_text = ?, learn_goal_points = ? where learn_goal_id = ? "; public LearningGoalDb() { init(); } public String getModuleID(PrintWriter out, String moduleName) { try( Connection connection = getConnection(); PreparedStatement prepStatement = connection.prepareStatement(GET_MODULE_ID); ){ prepStatement.setString(1, moduleName); try(ResultSet rset = prepStatement.executeQuery();) { while(rset.next()) { String moduleID = rset.getString("module_id"); return moduleID; } } } catch(SQLException exc) { out.println("Error in getModuleID(): " + exc); } return null; } public boolean addLearningGoals(PrintWriter out, String learnGoalText, String learnGoalPoints, String moduleName) { try( Connection connection = getConnection(); PreparedStatement prepStatement = connection.prepareStatement(ADD_LEARN_GOAL); ) { String moduleID = getModuleID(out, moduleName); prepStatement.setString(1, learnGoalText); prepStatement.setString(2, learnGoalPoints); prepStatement.setString(3, moduleID); prepStatement.executeUpdate(); return true; } catch(SQLException ex) { out.println("Error in function addLearningGoals(): " + ex); } return false; } public ArrayList<LearningGoal> writeLearningGoals(PrintWriter out, String moduleID) { try( Connection connection = getConnection(); PreparedStatement prepStatement = connection.prepareStatement(GET_LEARN_GOALS); ResultSet rset = prepStatement.executeQuery(); ) { ArrayList<LearningGoal> lgList = new ArrayList<>(); while(rset.next()) { LearningGoal lgoal = new LearningGoal(); lgoal.setLearn_goal_id(rset.getString("learn_goal_id")); lgoal.setText(rset.getString("learn_goal_text")); lgoal.setPoints(rset.getInt("learn_goal_points")); lgoal.setModuleID(rset.getString("module_id")); lgList.add(lgoal); } return lgList; } catch(SQLException e) { out.println("Error in function writeLearningGoals(): " + e); } return null; } public boolean editLearnGoals(PrintWriter out, HttpServletRequest request, String learnGoalText, String learnGoalPoints, String learnGoalID) { try( Connection connection = getConnection(); PreparedStatement prepStatement = connection.prepareStatement(EDIT_LEARN_GOALS); ) { prepStatement.setString(1, learnGoalText); prepStatement.setString(2, learnGoalPoints); prepStatement.setString(3, learnGoalID); prepStatement.executeUpdate(); return true; } catch(SQLException ex) { out.println("SQL Exception in function editLearnGoals(): " + ex); } return false; } }
30.507143
149
0.607352
ce160d6962977da4611681b0532fee49b1e339d3
379
package ru.itis.jwtserver.services; import ru.itis.jwtserver.dto.AccessTokenResponse; import ru.itis.jwtserver.dto.RefreshTokenResponse; import ru.itis.jwtserver.dto.UserAuthorizationForm; public interface UserLoginService { RefreshTokenResponse login(UserAuthorizationForm emailPasswordDto); AccessTokenResponse authenticate(RefreshTokenResponse refreshTokenDto); }
29.153846
75
0.846966
19bc731604d43706b067863c7dc7ba1b5774d9d2
247
package edu.javacourse.spring.integration; /** * @author Artem Pronchakov | email/xmpp: [email protected] */ public class LoggerB { public void log(String message){ System.out.println("Logger B: " + message); } }
19
72
0.680162
bb1604cbccba2683f63eb1808750be664c1108d9
2,592
package com.todo1.demoapp.dto; import java.util.Date; import javax.validation.constraints.NotBlank; import com.fasterxml.jackson.annotation.JsonProperty; /** * Objeto Producto DTO para * @author Mustarroz * */ public class ProductoDTO { /** * id autogenerado */ private Long id; /** * Identificación del producto (dato negocio) */ @JsonProperty @NotBlank private Long codProducto; /** * Detalle del producto */ @JsonProperty @NotBlank private String descripcion; /** * stock del producto */ @JsonProperty @NotBlank private Long stock; /** * fecha de ultima modificación del producto */ private Date fecha; /** * Marca del producto */ private String marca; public ProductoDTO() { } /** * Constructor del objeto ProductoDTO utilizado para modificaciones * @param id * @param codProducto * @param descripcion * @param stock * @param fechaUltimaActualizacion * @param marca */ public ProductoDTO(Long id, Long codProducto, String descripcion, Long stock, Date fechaUltimaActualizacion, String marca) { this.id = id; this.codProducto = codProducto; this.descripcion = descripcion; this.setStock(stock); this.setFecha(fechaUltimaActualizacion); this.marca = marca; } /** * Constructor del objecto ProductoDTO utilizado para la creación de productos * @param codProducto * @param descripcion * @param stock * @param fechaUltimaActualizacion * @param marca */ public ProductoDTO( Long codProducto, String descripcion, Long stock, Date fechaUltimaActualizacion, String marca) { this.codProducto = codProducto; this.descripcion = descripcion; this.setStock(stock); this.setFecha(fechaUltimaActualizacion); this.marca = marca; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Long getCodProducto() { return codProducto; } public void setCodProducto(Long codProducto) { this.codProducto = codProducto; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getStock() { return stock; } public void setStock(Long stock) { this.stock = stock; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public String getMarca() { return marca; } public void setMarca(String marca) { this.marca = marca; } }
19.343284
126
0.667824
551c518cd0cba09e397e3461c198045a5fcb1c0d
1,538
package org.femtoframework.service.apsis.k8s; import org.femtoframework.cube.spec.ConnectionSpec; import org.femtoframework.cube.spec.SystemSpec; import org.femtoframework.service.apsis.cube.CubeConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; /** * K8s Service */ public class K8sConnector extends CubeConnector { public static final int DEFAULT_PORT = 9168; private static Logger log = LoggerFactory.getLogger(K8sConnector.class); protected void connect(SystemSpec systemSpec, ConnectionSpec conn) { //Service Type URI uri = conn.getUri(); String serviceType = uri.getPath(); serviceType = serviceType.trim(); if (serviceType.startsWith("/")) { serviceType = serviceType.substring(1); } if (serviceType.isEmpty()) { log.warn("The target service isn't specified, ignore this service:" + uri); return; } int port = uri.getPort(); if (port <= 0) { port = DEFAULT_PORT; } // In K8s, statefulset uses "serviceType" try { InetAddress[] addresses = InetAddress.getAllByName(serviceType); for(InetAddress add: addresses) { connect(uri.getScheme(), add.getHostAddress(), port, conn); } } catch (UnknownHostException e) { log.warn("Service:" + serviceType + " not found", e); } } }
30.76
87
0.637191
53c173ee549a076e857ec2fb9e53604fa2cd9013
8,019
package com.thinkgem.jeesite.modules.tmc.modal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import com.thinkgem.jeesite.modules.taier.entity.TmcRwsqd; import com.thinkgem.jeesite.modules.tmc.utils.DBConnectionUtils; public class TmcRwsqdModal { public void save(TmcRwsqd rwsqd) throws SQLException{ Connection conn=DBConnectionUtils.getConnection(); String sql="INSERT INTO TMC9081.tmc_rwsqd("+ "SJDW, SJDWDZ, SCC, SCCDZ, ZZSMC, ZZSDZ, CD, LXRMC, YDDH, CZ,"+ " EMAIL, SBXH, JCLB, CSYJ, BGLX, YHSM, YHDBQZ, YHDBQZRQ, ZXSM, ZXRWSLYQZ,"+ " ZXRWSLYQZRQ, BBXX, XXXX, BZ, READER, WRITER, PK1, SBMC, CCCSQH, BH,"+ " DJ, EJDKXX, KCLX, SFZCCMMB, SFZCEGPRSGN, SFZCGPRSGN, SFZCGPSGN, SFZCLYGN, SFZCSYJGN, SFZCWAPI,"+ " RJBBCXFS, RJBBH, YJBBH, EDJ, EDSRDY, FSGL, EDGL, FSPL, SCDL, SCDY,"+ " ZDSRDY, SFFSJ, ZT, SQRQ, TYSM, JLSJ, SQFS, FSZS, SLBH, SBJC,"+ " SFSC, GJWWBG, BGSM, JCLBO, SFBM, SFCWAPI, SBLB, GDH, XXLB, DRFS,"+ " RWLY, DLS"+ ") VALUES ("+ "?,?,?,?,?,?,?,?,?,?,"+ "?,?,?,?,?,?,?,?,?,?,"+ "?,?,?,?,?,?,?,?,?,?,"+ "?,?,?,?,?,?,?,?,?,?,"+ "?,?,?,?,?,?,?,?,?,?,"+ "?,?,?,?,?,?,?,?,?,?,"+ "?,?,?,?,?,?,?,?,?,?,"+ "?,?"+ ")"; PreparedStatement ptmt=conn.prepareStatement(sql); ptmt.setString(1, rwsqd.getSjdw()); ptmt.setString(2, rwsqd.getSjdwdz()); ptmt.setString(3, rwsqd.getScc()); ptmt.setString(4, rwsqd.getSccdz()); ptmt.setString(5, rwsqd.getZzsmc()); ptmt.setString(6, rwsqd.getZzsdz()); ptmt.setString(7, rwsqd.getCd()); ptmt.setString(8, rwsqd.getLxrmc()); ptmt.setString(9, rwsqd.getYddh()); ptmt.setString(10, rwsqd.getCz()); ptmt.setString(11, rwsqd.getEmail()); ptmt.setString(12, rwsqd.getSbxh()); ptmt.setString(13, rwsqd.getJclb()); ptmt.setString(14, rwsqd.getCsyj()); ptmt.setString(15, rwsqd.getBglx()); ptmt.setString(16, rwsqd.getYhsm()); ptmt.setString(17, rwsqd.getYhdbqz()); ptmt.setString(18, rwsqd.getYhdbqzrq()); ptmt.setString(19, rwsqd.getZxsm()); ptmt.setString(20, rwsqd.getZxrwslyqz()); ptmt.setString(21, rwsqd.getZxrwslyqzrq()); ptmt.setString(22, rwsqd.getBbxx()); ptmt.setString(23, rwsqd.getXxxx()); ptmt.setString(24, rwsqd.getBz()); ptmt.setString(25, rwsqd.getReader()); ptmt.setString(26, rwsqd.getWriter()); ptmt.setString(27, rwsqd.getPk1()); ptmt.setString(28, rwsqd.getSbmc()); ptmt.setString(29, rwsqd.getCccsqh()); ptmt.setString(30, rwsqd.getBh()); ptmt.setString(31, rwsqd.getDj()); ptmt.setString(32, rwsqd.getEjdkxx()); ptmt.setString(33, rwsqd.getKclx()); ptmt.setString(34, rwsqd.getSfzccmmb()); ptmt.setString(35, rwsqd.getSfzcegprsgn()); ptmt.setString(36, rwsqd.getSfzcgprsgn()); ptmt.setString(37, rwsqd.getSfzcgpsgn()); ptmt.setString(38, rwsqd.getSfzclygn()); ptmt.setString(39, rwsqd.getSfzcsyjgn()); ptmt.setString(40, rwsqd.getSfzcwapi()); ptmt.setString(41, rwsqd.getRjbbcxfs()); ptmt.setString(42, rwsqd.getRjbbh()); ptmt.setString(43, rwsqd.getYjbbh()); ptmt.setString(44, rwsqd.getEdj()); ptmt.setString(45, rwsqd.getEdsrdy()); ptmt.setString(46, rwsqd.getFsgl()); ptmt.setString(47, rwsqd.getEdgl()); ptmt.setString(48, rwsqd.getFspl()); ptmt.setString(49, rwsqd.getScdl()); ptmt.setString(50, rwsqd.getScdy()); ptmt.setString(51, rwsqd.getZdsrdy()); ptmt.setString(52, rwsqd.getSffsj()); ptmt.setString(53, rwsqd.getZt()); ptmt.setString(54, rwsqd.getSqrq()); ptmt.setString(55, rwsqd.getTysm()); ptmt.setString(56, rwsqd.getJlsj()); ptmt.setString(57, rwsqd.getSqfs()); ptmt.setString(58, rwsqd.getFszs()); ptmt.setString(59, rwsqd.getSlbh()); ptmt.setString(60, rwsqd.getSbjc()); ptmt.setString(61, rwsqd.getSfsc()); ptmt.setString(62, rwsqd.getGjwwbg()); ptmt.setString(63, rwsqd.getBgsm()); ptmt.setString(64, rwsqd.getJclbo()); ptmt.setString(65, rwsqd.getSfbm()); ptmt.setString(66, rwsqd.getSfcwapi()); ptmt.setString(67, rwsqd.getSblb()); ptmt.setString(68, rwsqd.getGdh()); ptmt.setString(69, rwsqd.getXxlb()); ptmt.setString(70, rwsqd.getDrfs()); ptmt.setString(71, rwsqd.getRwly()); ptmt.setString(72, rwsqd.getDls()); ptmt.execute(); } public void update(TmcRwsqd rwsqd) throws SQLException{ Connection conn=DBConnectionUtils.getConnection(); String sql="UPDATE TMC9081.tmc_rwsqd SET "+ "SJDW=?, SJDWDZ=?, SCC=?, SCCDZ=?, ZZSMC=?, ZZSDZ=?, CD=?, LXRMC=?, YDDH=?, CZ=?,"+ " EMAIL=?, SBXH=?, JCLB=?, CSYJ=?, BGLX=?, YHSM=?, YHDBQZ=?, YHDBQZRQ=?, ZXSM=?, ZXRWSLYQZ=?,"+ " ZXRWSLYQZRQ=?, BBXX=?, XXXX=?, BZ=?, READER=?, WRITER=?,DLS=?, SBMC=?, CCCSQH=?, RWLY=?,"+ " DJ=?, EJDKXX=?, KCLX=?, SFZCCMMB=?, SFZCEGPRSGN=?, SFZCGPRSGN=?, SFZCGPSGN=?, SFZCLYGN=?, SFZCSYJGN=?, SFZCWAPI=?,"+ " RJBBCXFS=?, RJBBH=?, YJBBH=?, EDJ=?, EDSRDY=?, FSGL=?, EDGL=?, FSPL=?, SCDL=?, SCDY=?,"+ " ZDSRDY=?, SFFSJ=?, ZT=?, SQRQ=?, TYSM=?, JLSJ=?, SQFS=?, FSZS=?, SLBH=?, SBJC=?,"+ " SFSC=?, GJWWBG=?, BGSM=?, JCLBO=?, SFBM=?, SFCWAPI=?, SBLB=?, GDH=?, XXLB=?, DRFS=?"+ " WHERE pk1 = ?"; PreparedStatement ptmt=conn.prepareStatement(sql); ptmt.setString(1, rwsqd.getSjdw()); ptmt.setString(2, rwsqd.getSjdwdz()); ptmt.setString(3, rwsqd.getScc()); ptmt.setString(4, rwsqd.getSccdz()); ptmt.setString(5, rwsqd.getZzsmc()); ptmt.setString(6, rwsqd.getZzsdz()); ptmt.setString(7, rwsqd.getCd()); ptmt.setString(8, rwsqd.getLxrmc()); ptmt.setString(9, rwsqd.getYddh()); ptmt.setString(10, rwsqd.getCz()); ptmt.setString(11, rwsqd.getEmail()); ptmt.setString(12, rwsqd.getSbxh()); ptmt.setString(13, rwsqd.getJclb()); ptmt.setString(14, rwsqd.getCsyj()); ptmt.setString(15, rwsqd.getBglx()); ptmt.setString(16, rwsqd.getYhsm()); ptmt.setString(17, rwsqd.getYhdbqz()); ptmt.setString(18, rwsqd.getYhdbqzrq()); ptmt.setString(19, rwsqd.getZxsm()); ptmt.setString(20, rwsqd.getZxrwslyqz()); ptmt.setString(21, rwsqd.getZxrwslyqzrq()); ptmt.setString(22, rwsqd.getBbxx()); ptmt.setString(23, rwsqd.getXxxx()); ptmt.setString(24, rwsqd.getBz()); ptmt.setString(25, rwsqd.getReader()); ptmt.setString(26, rwsqd.getWriter()); //ptmt.setString(27, rwsqd.getPk1()); ptmt.setString(27, rwsqd.getDls()); ptmt.setString(28, rwsqd.getSbmc()); ptmt.setString(29, rwsqd.getCccsqh()); ptmt.setString(30, rwsqd.getRwly()); //ptmt.setString(30, rwsqd.getBh()); ptmt.setString(31, rwsqd.getDj()); ptmt.setString(32, rwsqd.getEjdkxx()); ptmt.setString(33, rwsqd.getKclx()); ptmt.setString(34, rwsqd.getSfzccmmb()); ptmt.setString(35, rwsqd.getSfzcegprsgn()); ptmt.setString(36, rwsqd.getSfzcgprsgn()); ptmt.setString(37, rwsqd.getSfzcgpsgn()); ptmt.setString(38, rwsqd.getSfzclygn()); ptmt.setString(39, rwsqd.getSfzcsyjgn()); ptmt.setString(40, rwsqd.getSfzcwapi()); ptmt.setString(41, rwsqd.getRjbbcxfs()); ptmt.setString(42, rwsqd.getRjbbh()); ptmt.setString(43, rwsqd.getYjbbh()); ptmt.setString(44, rwsqd.getEdj()); ptmt.setString(45, rwsqd.getEdsrdy()); ptmt.setString(46, rwsqd.getFsgl()); ptmt.setString(47, rwsqd.getEdgl()); ptmt.setString(48, rwsqd.getFspl()); ptmt.setString(49, rwsqd.getScdl()); ptmt.setString(50, rwsqd.getScdy()); ptmt.setString(51, rwsqd.getZdsrdy()); ptmt.setString(52, rwsqd.getSffsj()); ptmt.setString(53, rwsqd.getZt()); ptmt.setString(54, rwsqd.getSqrq()); ptmt.setString(55, rwsqd.getTysm()); ptmt.setString(56, rwsqd.getJlsj()); ptmt.setString(57, rwsqd.getSqfs()); ptmt.setString(58, rwsqd.getFszs()); ptmt.setString(59, rwsqd.getSlbh()); ptmt.setString(60, rwsqd.getSbjc()); ptmt.setString(61, rwsqd.getSfsc()); ptmt.setString(62, rwsqd.getGjwwbg()); ptmt.setString(63, rwsqd.getBgsm()); ptmt.setString(64, rwsqd.getJclbo()); ptmt.setString(65, rwsqd.getSfbm()); ptmt.setString(66, rwsqd.getSfcwapi()); ptmt.setString(67, rwsqd.getSblb()); ptmt.setString(68, rwsqd.getGdh()); ptmt.setString(69, rwsqd.getXxlb()); ptmt.setString(70, rwsqd.getDrfs()); ptmt.setString(71, rwsqd.getPk1()); ptmt.execute(); } }
40.296482
121
0.668413
8249993a38e2cc42c387ad25ff72b73ba744bf44
433
package com.rekmock; /** * Created by Faleh Omar on 01/23/2015. */ public class RekMokException extends RuntimeException { public RekMokException() { super(); } public RekMokException(String message) { super(message); } public RekMokException(String message, Throwable cause) { super(message, cause); } public RekMokException(Throwable cause) { super(cause); } }
18.826087
61
0.637413
d5358c64d453b108db17947713b120dfc5e59a14
6,867
package com.kalyoncu.mert.mancala.pit.playerstore.impl; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.javatuples.Pair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.StateMachine; import org.springframework.statemachine.action.Action; import com.kalyoncu.mert.mancala.pit.Pit; import com.kalyoncu.mert.mancala.pit.PitEvents; import com.kalyoncu.mert.mancala.pit.PitStates; import com.kalyoncu.mert.mancala.pit.playerpit.PitStateActions; import com.kalyoncu.mert.mancala.pit.playerpit.impl.PitStateActionsImpl.StateParameters; import com.kalyoncu.mert.mancala.pit.playerstore.StoreStateActions; import com.kalyoncu.mert.mancala.pit.playerstore.StoreStateMachineConfiguration; import com.kalyoncu.mert.mancala.pit.playerstore.entity.impl.PlayerStoreImpl; @Configuration public class StoreStateActionsImpl implements StoreStateActions { private static final Logger logger = Logger.getLogger(StoreStateActionsImpl.class.getName()); public enum StoreIndex { PLAYER_1_STORE(6), PLAYER_2_STORE(13); private final int value; private StoreIndex(int value) { this.value = value; } public int getValue() { return value; } } public enum StoreInitialPieceCounts { PLAYER_PIT(6), PLAYER_STORE(0); private final int value; private StoreInitialPieceCounts(int value) { this.value = value; } public int getValue() { return value; } } @Autowired private StoreStateMachineConfiguration storeStateMachineConfiguration; @Autowired private PitStateActions pitStateActions; public List<Pair<?, ?>> pitStateMachinePairList = new ArrayList<Pair<?, ?>>(); private List<Pair<Pit, StateMachine<PitStates.PLAYERSTORESTATES, PitEvents.PLAYERSTOREEVENTS>>> storeStateMachinePairList = new ArrayList<>(); @Override @Bean public Action<PitStates.PLAYERSTORESTATES, PitEvents.PLAYERSTOREEVENTS> initializeStore() { return ctx -> initializeStoreObject(ctx.getStateMachine().getId()); } private boolean initializeStoreObject(String id) { logger.log(Level.INFO, "inside initializePitObjects() method for id: {0}", id); Pit pit = (Pit) pitStateActions.getPitStateMachinePairList().get(Integer.valueOf(id)).getValue0(); pit.initialize(); return true; } @Override public Action<PitStates.PLAYERSTORESTATES, PitEvents.PLAYERSTOREEVENTS> deposit() { return ctx -> { logger.log(Level.INFO, "Inside deposit() action of PitStore"); int id = Integer.parseInt(ctx.getStateMachine().getId()); Pit pit = getPitObject(id); pit.setPieceCount(pit.getPieceCount() + 1); updatePitStateMachinePairList(id, pit); }; } private Pit getPitObject(int id) { return (Pit) (pitStateActions.getPitStateMachinePairList().get(id).getValue0()); } private boolean updatePitStateMachinePairList(int id, Pit pit) { pitStateActions.getPitStateMachinePairList().set(id, Pair.with(pit, pitStateActions.getPitStateMachinePairList().get(id).getValue1())); return true; } @Override public Action<PitStates.PLAYERSTORESTATES, PitEvents.PLAYERSTOREEVENTS> depositMany() { return ctx -> { logger.log(Level.INFO, "Inside depositMany() action of PitStore"); int id = Integer.parseInt(ctx.getStateMachine().getId()); int totalPiecesInOppositePit = (int) ctx.getExtendedState().getVariables() .getOrDefault(StateParameters.TOTAL_PIECES_TO_DEPOSIT, 0); ctx.getExtendedState().getVariables().put(StateParameters.TOTAL_PIECES_TO_DEPOSIT, 0); if (totalPiecesInOppositePit > 1) { Pit pit = getPitObject(id); pit.setPieceCount(pit.getPieceCount() + totalPiecesInOppositePit); updatePitStateMachinePairList(id, pit); } }; } public void createStoreStateMachines(List<Pair<?, ?>> pitStateMachinePairList) { Pit[] arrayOfStore = createStoreObjects(); storeStateMachinePairList.clear(); logger.log(Level.INFO, "creating Store State Machines"); for (int i = 0; i < pitStateMachinePairList.size(); i++) { StateMachine<PitStates.PLAYERSTORESTATES, PitEvents.PLAYERSTOREEVENTS> storeStateMachine = null; if (i == StoreIndex.PLAYER_1_STORE.getValue() || i == StoreIndex.PLAYER_2_STORE.getValue()) { storeStateMachine = storeStateMachineConfiguration.storeStateMachineFactory .getStateMachine(String.valueOf(i)); storeStateMachine.start(); int j = (i == StoreIndex.PLAYER_1_STORE.getValue()) ? 0 : 1; pitStateMachinePairList.set(i, (Pair.with(arrayOfStore[j], storeStateMachine))); storeStateMachinePairList.add(Pair.with(arrayOfStore[j], storeStateMachine)); } } this.pitStateMachinePairList = pitStateMachinePairList; logger.log(Level.INFO, "all state machines are created..."); } private Pit[] createStoreObjects() { Pit[] arrayOfStore = new Pit[2]; logger.log(Level.INFO, "creating Pit Objects"); arrayOfStore[0] = new PlayerStoreImpl(StoreIndex.PLAYER_1_STORE.getValue(), StoreInitialPieceCounts.PLAYER_STORE.getValue(), "Player 1"); arrayOfStore[1] = new PlayerStoreImpl(StoreIndex.PLAYER_2_STORE.getValue(), StoreInitialPieceCounts.PLAYER_STORE.getValue(), "Player 2"); logger.log(Level.INFO, " 0th store piece count is : " + arrayOfStore[0].getPieceCount()); logger.log(Level.INFO, " 0th store name is : " + arrayOfStore[0].getPlayer()); logger.log(Level.INFO, " 1st store piece count is : " + arrayOfStore[1].getPieceCount()); logger.log(Level.INFO, " 1st store name is : " + arrayOfStore[1].getPlayer()); return arrayOfStore; } public boolean sendBulkEvent(PitEvents.PLAYERSTOREEVENTS event) { for (Pair<?, ?> pair : pitStateMachinePairList) { if ((Pit) pair.getValue0() != null && (((Pit) pair.getValue0()).getId() == StoreIndex.PLAYER_1_STORE.getValue() || ((Pit) pair.getValue0()).getId() == StoreIndex.PLAYER_2_STORE.getValue())) { @SuppressWarnings("unchecked") StateMachine<PitStates.PLAYERSTORESTATES, PitEvents.PLAYERSTOREEVENTS> sm = (StateMachine<PitStates.PLAYERSTORESTATES, PitEvents.PLAYERSTOREEVENTS>) pair .getValue1(); sm.sendEvent(event); } } return true; } @SuppressWarnings("unchecked") public boolean endPitStoreActions() { List<Pair<?, ?>> pitStateMachinePair = pitStateActions.getPitStateMachinePairList(); for (Pair<?, ?> pair : pitStateMachinePair) { if (((Pit) pair.getValue0()).getId() == StoreIndex.PLAYER_1_STORE.getValue() || ((Pit) pair.getValue0()).getId() == StoreIndex.PLAYER_2_STORE.getValue()) { ((StateMachine<PitStates.PLAYERSTORESTATES, PitEvents.PLAYERSTOREEVENTS>) pair.getValue1()).stop(); } } return true; } @Override public boolean initializePitStores() { sendBulkEvent(PitEvents.PLAYERSTOREEVENTS.REPLAY); return true; } }
35.035714
157
0.751274
263291f5f432104e1e51c75c3cdebcab72752890
8,338
package edu.unc.irss.arc.dataverse.client.util.zip; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.lang3.StringUtils; /** * Creates a zip file by using NIO2 API. * * @author asone */ public class FileZipper { private static final Logger logger = Logger.getLogger(FileZipper.class.getName()); final static Map<String, String> DEFAULT_ENV = new HashMap<>(); static { // see http://docs.oracle.com/javase/8/docs/technotes/guides/io/fsp/zipfilesystemproviderprops.html // there are two properties: create (true|false[default]) and encoding (default // value is UTF-8) | env.put("encoding", "UTF-8") DEFAULT_ENV.put("create", "true"); } private FileSystem createZipFileSystem(String zipFilename, boolean create) throws IOException { Path path = Paths.get(zipFilename); if (Files.exists(path)) { logger.log(Level.INFO, "the target zip file [{0}] already exists: delete it", path); Files.delete(path); } else { logger.log(Level.INFO, "the target zip file [{0}] does not exist", path); } //path = Paths.get(zipFilename); final URI uri = URI.create("jar:file:" + path.toUri().getPath()); logger.log(Level.INFO, "uri={0}", uri.toString()); final Map<String, String> env = new HashMap<>(); // see http://docs.oracle.com/javase/8/docs/technotes/guides/io/fsp/zipfilesystemproviderprops.html // there are two properties: create (true|false[default]) and encoding (default // value is UTF-8) if (create) { env.put("create", "true"); //env.put("encoding", "UTF-8"); } return FileSystems.newFileSystem(uri, env); } private FileSystem createZipFileSystem(String zipFilename) throws IOException { Path path = Paths.get(zipFilename); if (Files.exists(path)) { logger.log(Level.INFO, "the target zip file [{0}] already exists: delete it", path); Files.delete(path); } else { logger.log(Level.INFO, "the target zip file [{0}] does not exist", path); } URI uri = URI.create("jar:file:" + path.toUri().getPath()); logger.log(Level.INFO, "uri={0}", uri.toString()); return FileSystems.newFileSystem(uri, DEFAULT_ENV); } /** * Creates a zip file whose pathname is denoted by * {@code zipFilename} from {@code srcPath} with a relative path * {@code relativizeBase}. * * @param srcPath * @param relativizeBase * @param zipFilename */ public void create(Path srcPath, Path relativizeBase, String zipFilename) { logger.log(Level.INFO, "srcPath={0}", srcPath); logger.log(Level.INFO, "relativizeBase={0}", relativizeBase); try (FileSystem zipFileSystem = createZipFileSystem(zipFilename)) { logger.log(Level.INFO, "target is a directory"); Files.walkFileTree(srcPath, new FileVisitorForZipping(zipFileSystem, relativizeBase)); } catch (IOException ie) { logger.log(Level.INFO, "IOException was thrown from FileZipper#create()", ie); } } /** * Creates a zip file whose path is specified by the first one from * the second one. * * @param sourcePath the path to the source file or directory * @param zipPath the path to the resulting zip file */ public void create(Path sourcePath, Path zipPath) { try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(zipPath));) { Files.walk(sourcePath).filter(path -> !Files.isDirectory(path)).forEach(path -> { String sp = path.toAbsolutePath().toString().replace(sourcePath.toAbsolutePath().toString(), "").replace(path.getFileName().toString(), "").replace("\\", "/"); // the following works for dataverse logger.log(Level.INFO, "sp={0}", sp); logger.log(Level.INFO, "filename={0}", path.getFileName().toString()); sp = sp.replaceFirst("/", "") + path.getFileName().toString(); logger.log(Level.INFO, "sp={0}", sp); ZipEntry zipEntry = new ZipEntry(sp); // the following line uses "\" as a path-separator and // dataverse upload failure (2016-11-30) try { zs.putNextEntry(zipEntry); zs.write(Files.readAllBytes(path)); zs.closeEntry(); } catch (IOException ex) { logger.log(Level.SEVERE, "IO Exception was thrown within the inner loop", ex); } }); } catch (IOException ex) { logger.log(Level.SEVERE, "IO Exception was thrown from the outer loop", ex); } } /** * Creates a zip file whose pathname is specified by * the second pathname from the source file denoted by the first * pathname. * * @param sourceDirPath * @param zipFilePath */ public void create(String sourceDirPath, String zipFilePath) { Path p; Path pp; try { p = Files.createFile(Paths.get(zipFilePath)); pp = Paths.get(sourceDirPath); create(pp, p); } catch (IOException ex) { logger.log(Level.SEVERE, "IOException was thrown", ex); } } /** * Tests whether the file denoted by this pathname string is a zip file. * * @param pathString * @return {@code true} if the given pathname string points to a zip file ; * otherwise {@code false} */ public static boolean isZipFile(String pathString) { // null or blank test if (StringUtils.isBlank(pathString)) { return false; } File testFile = new File(pathString); if (testFile.exists() && !testFile.isDirectory()) { try (FileInputStream fis = new FileInputStream(testFile)) { return new ZipInputStream(fis).getNextEntry() != null; } catch (FileNotFoundException ex ) { logger.log(Level.SEVERE, "FileNotFoundException was thrown", ex); return false; } catch (IOException ex) { logger.log(Level.SEVERE, "IOException was thrown", ex); return false; } } else { logger.log(Level.INFO, "pathString[{0}] points to a directory", pathString); return false; } } /** * Tests whether the specified file is a zip file. * * @param payloadFile the file to be uploaded to the target dataset. * @return {@code true} if the given File is a zip file ; * otherwise {@code false} */ public static boolean isZipFile(File payloadFile) { // null test if (payloadFile == null) { return false; } if (payloadFile.exists() && !payloadFile.isDirectory()) { try (FileInputStream fis = new FileInputStream(payloadFile)) { return new ZipInputStream(fis).getNextEntry() != null; } catch (FileNotFoundException ex ) { logger.log(Level.SEVERE, "FileNotFoundException was thrown", ex); return false; } catch (IOException ex) { logger.log(Level.SEVERE, "IOException was thrown", ex); return false; } } else { logger.log(Level.INFO, "File[{0}] a directory; not a zip file", payloadFile); return false; } } }
34.887029
175
0.580955
845739eae9da51cd9ba773e78cf68b3a780e5412
1,271
package io.schinzel.basicutils.collections.valueswithkeys; import lombok.AllArgsConstructor; import lombok.Getter; import org.junit.Test; import java.util.Arrays; import java.util.List; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; public class IValueWithKeyTest { @AllArgsConstructor class MyClass implements IValueWithKey { final int mOrder; @Getter private final String key; } @Test public void compareTo() throws Exception { List<MyClass> list = Arrays.asList( new MyClass(2, "Ab"), new MyClass(1, "aa"), new MyClass(3, "B"), new MyClass(9, "tB"), new MyClass(4, "C"), new MyClass(5, "D"), new MyClass(7, "OB"), new MyClass(6, "oA"), new MyClass(8, "TA"), new MyClass(10, "Ö"), new MyClass(0, "-") ); list = list.stream().sorted().collect(toList()); int prev = -100; for (MyClass myClass : list) { int current = myClass.mOrder; assertThat(current).isGreaterThan(prev); prev = current; } } }
27.630435
58
0.553895
517365edff4484589dd5f45db0b6be763d0612d8
10,450
package frc.team7170.lib.networktables; import edu.wpi.first.networktables.*; import frc.team7170.lib.Name; import frc.team7170.lib.Named; import frc.team7170.lib.ReflectUtil; import java.lang.reflect.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; // TODO: make stuff optionally sendable // TODO: allow passing functional interfaces for communicators in addition to annotated methods/fields // TODO: POST-SEASON: Deprecate the entire annotation and use interface-based communicator registration to maintain type safety public final class Communication implements Named { private static final Logger LOGGER = Logger.getLogger(Communication.class.getName()); private static final String PATH_SEPARATOR = String.valueOf(NetworkTable.PATH_SEPARATOR); private static final String ENTRY_NAME_PREFIX_SEP = "_"; // TODO: TEMP // private final Commander commander = new Commander(NetworkTableInstance.getDefault(), getNameObject()); private final Map<String, Transmitter> transmitterMap = new HashMap<>(); private final Map<String, Receiver> receiverMap = new HashMap<>(); private Communication() {} private static final Communication INSTANCE = new Communication(); public static Communication getInstance() { return INSTANCE; } public void registerStaticCommunicator(Class<?> cls, Name name, NetworkTable table) { findCommAnnotations(null, cls, name, table); } public void registerStaticCommunicator(Class<?> cls, NetworkTable table) { registerStaticCommunicator(cls, Name.UNNAMED, table); } public void registerCommunicator(Named obj, NetworkTable table) { findCommAnnotations(obj, obj.getClass(), obj.getNameObject(), table); } private void findCommAnnotations(Object obj, Class<?> cls, Name prefix, NetworkTable table) { ReflectUtil.getMethodAnnotationStream(cls, Transmit.class).forEach(pair -> { Method method = pair.getLeft(); Transmit transmit = pair.getRight(); // Sanity checks. if (method.getAnnotation(Receive.class) != null) { throw new IllegalCommunicatorException("a method cannot be a transmitter and a receiver"); } doMethodAssertions(obj, method); ReflectUtil.assertParameterCount(method, 0); assertValidNTType(method.getReturnType()); NetworkTableEntry entry = resolveEntry(table, prefix, transmit.value(), method); Runnable runnable = () -> invokeWithHandling(entry::setValue, method, obj); newTransmitter(runnable, transmit.pollRateMs(), entry); }); ReflectUtil.getMethodAnnotationStream(cls, Receive.class).forEach(pair -> { Method method = pair.getLeft(); Receive receive = pair.getRight(); // Sanity checks. doMethodAssertions(obj, method); ReflectUtil.assertParameterCount(method, 1); ReflectUtil.assertReturnType(method, void.class); Consumer<EntryNotification> consumer; Consumer<Object> retConsumer = (x) -> {}; // Return type is void! Class<?> paramType = method.getParameterTypes()[0]; if (paramType == EntryNotification.class) { consumer = notification -> invokeWithHandling(retConsumer, method, obj, notification); } else if (paramType == NetworkTableValue.class) { consumer = notification -> invokeWithHandling(retConsumer, method, obj, notification.value); } else if (isValidNTType(paramType)) { consumer = notification -> invokeWithHandling(retConsumer, method, obj, notification.value.getValue()); } else { throw new IllegalCommunicatorException("invalid method parameter type; expected one of: " + "'EntryNotification', 'NetworkTableValue', or any valid networktables type"); } NetworkTableEntry entry = resolveEntry(table, prefix, receive.value(), method); newReceiver(consumer, receive.flags(), entry); }); ReflectUtil.getFieldAnnotationStream(cls, CommField.class).forEach(pair -> { Field field = pair.getLeft(); CommField commField = pair.getRight(); // Sanity checks. doFieldAssertions(obj, field); NetworkTableEntry entry = resolveEntry(table, prefix, commField.value(), field); if (commField.transmit()) { Runnable runnable = () -> { try { tryMakeAccessible(field); entry.setValue(field.get(obj)); } catch (IllegalAccessException e) { LOGGER.log(Level.SEVERE, "Failed to access field.", e); } }; newTransmitter(runnable, commField.pollRateMs(), entry); } if (commField.receive()) { ReflectUtil.assertNonFinal(field); Consumer<EntryNotification> consumer = notification -> { try { tryMakeAccessible(field); field.set(obj, notification.value.getValue()); } catch (IllegalAccessException e) { LOGGER.log(Level.SEVERE, "Failed to access field.", e); } }; newReceiver(consumer, commField.flags(), entry); } }); } private void newTransmitter(Runnable runnable, int pollRateMs, NetworkTableEntry entry) { Transmitter transmitter = new Transmitter(runnable, pollRateMs, entry); if (!transmitter.start()) { transmitter.invoke(); } Transmitter old = transmitterMap.put(transmitter.getName(), transmitter); if (old != null) { LOGGER.warning(String.format("More than one transmitter with name '%s' registered; removing oldest one.", old.getName())); old.cancel(); } } private void newReceiver(Consumer<EntryNotification> consumer, int flags, NetworkTableEntry entry) { Receiver receiver = new Receiver(consumer, flags, entry); receiver.start(); Receiver old = receiverMap.put(receiver.getName(), receiver); if (old != null) { LOGGER.warning(String.format("More than one receiver with name '%s' registered; removing oldest one.", old.getName())); old.cancel(); } } private static void doMethodAssertions(Object obj, Method method) { assertStaticness(obj, method); ReflectUtil.assertInvokable(method); } private static void doFieldAssertions(Object obj, Field field) { assertStaticness(obj, field); assertValidNTType(field.getType()); } private static void tryMakeAccessible(AccessibleObject accessibleObject) { if (!accessibleObject.trySetAccessible()) { LOGGER.warning("Failed to make object accessible."); } } private static void assertStaticness(Object obj, Member member) { boolean isStatic = Modifier.isStatic(member.getModifiers()); if (!((obj != null && !isStatic) || (obj == null && isStatic))) { throw new IllegalCommunicatorException("obj given for static communicator or no obj given for instance communicator"); } } private static final ArrayList<Class<?>> PRIMITIVE_NUMBER_TYPES = new ArrayList<>(6); static { PRIMITIVE_NUMBER_TYPES.add(byte.class); PRIMITIVE_NUMBER_TYPES.add(short.class); PRIMITIVE_NUMBER_TYPES.add(int.class); PRIMITIVE_NUMBER_TYPES.add(long.class); PRIMITIVE_NUMBER_TYPES.add(float.class); PRIMITIVE_NUMBER_TYPES.add(double.class); } private static boolean isValidNTType(Class<?> cls) { if (cls.isArray()) { cls = cls.getComponentType(); } if ((cls == boolean.class) || (cls == Boolean.class)) { return true; } else if (Number.class.isAssignableFrom(cls) || PRIMITIVE_NUMBER_TYPES.contains(cls)) { return true; } else if (cls == String.class) { return true; } else if (cls == NetworkTableValue.class) { return true; } return false; } private static void assertValidNTType(Class<?> cls) { if (!isValidNTType(cls)) { throw new IllegalCommunicatorException("(return/parameter) type is not one of valid networktables types"); } } private static void invokeWithHandling(Consumer<Object> retConsumer, Method method, Object obj, Object... args) { tryMakeAccessible(method); try { retConsumer.accept(method.invoke(obj, (Object[]) args)); } catch (IllegalAccessException e) { LOGGER.log(Level.SEVERE, "Failed to access method.", e); } catch (InvocationTargetException e) { LOGGER.log(Level.SEVERE, "Communicator callback threw an exception.", e); } } private static NetworkTableEntry resolveEntry(NetworkTable baseTable, Name prefix, String key, Member member) { String[] keyComponents; if (key.isEmpty()) { keyComponents = new String[] {member.getName()}; } else { keyComponents = decomposeKey(key); for (String kc : keyComponents) { Name.requireValidName(kc); } } NetworkTable table = baseTable; for (int i = 0; i < keyComponents.length - 1; ++i) { table = table.getSubTable(keyComponents[i]); } String entryName = keyComponents[keyComponents.length - 1]; if (!prefix.equals(Name.UNNAMED)) { entryName = prefix + ENTRY_NAME_PREFIX_SEP + entryName; } return table.getEntry(entryName); } private static String[] decomposeKey(String key) { if (key.startsWith(PATH_SEPARATOR)) { key = key.substring(1); } if (key.endsWith(PATH_SEPARATOR)) { key = key.substring(0, key.length() - 1); } return key.split(PATH_SEPARATOR); } @Override public String getName() { return "communication"; } }
40.820313
134
0.623445
9fe9f4b61b8c2f9bd040e300ed02cf89d03623a3
6,158
package com.aliyun.alink.linksdk.channel.core.persistent.mqtt.send; import android.content.Context; import android.text.TextUtils; import com.aliyun.alink.linksdk.channel.core.base.ASend; import com.aliyun.alink.linksdk.channel.core.persistent.BadNetworkException; import com.aliyun.alink.linksdk.channel.core.persistent.ISendExecutor; import com.aliyun.alink.linksdk.channel.core.persistent.PersistentConnectState; import com.aliyun.alink.linksdk.channel.core.persistent.mqtt.MqttNet; import com.aliyun.alink.linksdk.channel.core.persistent.mqtt.request.MqttPublishRequest; import com.aliyun.alink.linksdk.channel.core.persistent.mqtt.request.MqttSubscribeRequest; import com.aliyun.alink.linksdk.channel.core.persistent.mqtt.utils.MqttAlinkProtocolHelper; import com.aliyun.alink.linksdk.tools.ALog; import com.aliyun.alink.linksdk.tools.NetTools; import org.eclipse.paho.client.mqttv3.IMqttAsyncClient; import org.eclipse.paho.client.mqttv3.MqttMessage; /** * Created by huanyu.zhy on 17/11/7. * * Mqtt 发送执行类,执行Publish Subcribe UnSubsribe 等请求 */ public class MqttSendExecutor implements ISendExecutor { private static final String TAG = "MqttSendExecutor"; @Override public void asyncSend(ASend send) { if (null == send || null == send.getRequest()) { ALog.e(TAG, "asyncSend(): bad parameters: NULL"); return; } IMqttAsyncClient mqttAsyncClient = MqttNet.getInstance().getClient(); if (null == mqttAsyncClient) { ALog.e(TAG, "asyncSend(): MqttNet::getClient() return null"); return; } if (!(send instanceof MqttSend)) { ALog.d(TAG, "asyncSend(): bad parameter: need MqttSend"); return; } MqttSend mqttSend = (MqttSend) send; // bad network Context context = MqttNet.getInstance().getContext(); if (null != context && !NetTools.isAvailable(context)) { mqttSend.setStatus(MqttSendStatus.completed); mqttSend.onFailure(null, new BadNetworkException()); return; } //gateway disconnect if (MqttNet.getInstance().getConnectState() != PersistentConnectState.CONNECTED) { mqttSend.setStatus(MqttSendStatus.completed); mqttSend.onFailure(null, new BadNetworkException()); return; } //handle mqtt publish req if (send.getRequest() instanceof MqttPublishRequest) { MqttPublishRequest publishRequest = (MqttPublishRequest) send.getRequest(); if (TextUtils.isEmpty(publishRequest.topic) || publishRequest.payloadObj == null) { ALog.e(TAG, "asyncSend(): bad parameters: topic or payload empty"); return; } //RPC 请求,需要先订阅reply (complete 为 retry场景) if (publishRequest.isRPC && (mqttSend.getStatus() == MqttSendStatus.waitingToSend || mqttSend.getStatus() == MqttSendStatus.completed)) { try{ publishRequest.msgId = MqttAlinkProtocolHelper.parseMsgIdFromPayload(publishRequest.payloadObj.toString()); if (TextUtils.isEmpty(publishRequest.replyTopic)) publishRequest.replyTopic = publishRequest.topic+"_reply"; ALog.d(TAG,"publish: RPC sub reply topic: [ "+publishRequest.replyTopic+" ]"); mqttSend.setStatus(MqttSendStatus.waitingToSubReply); mqttAsyncClient.subscribe(publishRequest.replyTopic,0,null,mqttSend,mqttSend); }catch (Exception e){ ALog.d(TAG,"asyncSend(), publish , send subsribe reply error, e = "+e.toString()); mqttSend.setStatus(MqttSendStatus.completed); mqttSend.onFailure(null,new MqttThrowable(e.getMessage())); } } else { try { String content = publishRequest.payloadObj.toString(); ALog.d(TAG,"publish: topic: [ "+publishRequest.topic+" ]"); ALog.d(TAG,"publish: payload: [ "+content+" ]"); MqttMessage message = new MqttMessage(content.getBytes("utf-8")); message.setQos(0); // isRPC 已订阅过了 if (publishRequest.isRPC) { mqttSend.setStatus(MqttSendStatus.waitingToPublish); }else { mqttSend.setStatus(MqttSendStatus.waitingToComplete); } mqttAsyncClient.publish(publishRequest.topic, message, null, mqttSend); } catch (Exception e) { ALog.d(TAG, "asyncSend(), send publish error, e = " + e.toString()); mqttSend.setStatus(MqttSendStatus.completed); mqttSend.onFailure(null, new MqttThrowable(e.getMessage())); } } } // handle mqtt subscribe req else if (send.getRequest() instanceof MqttSubscribeRequest) { MqttSubscribeRequest subscribeRequest = (MqttSubscribeRequest) send.getRequest(); if (TextUtils.isEmpty(subscribeRequest.topic)) { ALog.e(TAG, "asyncSend(): bad parameters: subsribe req , topic empty"); return; } try{ mqttSend.setStatus(MqttSendStatus.waitingToComplete); if (subscribeRequest.isSubscribe){ ALog.d(TAG,"subscribe: topic: [ "+subscribeRequest.topic+" ]"); mqttAsyncClient.subscribe(subscribeRequest.topic,0,null,mqttSend); } else { ALog.d(TAG,"unsubscribe: topic: [ "+subscribeRequest.topic+" ]"); mqttAsyncClient.unsubscribe(subscribeRequest.topic,null,mqttSend); } }catch (Exception e){ ALog.d(TAG,"asyncSend(), send subsribe error, e = "+e.toString()); mqttSend.setStatus(MqttSendStatus.completed); mqttSend.onFailure(null,new MqttThrowable(e.getMessage())); } } } }
43.673759
149
0.609938
471e1a163446b3818419728e4f45e2986dbf923d
4,201
package com.example.feedbackapp.ui.classs; import androidx.lifecycle.ViewModelProvider; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.feedbackapp.Adapter.TraineeOfClassAdapter; import com.example.feedbackapp.ModelClassToReceiveFromAPI.Class.ClassInfo; import com.example.feedbackapp.ModelClassToReceiveFromAPI.Class.Classs; import com.example.feedbackapp.ModelClassToReceiveFromAPI.Class.TraineeForClass; import com.example.feedbackapp.R; import com.example.feedbackapp.RetrofitAPISetvice.ClassAPIService; import com.example.feedbackapp.UserInfo.UserInfo; import java.util.ArrayList; import java.util.Arrays; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ShowTraineeOfClassFragment extends Fragment{ private ShowTraineeOfClassViewModel mViewModel; TextView txtTraineeListClassID, txtTraineeListClassName; Button btnBack; String classID; TraineeOfClassAdapter traineeAdapter; Classs classs; ClassInfo classInfo; ArrayList<TraineeForClass> traineeList; RecyclerView rcvTraineeList; public static ShowTraineeOfClassFragment getInstance() { return new ShowTraineeOfClassFragment(); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.show_trainee_of_class_fragment, container, false); try{ classID = getArguments().getString("ClassId"); LoadTrainee(root); } catch(Exception ex) { } txtTraineeListClassID = root.findViewById(R.id.txt_TraineeListClassID); txtTraineeListClassName = root.findViewById(R.id.txt_TraineeListClassName); btnBack = root.findViewById(R.id.btn_TraineeListBack); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // FragmentManager fragmentManager = getFragmentManager(); // if(fragmentManager.getBackStackEntryCount()>0){ // fragmentManager.popBackStack(); // } Navigation.findNavController(v).navigate(R.id.show_trainee_back_to_class); } }); rcvTraineeList = root.findViewById(R.id.rcv_TraineeList); rcvTraineeList.setLayoutManager(new LinearLayoutManager(getActivity())); return root; } void LoadTrainee(View root){ ClassAPIService.classAPIService.getClass("Bearer "+ new UserInfo(getContext()).token(),classID).enqueue(new Callback<ClassInfo>() { @Override public void onResponse(Call<ClassInfo> call, Response<ClassInfo> response) { if(response.isSuccessful()){ classInfo = response.body(); setLayoutValue(root); } } @Override public void onFailure(Call<ClassInfo> call, Throwable t) { } }); } void setLayoutValue(View root){ classs = classInfo.getClass_res(); txtTraineeListClassID.setText(classs.getId()); txtTraineeListClassName.setText(classs.getClassName()); traineeList = new ArrayList<TraineeForClass>(Arrays.asList(classs.getListTrainee())); traineeAdapter = new TraineeOfClassAdapter(root.getContext(),traineeList); rcvTraineeList.setAdapter(traineeAdapter); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel = new ViewModelProvider(this).get(ShowTraineeOfClassViewModel.class); // TODO: Use the ViewModel } }
37.176991
139
0.711021
55fa2ec1c367259a70f2a1e2bfbd32c1dd591f06
8,524
package com.andretissot.firebaseextendednotification; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Notification.BigPictureStyle; import android.app.Notification.BigTextStyle; import android.app.Notification.InboxStyle; import android.app.Notification.Builder; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.media.AudioAttributes; import android.os.Build; import android.service.notification.StatusBarNotification; import com.gae.scaffolder.plugin.*; import java.util.*; import org.json.*; /** * Created by André Augusto Tissot on 15/10/16. */ public class Manager { protected Context context; public Manager(Context context) { this.context = context; } public boolean notificationExists(int notificationId) { NotificationManager notificationManager = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE); if (android.os.Build.VERSION.SDK_INT >= 23) { StatusBarNotification[] notifications = notificationManager .getActiveNotifications(); for (StatusBarNotification notification : notifications) if (notification.getId() == notificationId) return true; return false; } //If lacks support return true; } public void cancelNotification(int notificationId){ NotificationManager notificationManager = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(notificationId); } public void showNotification(JSONObject dataToReturnOnClick, JSONObject notificationOptions){ Options options = new Options(notificationOptions, this.context.getApplicationContext()); this.createNotificationChannel(options); Notification.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { builder = new Notification.Builder(this.context, options.getChannelId()); } else { builder = new Notification.Builder(this.context); } builder.setDefaults(0) .setContentTitle(options.getTitle()).setSmallIcon(options.getSmallIconResourceId()) .setLargeIcon(options.getLargeIconBitmap()).setAutoCancel(options.doesAutoCancel()); if(options.getBigPictureBitmap() != null) builder.setStyle(new BigPictureStyle().bigPicture(options.getBigPictureBitmap())); if(options.doesVibrate() && options.getVibratePattern() != null) builder.setVibrate(options.getVibratePattern()); else if (Build.VERSION.SDK_INT >= 21 && options.doesHeadsUp()) builder.setVibrate(new long[0]); if(options.doesHeadsUp()) { builder.setPriority(Notification.PRIORITY_HIGH); } if(options.doesSound() && options.getSoundUri() != null) builder.setSound(options.getSoundUri(), android.media.AudioManager.STREAM_NOTIFICATION); if (options.doesColor() && Build.VERSION.SDK_INT >= 22) builder.setColor(options.getColor()); this.setContentTextAndMultiline(builder, options); this.setOnClick(builder, dataToReturnOnClick); Notification notification; if (Build.VERSION.SDK_INT < 16) { notification = builder.getNotification(); // Notification for HoneyComb to ICS } else { notification = builder.build(); // Notification for Jellybean and above } if(options.doesAutoCancel()) notification.flags |= Notification.FLAG_AUTO_CANCEL; if(options.doesVibrate() && options.getVibratePattern() == null) notification.defaults |= Notification.DEFAULT_VIBRATE; if(options.doesSound() && options.getSoundUri() == null) notification.defaults |= Notification.DEFAULT_SOUND; NotificationManager notificationManager = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(options.getId(), notification); if(options.doesOpenApp()) openApp(); } private void setContentTextAndMultiline(Builder builder, Options options) { String bigText = options.getBigText(); String text = options.getText(); if(bigText != null && !bigText.isEmpty()){ builder.setStyle(new BigTextStyle().bigText(bigText).setSummaryText(options.getSummary())); builder.setContentText(text).setTicker(options.getTicker()); return; } if(text != null && !text.isEmpty()){ String ticker = options.getTicker(); if(ticker == null) { ticker = text; } builder.setContentText(text).setTicker(ticker); return; } String[] textLines = options.getTextLines(); if(textLines == null || textLines.length == 0) { return; } if(textLines.length == 1) { String ticker = options.getTicker(); if(ticker == null) { ticker = textLines[0]; } builder.setContentText(textLines[0]).setTicker(ticker); return; } InboxStyle inboxStyle = new InboxStyle(); for(String line : textLines) inboxStyle.addLine(line); String summary = options.getSummary(); builder.setStyle(inboxStyle.setSummaryText(summary)); String ticker = options.getTicker(); if(ticker == null) { ticker = summary; } builder.setContentText(summary).setTicker(ticker); } private void setOnClick(Builder builder, JSONObject dataToReturnOnClick) { Intent intent = new Intent(this.context, NotificationActivity.class).setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); Iterator<?> keys = dataToReturnOnClick.keys(); while (keys.hasNext()) { String key = (String) keys.next(); Object value; try { value = dataToReturnOnClick.get(key); } catch(JSONException e){ value = null; } intent.putExtra(key, value == null ? null : value.toString()); } int reqCode = new Random().nextInt(); PendingIntent contentIntent = PendingIntent.getActivity( this.context, reqCode, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(contentIntent); } private void openApp(){ PackageManager manager = this.context.getPackageManager(); Context context = this.context.getApplicationContext(); Intent launchIntent = manager.getLaunchIntentForPackage(context.getPackageName()); context.startActivity(launchIntent); } private void createNotificationChannel(Options options) { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { int importance = NotificationManager.IMPORTANCE_DEFAULT; if(options.doesHeadsUp()) { importance = NotificationManager.IMPORTANCE_HIGH; } else if(!options.doesSound()) { importance = NotificationManager.IMPORTANCE_LOW; } NotificationChannel channel = new NotificationChannel(options.getChannelId(), options.getChannelName(), importance); if(options.doesHeadsUp()) { channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); } channel.setDescription(options.getChannelDescription()); if(options.doesSound() && options.getSoundUri() != null) { AudioAttributes audioAttributes = new AudioAttributes.Builder() .setLegacyStreamType(android.media.AudioManager.STREAM_NOTIFICATION) .build(); channel.setSound(options.getSoundUri(), audioAttributes); } // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManager notificationManager = this.context.getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } } }
45.582888
128
0.660371
f7883b8c00578904dee09dcf8dbfce9e2831dd38
2,192
/* * Copyright 2021 EPAM Systems. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.epam.digital.data.platform.reportexporter.controller; import com.epam.digital.data.platform.reportexporter.model.Dashboard; import java.util.List; import com.epam.digital.data.platform.reportexporter.service.ReportService; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/reports") public class ReportController { private static final String CONTENT_DISPOSITION_HEADER_NAME = "Content-Disposition"; private static final String ATTACHMENT_HEADER_VALUE = "attachment; filename=\"dashboard_%s.zip\""; private final ReportService service; public ReportController( ReportService service) { this.service = service; } @GetMapping public ResponseEntity<List<Dashboard>> getAllDashboards() { return ResponseEntity.ok().body(service.getDashboards()); } @GetMapping(path = "/{slug_id}") public ResponseEntity<Resource> getDashboardArchive(@PathVariable("slug_id") String slugId) { var zip = service.getArchive(slugId); return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .contentLength(zip.getByteArray().length) .header(CONTENT_DISPOSITION_HEADER_NAME, String.format(ATTACHMENT_HEADER_VALUE, slugId)) .body(zip); } }
36.533333
100
0.773723
0650aad2ea9df44e2372803ac28fd0cb07fa0c3d
853
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package uk.gov.ipo.renewals.model; import java.time.LocalDate; import java.time.format.DateTimeFormatter; /** * * @author simon chance */ public class NonWorkingDay { static final long serialVersionUID = 1L; private LocalDate date; public NonWorkingDay(String date) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy"); this.date = LocalDate.parse(date, formatter); } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } @Override public String toString() { return "nonWorkingDate{" + "date=" + date + "}"; } }
19.837209
79
0.671747
713ae1f1687a5fbbb69bf98fa5a3da79c50aa395
3,087
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package csc212hw8; /** * * @author jregistr */ public class BinaryTreeNode { public String value; public BinaryTreeNode left, right; public BinaryTreeNode (String v){ value = v; left = null; right = null; } public BinaryTreeNode insert(String v){ if(v.compareTo(value) > 0 ){ if(right == null){ BinaryTreeNode temp = new BinaryTreeNode (v); right = temp; return temp; }else{ return right.insert(v); } }else { if(left == null){ left = new BinaryTreeNode (v); return left; }else{ return left.insert(v); } } } // public void insert(String v){ // if(v.compareTo(value) > 0 ){ // if(right == null){ // BinaryTreeNode temp = new BinaryTreeNode (v); // right = temp; // }else{ // right.insert(v); // } // }else if (v.compareTo(value) < 0 ){ // if(left == null){ // left = new BinaryTreeNode (v); // }else{ // left.insert(v); // } // } // } public boolean contains(String v) { if (v.equals(value)) { return true; } else if (left == null && right == null) { return false; } else if (v.compareTo(value) >= 0) { if (right != null) { return right.contains(v); } else { return false; } } else { if (left != null) { return left.contains(v); } else { return false; } } } public void printInOrder() { // Recurse - Go left if (left != null) { left.printInOrder(); } // Base case - Print the current node System.out.print(String.format("[%s]", value)); // Recurse - Go right if (right != null) { right.printInOrder(); } } public void printPostOrder(){ if (left != null) { left.printPostOrder(); } if (right != null) { right.printPostOrder(); } System.out.print(String.format("[%s]", value)); } public void printPreOrder(){ // Base case - Print the current node System.out.print(String.format("[%s]", value)); if (left != null) { left.printPreOrder(); } if (right != null) { right.printPreOrder(); } } }
26.384615
65
0.396501
8ce786efce74a0806d48a20db496dfc157c1b58c
624
package io.vertx.up.annotations; import java.lang.annotation.*; /** * Event bus annotation * If it's annotated on method, it means that this action enabled event bus. * Otherwise use sync response directly. * Address/Out should be matching * Address -> The component will send message to event bus ( EndPoint ) * Out -> The component will consume message to event bus. ( Worker ) */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface Address { /** * Target address * * @return String address value on EventBus */ String value(); }
24.96
76
0.703526
386abf8d30aa58e6d3734c63b9909cd4c7b1cf1b
7,850
package net.minecraft.world.level.levelgen.feature; import com.mojang.serialization.Codec; import java.util.Random; import net.minecraft.core.BlockPos; import net.minecraft.core.SectionPos; import net.minecraft.tags.BlockTags; import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.BaseStoneSource; import net.minecraft.world.level.levelgen.feature.configurations.BlockStateConfiguration; import net.minecraft.world.level.material.Material; public class LakeFeature extends Feature<BlockStateConfiguration> { private static final BlockState AIR = Blocks.CAVE_AIR.defaultBlockState(); public LakeFeature(Codec<BlockStateConfiguration> p_66259_) { super(p_66259_); } public boolean place(FeaturePlaceContext<BlockStateConfiguration> p_159958_) { BlockPos blockpos = p_159958_.origin(); WorldGenLevel worldgenlevel = p_159958_.level(); Random random = p_159958_.random(); BlockStateConfiguration blockstateconfiguration; for(blockstateconfiguration = p_159958_.config(); blockpos.getY() > worldgenlevel.getMinBuildHeight() + 5 && worldgenlevel.isEmptyBlock(blockpos); blockpos = blockpos.below()) { } if (blockpos.getY() <= worldgenlevel.getMinBuildHeight() + 4) { return false; } else { blockpos = blockpos.below(4); if (worldgenlevel.startsForFeature(SectionPos.of(blockpos), StructureFeature.VILLAGE).findAny().isPresent()) { return false; } else { boolean[] aboolean = new boolean[2048]; int i = random.nextInt(4) + 4; for(int j = 0; j < i; ++j) { double d0 = random.nextDouble() * 6.0D + 3.0D; double d1 = random.nextDouble() * 4.0D + 2.0D; double d2 = random.nextDouble() * 6.0D + 3.0D; double d3 = random.nextDouble() * (16.0D - d0 - 2.0D) + 1.0D + d0 / 2.0D; double d4 = random.nextDouble() * (8.0D - d1 - 4.0D) + 2.0D + d1 / 2.0D; double d5 = random.nextDouble() * (16.0D - d2 - 2.0D) + 1.0D + d2 / 2.0D; for(int l = 1; l < 15; ++l) { for(int i1 = 1; i1 < 15; ++i1) { for(int j1 = 1; j1 < 7; ++j1) { double d6 = ((double)l - d3) / (d0 / 2.0D); double d7 = ((double)j1 - d4) / (d1 / 2.0D); double d8 = ((double)i1 - d5) / (d2 / 2.0D); double d9 = d6 * d6 + d7 * d7 + d8 * d8; if (d9 < 1.0D) { aboolean[(l * 16 + i1) * 8 + j1] = true; } } } } } for(int k1 = 0; k1 < 16; ++k1) { for(int k2 = 0; k2 < 16; ++k2) { for(int k = 0; k < 8; ++k) { boolean flag = !aboolean[(k1 * 16 + k2) * 8 + k] && (k1 < 15 && aboolean[((k1 + 1) * 16 + k2) * 8 + k] || k1 > 0 && aboolean[((k1 - 1) * 16 + k2) * 8 + k] || k2 < 15 && aboolean[(k1 * 16 + k2 + 1) * 8 + k] || k2 > 0 && aboolean[(k1 * 16 + (k2 - 1)) * 8 + k] || k < 7 && aboolean[(k1 * 16 + k2) * 8 + k + 1] || k > 0 && aboolean[(k1 * 16 + k2) * 8 + (k - 1)]); if (flag) { Material material = worldgenlevel.getBlockState(blockpos.offset(k1, k, k2)).getMaterial(); if (k >= 4 && material.isLiquid()) { return false; } if (k < 4 && !material.isSolid() && worldgenlevel.getBlockState(blockpos.offset(k1, k, k2)) != blockstateconfiguration.state) { return false; } } } } } for(int l1 = 0; l1 < 16; ++l1) { for(int l2 = 0; l2 < 16; ++l2) { for(int l3 = 0; l3 < 8; ++l3) { if (aboolean[(l1 * 16 + l2) * 8 + l3]) { BlockPos blockpos2 = blockpos.offset(l1, l3, l2); boolean flag1 = l3 >= 4; worldgenlevel.setBlock(blockpos2, flag1 ? AIR : blockstateconfiguration.state, 2); if (flag1) { worldgenlevel.getBlockTicks().scheduleTick(blockpos2, AIR.getBlock(), 0); this.markAboveForPostProcessing(worldgenlevel, blockpos2); } } } } } for(int i2 = 0; i2 < 16; ++i2) { for(int i3 = 0; i3 < 16; ++i3) { for(int i4 = 4; i4 < 8; ++i4) { if (aboolean[(i2 * 16 + i3) * 8 + i4]) { BlockPos blockpos3 = blockpos.offset(i2, i4 - 1, i3); if (isDirt(worldgenlevel.getBlockState(blockpos3)) && worldgenlevel.getBrightness(LightLayer.SKY, blockpos.offset(i2, i4, i3)) > 0) { Biome biome = worldgenlevel.getBiome(blockpos3); if (biome.getGenerationSettings().getSurfaceBuilderConfig().getTopMaterial().is(Blocks.MYCELIUM)) { worldgenlevel.setBlock(blockpos3, Blocks.MYCELIUM.defaultBlockState(), 2); } else { worldgenlevel.setBlock(blockpos3, Blocks.GRASS_BLOCK.defaultBlockState(), 2); } } } } } } if (blockstateconfiguration.state.getMaterial() == Material.LAVA) { BaseStoneSource basestonesource = p_159958_.chunkGenerator().getBaseStoneSource(); for(int j3 = 0; j3 < 16; ++j3) { for(int j4 = 0; j4 < 16; ++j4) { for(int l4 = 0; l4 < 8; ++l4) { boolean flag2 = !aboolean[(j3 * 16 + j4) * 8 + l4] && (j3 < 15 && aboolean[((j3 + 1) * 16 + j4) * 8 + l4] || j3 > 0 && aboolean[((j3 - 1) * 16 + j4) * 8 + l4] || j4 < 15 && aboolean[(j3 * 16 + j4 + 1) * 8 + l4] || j4 > 0 && aboolean[(j3 * 16 + (j4 - 1)) * 8 + l4] || l4 < 7 && aboolean[(j3 * 16 + j4) * 8 + l4 + 1] || l4 > 0 && aboolean[(j3 * 16 + j4) * 8 + (l4 - 1)]); if (flag2 && (l4 < 4 || random.nextInt(2) != 0)) { BlockState blockstate = worldgenlevel.getBlockState(blockpos.offset(j3, l4, j4)); if (blockstate.getMaterial().isSolid() && !blockstate.is(BlockTags.LAVA_POOL_STONE_CANNOT_REPLACE)) { BlockPos blockpos1 = blockpos.offset(j3, l4, j4); worldgenlevel.setBlock(blockpos1, basestonesource.getBaseBlock(blockpos1), 2); this.markAboveForPostProcessing(worldgenlevel, blockpos1); } } } } } } if (blockstateconfiguration.state.getMaterial() == Material.WATER) { for(int j2 = 0; j2 < 16; ++j2) { for(int k3 = 0; k3 < 16; ++k3) { int k4 = 4; BlockPos blockpos4 = blockpos.offset(j2, 4, k3); if (worldgenlevel.getBiome(blockpos4).shouldFreeze(worldgenlevel, blockpos4, false)) { worldgenlevel.setBlock(blockpos4, Blocks.ICE.defaultBlockState(), 2); } } } } return true; } } } }
50.974026
393
0.483312
e159b0f3382c4ce5ff25113d6d6a568dbb444547
891
package com.example.cihan.eczanebul; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; public class NobetciActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nobetci); Database database = Database.getInstance(this); ArrayList<String> list = database.nobetciBul(getIntent().getFloatExtra("x",-1),getIntent().getFloatExtra("y",-1)); RecyclerView rv = (RecyclerView)findViewById(R.id.nobetciRecyclerView); rv.setLayoutManager(new LinearLayoutManager(this)); EczaneAdapter adapter = new EczaneAdapter(list,this); rv.setAdapter(adapter); } }
34.269231
122
0.747475
e43e3f9bf5484f2f8c144cd52567529ac4e2e1f0
731
package Release_VIII.B_Chapter_12.P1_EnumDemo; public class EnumDemo { public static void main(String[] args) { Apple ap = Apple.RedDel; System.out.println("Wartość ap = " +ap +"\n"); ap = Apple.GoldenDel; if(ap == Apple.GoldenDel) { System.out.println("ap zawiera GoldenDel. \n"); } switch(ap) { case Jonathan: System.out.println("Jonathan jest czerwone."); break; case GoldenDel: System.out.println("Golden Delicious jest zlote"); break; case RedDel: System.out.println("Red Delicious jest czerwone."); break; case Winesap: System.out.println("Winesap jest czerwone."); break; case Cortland: System.out.println("Cortland jest czerwone."); break; } } }
19.756757
54
0.662107
64e65cd92edea594657f237b8d5b5ac50e6d8113
15,181
package io.jenkins.plugins.checks.steps; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import edu.hm.hafner.util.VisibleForTesting; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.Run; import hudson.model.TaskListener; import hudson.util.ListBoxModel; import io.jenkins.plugins.checks.api.ChecksAction; import io.jenkins.plugins.checks.api.ChecksAnnotation; import io.jenkins.plugins.checks.api.ChecksConclusion; import io.jenkins.plugins.checks.api.ChecksDetails; import io.jenkins.plugins.checks.api.ChecksOutput; import io.jenkins.plugins.checks.api.ChecksPublisherFactory; import io.jenkins.plugins.checks.api.ChecksStatus; /** * Pipeline step to publish customized checks. */ @SuppressWarnings({"PMD.DataClass", "PMD.ExcessivePublicCount"}) public class PublishChecksStep extends Step implements Serializable { private static final long serialVersionUID = 1L; private String name = StringUtils.EMPTY; private String summary = StringUtils.EMPTY; private String title = StringUtils.EMPTY; private String text = StringUtils.EMPTY; private String detailsURL = StringUtils.EMPTY; private ChecksStatus status = ChecksStatus.COMPLETED; private ChecksConclusion conclusion = ChecksConclusion.SUCCESS; private List<StepChecksAction> actions = Collections.emptyList(); private List<StepChecksAnnotation> annotations = Collections.emptyList(); /** * Constructor used for pipeline by Stapler. */ @DataBoundConstructor public PublishChecksStep() { super(); } @DataBoundSetter public void setName(final String name) { this.name = name; } @DataBoundSetter public void setSummary(final String summary) { this.summary = summary; } @DataBoundSetter public void setTitle(final String title) { this.title = title; } @DataBoundSetter public void setText(final String text) { this.text = text; } @DataBoundSetter public void setDetailsURL(final String detailsURL) { this.detailsURL = detailsURL; } /** * Change the status of the check. * When the {@code status} is {@link ChecksStatus#QUEUED} or {@link ChecksStatus#IN_PROGRESS}, * the conclusion will be reset to {@link ChecksConclusion#NONE} * * @param status * the status to be set */ @DataBoundSetter public void setStatus(final ChecksStatus status) { this.status = status; if (status == ChecksStatus.QUEUED || status == ChecksStatus.IN_PROGRESS) { this.conclusion = ChecksConclusion.NONE; } } @DataBoundSetter public void setConclusion(final ChecksConclusion conclusion) { this.conclusion = conclusion; } @DataBoundSetter public void setActions(final List<StepChecksAction> actions) { this.actions = actions; } @DataBoundSetter public void setAnnotations(final List<StepChecksAnnotation> annotations) { this.annotations = annotations; } public String getName() { return name; } public String getSummary() { return summary; } public String getTitle() { return StringUtils.defaultIfEmpty(title, name); } public String getText() { return text; } public String getDetailsURL() { return detailsURL; } public ChecksStatus getStatus() { return status; } public ChecksConclusion getConclusion() { return conclusion; } public List<StepChecksAction> getActions() { return actions; } public List<StepChecksAnnotation> getAnnotations() { return annotations; } @Override public StepExecution start(final StepContext stepContext) { return new PublishChecksStepExecution(stepContext, this); } /** * This step's descriptor which defines function name, display name, and context. */ @Extension public static class PublishChecksStepDescriptor extends StepDescriptor { private final StepUtils utils = new StepUtils(); @Override public String getFunctionName() { return "publishChecks"; } @Override public Set<? extends Class<?>> getRequiredContext() { return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(Run.class, TaskListener.class))); } @NonNull @Override public String getDisplayName() { return "Publish customized checks to SCM platforms"; } /** * Fill the dropdown list model with all {@link ChecksStatus}es. * * @return a model with all {@link ChecksStatus}es. */ public ListBoxModel doFillStatusItems() { return utils.asListBoxModel(ChecksStatus.values()); } /** * Fill the dropdown list model with all {@link ChecksConclusion}s. * * @return a model with all {@link ChecksConclusion}s. */ public ListBoxModel doFillConclusionItems() { return utils.asListBoxModel(ChecksConclusion.values()); } } /** * This step's execution to actually publish checks. */ static class PublishChecksStepExecution extends SynchronousNonBlockingStepExecution<Void> { private static final long serialVersionUID = 1L; private final PublishChecksStep step; PublishChecksStepExecution(final StepContext context, final PublishChecksStep step) { super(context); this.step = step; } @Override protected Void run() throws IOException, InterruptedException { ChecksPublisherFactory.fromRun(getContext().get(Run.class), getContext().get(TaskListener.class)) .publish(extractChecksDetails()); return null; } @VisibleForTesting ChecksDetails extractChecksDetails() throws IOException, InterruptedException { // If a checks name has been provided as part of the step, use that. // If not, check to see if there is an active ChecksInfo context (e.g. from withChecks). String checksName = StringUtils.defaultIfEmpty(step.getName(), Optional.ofNullable(getContext().get(ChecksInfo.class)) .map(ChecksInfo::getName) .orElse(StringUtils.EMPTY) ); return new ChecksDetails.ChecksDetailsBuilder() .withName(checksName) .withStatus(step.getStatus()) .withConclusion(step.getConclusion()) .withDetailsURL(step.getDetailsURL()) .withOutput(new ChecksOutput.ChecksOutputBuilder() .withTitle(step.getTitle()) .withSummary(step.getSummary()) .withText(step.getText()) .withAnnotations(step.getAnnotations().stream() .map(StepChecksAnnotation::getAnnotation) .collect(Collectors.toList())) .build()) .withActions(step.getActions().stream() .map(StepChecksAction::getAction) .collect(Collectors.toList())) .build(); } } /** * A simple wrapper for {@link ChecksAnnotation} to allow users add code annotations by {@link PublishChecksStep}. */ public static class StepChecksAnnotation extends AbstractDescribableImpl<StepChecksAnnotation> implements Serializable { private static final long serialVersionUID = 1L; private final String path; private final int startLine; private final int endLine; private final String message; @CheckForNull private Integer startColumn; @CheckForNull private Integer endColumn; @CheckForNull private String title; @CheckForNull private String rawDetails; private ChecksAnnotation.ChecksAnnotationLevel annotationLevel = ChecksAnnotation.ChecksAnnotationLevel.WARNING; /** * Creates an annotation with required parameters. * * @param path * path of the file to annotate * @param startLine * start line of the annotation * @param endLine * end line of the annotation * @param message * annotation message */ @DataBoundConstructor public StepChecksAnnotation(final String path, final int startLine, final int endLine, final String message) { super(); this.path = path; this.startLine = startLine; this.endLine = endLine; this.message = message; } @DataBoundSetter public void setStartColumn(final Integer startColumn) { this.startColumn = startColumn; } @DataBoundSetter public void setEndColumn(final Integer endColumn) { this.endColumn = endColumn; } @DataBoundSetter public void setTitle(final String title) { this.title = title; } @DataBoundSetter public void setRawDetails(final String rawDetails) { this.rawDetails = rawDetails; } @DataBoundSetter public void setAnnotationLevel(final ChecksAnnotation.ChecksAnnotationLevel annotationLevel) { this.annotationLevel = annotationLevel; } public String getPath() { return path; } public int getStartLine() { return startLine; } public int getEndLine() { return endLine; } public String getMessage() { return message; } @CheckForNull public Integer getStartColumn() { return startColumn; } @CheckForNull public Integer getEndColumn() { return endColumn; } @CheckForNull public String getTitle() { return title; } @CheckForNull public String getRawDetails() { return rawDetails; } public ChecksAnnotation.ChecksAnnotationLevel getAnnotationLevel() { return annotationLevel; } /** * Get {@link ChecksAnnotation} built with user-provided parameters in {@link PublishChecksStep}. * * @return the annotation built with provided parameters */ public ChecksAnnotation getAnnotation() { ChecksAnnotation.ChecksAnnotationBuilder builder = new ChecksAnnotation.ChecksAnnotationBuilder() .withPath(path) .withStartLine(startLine) .withEndLine(endLine) .withMessage(message) .withAnnotationLevel(annotationLevel); if (startColumn != null) { builder.withStartColumn(startColumn); } if (endColumn != null) { builder.withEndColumn(endColumn); } if (title != null) { builder.withTitle(title); } if (rawDetails != null) { builder.withRawDetails(rawDetails); } return builder.build(); } /** * Descriptor for {@link StepChecksAnnotation}, required for Pipeline Snippet Generator. */ @Extension public static class StepChecksAnnotationDescriptor extends Descriptor<StepChecksAnnotation> { private final StepUtils utils = new StepUtils(); /** * Fill the dropdown list model with all {@link io.jenkins.plugins.checks.api.ChecksAnnotation.ChecksAnnotationLevel} * values. * * @return a model with all {@link io.jenkins.plugins.checks.api.ChecksAnnotation.ChecksAnnotationLevel} values. */ public ListBoxModel doFillAnnotationLevelItems() { return utils.asListBoxModel( Arrays.stream(ChecksAnnotation.ChecksAnnotationLevel.values()) .filter(v -> v != ChecksAnnotation.ChecksAnnotationLevel.NONE) .toArray(Enum[]::new)); } } } /** * A simple wrapper for {@link ChecksAction} to allow users add checks actions by {@link PublishChecksStep}. */ public static class StepChecksAction extends AbstractDescribableImpl<StepChecksAction> implements Serializable { private static final long serialVersionUID = 1L; private final String label; private final String identifier; private String description = StringUtils.EMPTY; /** * Creates an instance that wraps a newly constructed {@link ChecksAction} with according parameters. * * @param label * label of the action to display in the checks report on SCMs * @param identifier * identifier for the action, useful to identify which action is requested by users */ @DataBoundConstructor public StepChecksAction(final String label, final String identifier) { super(); this.label = label; this.identifier = identifier; } @DataBoundSetter public void setDescription(final String description) { this.description = description; } public String getLabel() { return label; } public String getDescription() { return description; } public String getIdentifier() { return identifier; } public ChecksAction getAction() { return new ChecksAction(label, description, identifier); } /** * Descriptor for {@link StepChecksAction}, required for Pipeline Snippet Generator. */ @Extension public static class StepChecksActionDescriptor extends Descriptor<StepChecksAction> { } } }
32.36887
129
0.619327
f6bba49b6744f3659d1adef53a723c3aa12164a2
805
package com.lio.sc.test; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.commons.dbcp.BasicDataSource; public class DataSourceTest { public static void main(String[] args) throws SQLException{ BasicDataSource source = new BasicDataSource(); source.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver"); source.setUrl("jdbc:derby:SHOPPING_CART;create=true"); ResultSet rs = source.getConnection().createStatement().executeQuery("select product0_.PRODUCTID as PRODUCTID0_, product0_.CATEGORYID as CATEGORYID0_, product0_.PRICE as PRICE0_, product0_.PRODUCTNAME as PRODUCTN4_0_, product0_.SUPPLIERID as SUPPLIERID0_, product0_.UNIT as UNIT0_ from PRODUCTS product0_"); while(rs.next()){ System.out.println(rs.getString("PRODUCTID0_")); } } }
33.541667
309
0.778882
6e88851f3145d50dc7130cc93366ff38ad9da1d7
374
package class_loader.exception; /** * Created by qindongliang on 2018/9/25. */ public class NoClassFoundErrorTest { public static void main(String[] args) { try { double i=Loading.i; }catch (Throwable e){//此处,必须用Throwable,用Exception会直接退出。 System.out.println(e); } //继续使用 Loading.print(); } }
15.583333
63
0.574866
09856cb1a6845272b7c1d0903f3fcd18d7fd8df9
5,630
/** * Copyright Liaison Technologies, Inc. All rights reserved. * <p> * This software is the confidential and proprietary information of * Liaison Technologies, Inc. ("Confidential Information"). You shall * not disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Liaison Technologies. */ package com.liaison.mailbox.service.dropbox; import com.liaison.commons.jpa.DAOUtil; import com.liaison.commons.jpa.GenericDAOBase; import com.liaison.commons.util.StringUtil; import com.liaison.mailbox.MailBoxConstants; import com.liaison.mailbox.rtdm.dao.MailboxRTDMDAO; import com.liaison.mailbox.rtdm.dao.UploadedFileDAO; import com.liaison.mailbox.rtdm.model.UploadedFile; import com.liaison.mailbox.service.dto.GenericSearchFilterDTO; import com.liaison.mailbox.service.util.MailBoxUtil; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * This will fetch the uploaded file details. */ public class UploadedFileDAOBase extends GenericDAOBase<UploadedFile> implements UploadedFileDAO, MailboxRTDMDAO { public UploadedFileDAOBase() { super(PERSISTENCE_UNIT_NAME); } @Override public int getUploadedFilesCountByUserId(String loginId, String fileName) { EntityManager entityManager = null; int count; try { entityManager = DAOUtil.getEntityManager(persistenceUnitName); //by using criteria boolean nameIsEmpty = MailBoxUtil.isEmpty(fileName); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class); Root<UploadedFile> fromUploadedFile = criteriaQuery.from(UploadedFile.class); List<Predicate> predicates = new ArrayList<>(); predicates.add(criteriaBuilder.equal(fromUploadedFile.get("userId"), loginId)); predicates.add(criteriaBuilder.greaterThan(fromUploadedFile.get("expiryDate"), new Date())); if (!nameIsEmpty) { predicates.add(criteriaBuilder.like(criteriaBuilder.lower(fromUploadedFile.get("fileName")), fileName.toLowerCase() + "%")); } TypedQuery<Long> tQueryCount = entityManager.createQuery(criteriaQuery .select(criteriaBuilder.count(fromUploadedFile)) .where(predicates.toArray(new Predicate[]{})) .distinct(true)); count = tQueryCount.getSingleResult().intValue(); } finally { if (entityManager != null) { entityManager.close(); } } return count; } @Override public List<UploadedFile> fetchUploadedFiles(String loginId, GenericSearchFilterDTO searchFilter, Map<String, Integer> pageOffsetDetails) { EntityManager entityManager = null; List<UploadedFile> uploadedFiles; try { entityManager = DAOUtil.getEntityManager(persistenceUnitName); //Named query execution // get Search Filters String fileName = searchFilter.getUploadedFileName(); boolean nameIsEmpty = MailBoxUtil.isEmpty(fileName); //by using criteria CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<UploadedFile> criteriaQuery = criteriaBuilder.createQuery(UploadedFile.class); Root<UploadedFile> fromUploadedFile = criteriaQuery.from(UploadedFile.class); List<Predicate> predicates = new ArrayList<>(); predicates.add(criteriaBuilder.equal(fromUploadedFile.get(USER_ID), loginId)); predicates.add(criteriaBuilder.greaterThan(fromUploadedFile.get(EXPIRY_DATE), new Date())); if (!nameIsEmpty) { predicates.add(criteriaBuilder.like(criteriaBuilder.lower(fromUploadedFile.get(FILE_NAME)), fileName.toLowerCase() + "%")); } TypedQuery<UploadedFile> tQuery = entityManager.createQuery(criteriaQuery .select(fromUploadedFile) .where(predicates.toArray(new Predicate[]{})) .distinct(true) .orderBy(isDescendingSort(searchFilter.getSortDirection()) ? criteriaBuilder.desc(fromUploadedFile.get(searchFilter.getSortField())) : criteriaBuilder.asc(fromUploadedFile.get(searchFilter.getSortField())))); uploadedFiles = tQuery.setFirstResult(pageOffsetDetails.get(MailBoxConstants.PAGING_OFFSET)) .setMaxResults(pageOffsetDetails.get(MailBoxConstants.PAGING_COUNT)) .getResultList(); } finally { if (null != entityManager) { entityManager.close(); } } return uploadedFiles; } /** * Method to check the sort direction. * * @param sortDirection * @return boolean */ private boolean isDescendingSort(String sortDirection) { return !StringUtil.isNullOrEmptyAfterTrim(sortDirection) && sortDirection.toUpperCase().equals(SORT_DIR_DESC); } }
39.647887
140
0.669094
4bc8288ca3f89a9140394b64aed448db42763052
26,293
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * 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.jbpm.workbench.common.client.filters.basic; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import javax.annotation.PostConstruct; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.user.client.DOM; import org.dashbuilder.dataset.DataSetLookup; import org.jboss.errai.common.client.api.IsElement; import org.jboss.errai.common.client.dom.*; import org.jboss.errai.ioc.client.api.ManagedInstance; import org.jboss.errai.ui.shared.api.annotations.DataField; import org.jboss.errai.ui.shared.api.annotations.EventHandler; import org.jboss.errai.ui.shared.api.annotations.ForEvent; import org.jboss.errai.ui.shared.api.annotations.Templated; import org.jbpm.workbench.common.client.dataset.DataSetAwareSelect; import org.jbpm.workbench.common.client.filters.active.ActiveFilterItem; import org.jbpm.workbench.common.client.list.DatePickerRange; import org.jbpm.workbench.common.client.resources.i18n.Constants; import org.jbpm.workbench.common.client.util.DateRange; import org.uberfire.client.views.pfly.widgets.DateRangePicker; import org.uberfire.client.views.pfly.widgets.DateRangePickerOptions; import org.uberfire.client.views.pfly.widgets.JQueryProducer; import org.uberfire.client.views.pfly.widgets.Moment; import org.uberfire.client.views.pfly.widgets.Popover; import org.uberfire.client.views.pfly.widgets.SanitizedNumberInput; import org.uberfire.client.views.pfly.widgets.Select; import static org.jboss.errai.common.client.dom.DOMUtil.*; import static org.jboss.errai.common.client.dom.Window.getDocument; import static org.jbpm.workbench.common.client.list.DatePickerRange.getDatePickerRangeFromLabel; import static org.uberfire.client.views.pfly.widgets.Moment.Builder.moment; @Dependent @Templated(stylesheet = "/org/jbpm/workbench/common/client/resources/css/kie-manage.less") public class BasicFiltersViewImpl implements BasicFiltersView, IsElement { private final Constants constants = Constants.INSTANCE; @Inject @DataField("content") Div content; @Inject @DataField("filter-list") Div filterList; @Inject @DataField("refine-section") Div refineSection; @Inject @DataField("refine") @Named("h5") Heading refine; @Inject @DataField("refine-options") Select refineSelect; @Inject @DataField("filters-input") Div filtersInput; @Inject @DataField("filters-input-help") Button filtersInputHelp; @Inject @DataField("refine-apply") Button refineApply; @Inject @DataField("form") Form form; @Inject private JQueryProducer.JQuery<Popover> jQueryPopover; @Inject private ManagedInstance<Select> selectProvider; @Inject private ManagedInstance<DataSetAwareSelect> dataSetSelectProvider; @Inject private ManagedInstance<DateRangePicker> dateRangePickerProvider; @Inject private ManagedInstance<SanitizedNumberInput> sanitizedNumberInput; private Map<String, List<Input>> selectInputs = new HashMap<>(); @PostConstruct public void init() { refine.setTextContent(constants.FilterBy()); filtersInputHelp.setAttribute("data-content", getInputStringHelpHtml()); jQueryPopover.wrap(filtersInputHelp).popover(); refineSelect.getElement().addEventListener("change", e -> setInputCurrentFilter(refineSelect.getValue()), false); refineApply.setTextContent(constants.Apply()); } private String getInputStringHelpHtml() { return "<p>" + constants.AllowedWildcardsForStrings() + "</p>\n" + " <ul>\n" + " <li><code>_</code> - " + constants.ASubstituteForASingleCharacter() + "</li>\n" + " <li><code>%</code> - " + constants.ASubstituteForZeroOrMoreCharacters() + "</li>\n" + " </ul>\n"; } @Override public HTMLElement getElement() { return content; } @Override public void addTextFilter(final String label, final String placeholder, final Consumer<ActiveFilterItem<String>> callback) { addTextFilter(label, placeholder, false, callback); } @Override public void addTextFilter(String label, String placeholder, boolean disableFiltersInputHelp, Consumer<ActiveFilterItem<String>> callback) { filtersInputHelp.setDisabled(disableFiltersInputHelp); if (disableFiltersInputHelp) { addCSSClass(filtersInputHelp, "hidden"); } createFilterOption(label); createTextInput(label, placeholder, refineSelect.getOptions().getLength() > 1, input -> input.setType("text"), v -> v, callback); } protected void hideFiltersInputHelp() { filtersInputHelp.setDisabled(true); addCSSClass(filtersInputHelp, "hidden"); } protected void showFiltersInputHelp() { filtersInputHelp.setDisabled(false); removeCSSClass(filtersInputHelp, "hidden"); } @Override public void addNumericFilter(final String label, final String placeholder, final Consumer<ActiveFilterItem<Integer>> callback) { createFilterOption(label); createNumberInput(label, placeholder, refineSelect.getOptions().getLength() > 1, input -> { input.setType("number"); input.setAttribute("min", "0"); }, v -> Integer.valueOf(v), callback); if (refineSelect.getOptions().getLength() == 1) { hideFiltersInputHelp(); } } @Override public void addDataSetSelectFilter(final String label, final DataSetLookup lookup, final String textColumnId, final String valueColumnId, final Consumer<ActiveFilterItem<String>> callback) { final DataSetAwareSelect select = dataSetSelectProvider.get(); select.setDataSetLookup(lookup); select.setTextColumnId(textColumnId); select.setValueColumnId(valueColumnId); setupSelect(label, select.getSelect(), callback); } @Override public void addDateRangeFilter(final String label, final String placeholder, final Boolean useMaxDate, final Consumer<ActiveFilterItem<DateRange>> callback) { final DateRangePicker dateRangePicker = dateRangePickerProvider.get(); dateRangePicker.getElement().setReadOnly(true); dateRangePicker.getElement().setAttribute("placeholder", placeholder); addCSSClass(dateRangePicker.getElement(), "form-control"); addCSSClass(dateRangePicker.getElement(), "bootstrap-datepicker"); final DateRangePickerOptions options = getDateRangePickerOptions(useMaxDate); dateRangePicker.setup(options, null); dateRangePicker.addApplyListener((e, p) -> { final Optional<DatePickerRange> datePickerRange = getDatePickerRangeFromLabel(p.getChosenLabel()); onDateRangeValueChange(label, datePickerRange.isPresent() ? datePickerRange.get().getLabel() : constants.Custom(), datePickerRange.isPresent() ? datePickerRange.get().getStartDate() : p.getStartDate(), datePickerRange.isPresent() ? datePickerRange.get().getEndDate() : p.getEndDate(), callback); }); appendHorizontalRule(); appendSectionTitle(label); Div div = (Div) getDocument().createElement("div"); addCSSClass(div, "input-group"); addCSSClass(div, "date"); Span spanGroup = (Span) getDocument().createElement("span"); addCSSClass(spanGroup, "input-group-addon"); Span spanIcon = (Span) getDocument().createElement("span"); addCSSClass(spanIcon, "fa"); addCSSClass(spanIcon, "fa-calendar"); spanGroup.appendChild(spanIcon); div.appendChild(dateRangePicker.getElement()); div.appendChild(spanGroup); appendFormGroup(div); } protected DateRangePickerOptions getDateRangePickerOptions(final Boolean useMaxDate) { final DateRangePickerOptions options = DateRangePickerOptions.create(); options.setAutoUpdateInput(false); options.setAutoApply(true); options.setTimePicker(true); options.setDrops("up"); options.setTimePickerIncrement(30); if (useMaxDate) { options.setMaxDate(moment().endOf("day")); } for (DatePickerRange range : DatePickerRange.values()) { options.addRange(range.getLabel(), range.getStartDate(), range.getEndDate().endOf("day")); } return options; } protected void onDateRangeValueChange(final String label, final String selectedLabel, final Moment fromDate, final Moment toDate, final Consumer<ActiveFilterItem<DateRange>> callback) { final DateRange dateRange = new DateRange(fromDate.milliseconds(0).asDate(), toDate.milliseconds(0).asDate()); final String hint = constants.From() + ": " + fromDate.format("lll") + "<br>" + constants.To() + ": " + toDate.format("lll"); addActiveFilter(label, selectedLabel, hint, dateRange, callback); } @Override public void addSelectFilter(final String label, final Map<String, String> options, final Consumer<ActiveFilterItem<String>> callback) { final Select select = selectProvider.get(); options.forEach((k, v) -> select.addOption(v, k)); setupSelect(label, select, callback); } @Override public void clearAllSelectFilter() { selectInputs.values().forEach(values -> { values.forEach(i -> { if (i.getChecked()) { i.setChecked(false); } }); }); } @Override public void checkSelectFilter(final String label, final String value) { selectInputs.computeIfPresent(label, (key, values) -> { values.forEach(i -> { if (i.getValue().equals(value) && i.getChecked() == false) { i.setChecked(true); } }); return values; }); } @Override public void clearSelectFilter(final String label) { selectInputs.computeIfPresent(label, (key, values) -> { values.forEach(i -> { if (i.getChecked()) { i.setChecked(false); } }); return values; }); } @Override public void addMultiSelectFilter(final String label, final Map<String, String> options, final Consumer<ActiveFilterItem<List<String>>> callback) { final HTMLElement hr = getDocument().createElement("hr"); addCSSClass(hr, "kie-dock__divider"); addCSSClass(hr, "kie-dock__divider_collapse"); form.insertBefore(hr, form.getFirstChild()); final Div group = (Div) getDocument().createElement("div"); addCSSClass(group, "panel-group"); addCSSClass(group, "kie-dock__panel-group"); form.insertBefore(group, form.getFirstChild()); final Div heading = (Div) getDocument().createElement("div"); addCSSClass(heading, "panel-heading"); addCSSClass(heading, "kie-dock__panel-heading"); group.appendChild(heading); final Div title = (Div) getDocument().createElement("div"); addCSSClass(title, "panel-title"); addCSSClass(title, "kie-dock__heading--section"); heading.appendChild(title); final Anchor anchorTitle = (Anchor) getDocument().createElement("a"); anchorTitle.setAttribute("data-toggle", "collapse"); final String divId = DOM.createUniqueId(); anchorTitle.setAttribute("data-target", "#" + divId); anchorTitle.setTextContent(label); title.appendChild(anchorTitle); final Div content = (Div) getDocument().createElement("div"); addCSSClass(content, "panel-collapse"); addCSSClass(content, "collapse"); addCSSClass(content, "in"); content.setId(divId); group.appendChild(content); final Div divPanel = (Div) getDocument().createElement("div"); addCSSClass(divPanel, "panel-body"); addCSSClass(divPanel, "kie-dock__panel-body"); content.appendChild(divPanel); final Div div = (Div) getDocument().createElement("div"); addCSSClass(div, "form-group"); for (Map.Entry<String, String> entry : options.entrySet()) { final Label labelElement = (Label) getDocument().createElement("label"); final Input input = (Input) getDocument().createElement("input"); input.setType("checkbox"); input.setValue(entry.getKey()); input.setAttribute("data-label", entry.getValue()); input.addEventListener("change", e -> { final List<String> values = new ArrayList<>(); final List<String> labels = new ArrayList<>(); selectInputs.get(label).stream().filter(i -> i.getChecked()).forEach(i -> { values.add(i.getValue()); labels.add(i.getAttribute("data-label")); }); addActiveFilter(label, String.join(", ", labels), null, values, callback); }, false); selectInputs.computeIfAbsent(label, key -> new ArrayList<Input>()); selectInputs.get(label).add(input); labelElement.appendChild(input); labelElement.appendChild(getDocument().createTextNode(entry.getValue())); final Div checkBoxDiv = (Div) getDocument().createElement("div"); addCSSClass(checkBoxDiv, "checkbox"); checkBoxDiv.appendChild(labelElement); div.appendChild(checkBoxDiv); } divPanel.appendChild(div); } @Override public void hideFilterBySection() { addCSSClass(refineSection, "hidden"); } private void setupSelect(final String label, final Select select, final Consumer<ActiveFilterItem<String>> callback) { appendHorizontalRule(); appendSectionTitle(label); select.setTitle(constants.Select()); select.setWidth("100%"); addCSSClass(select.getElement(), "selectpicker"); addCSSClass(select.getElement(), "form-control"); select.getElement().addEventListener("change", event -> { if (select.getValue().isEmpty() == false) { final OptionsCollection options = select.getOptions(); for (int i = 0; i < options.getLength(); i++) { final Option item = (Option) options.item(i); if (item.getSelected()) { addActiveFilter(label, item.getText(), null, select.getValue(), callback); select.setValue(""); break; } } } }, false); appendFormGroup(select.getElement()); select.refresh(); } private void appendFormGroup(final HTMLElement element) { Div div = (Div) getDocument().createElement("div"); addCSSClass(div, "form-group"); div.appendChild(element); filterList.appendChild(div); } private void appendHorizontalRule() { final HTMLElement hr = getDocument().createElement("hr"); addCSSClass(hr, "kie-dock__divider"); filterList.appendChild(hr); } private void appendSectionTitle(final String title) { final Heading heading = (Heading) getDocument().createElement("h5"); heading.setTextContent(title); addCSSClass(heading, "kie-dock__heading--section"); filterList.appendChild(heading); } private <T extends Object> void createNumberInput(final String label, final String placeholder, final Boolean hidden, final Consumer<Input> customizeCallback, final Function<String, T> valueMapper, final Consumer<ActiveFilterItem<T>> callback) { final SanitizedNumberInput numberInput = sanitizedNumberInput.get(); numberInput.init(); Input input = numberInput.getElement(); createInput(label, input, placeholder, hidden, customizeCallback, valueMapper, callback); } private <T extends Object> void createInput(final String label, final Input input, final String placeholder, final Boolean hidden, final Consumer<Input> customizeCallback, final Function<String, T> valueMapper, final Consumer<ActiveFilterItem<T>> callback) { customizeCallback.accept(input); input.setAttribute("placeholder", placeholder); input.setAttribute("data-filter", label); addCSSClass(input, "form-control"); addCSSClass(input, "filter-control"); if (hidden) { addCSSClass(input, "hidden"); } input.setOnkeypress((KeyboardEvent e) -> { if ((e == null || e.getKeyCode() == KeyCodes.KEY_ENTER) && input.getValue().isEmpty() == false) { addActiveFilter(label, input.getValue(), null, valueMapper.apply(input.getValue()), callback); input.setValue(""); } }); filtersInput.insertBefore(input, filtersInput.getFirstChild()); } private <T extends Object> void createTextInput(final String label, final String placeholder, final Boolean hidden, final Consumer<Input> customizeCallback, final Function<String, T> valueMapper, final Consumer<ActiveFilterItem<T>> callback) { final Input input = (Input) getDocument().createElement("input"); createInput(label, input, placeholder, hidden, customizeCallback, valueMapper, callback); } private void createFilterOption(final String label) { refineSelect.addOption(label); refineSelect.refresh(); } private void setInputCurrentFilter(final String label) { for (Element child : elementIterable(filtersInput.getChildNodes())) { if (child.getTagName().equals("INPUT")) { if (label.equals(child.getAttribute("data-filter"))) { removeCSSClass((HTMLElement) child, "hidden"); if (((Input) child).getType().equals("number")) { hideFiltersInputHelp(); } else { showFiltersInputHelp(); } } else { addCSSClass((HTMLElement) child, "hidden"); } } } } @EventHandler("refine-apply") public void onApplyClick(@ForEvent("click") Event e) { for (Element child : elementIterable(filtersInput.getChildNodes())) { if (child.getTagName().equals("INPUT")) { Input input = (Input) child; if (input.getClassList().contains("hidden") == false) { input.getOnkeypress().call(null); break; } } } } protected <T extends Object> void addActiveFilter(final String labelKey, final String labelValue, final String hint, final T value, final Consumer<ActiveFilterItem<T>> callback) { if (callback != null) { callback.accept(new ActiveFilterItem(labelKey, labelKey + ": " + labelValue, hint, value, null)); } } protected Map<String, List<Input>> getSelectInputs() { return selectInputs; } }
40.019787
143
0.499791
3e600b25dc960335b28cbfd050f73ec27af61e6d
1,629
package com.sap.cloud.security.xsuaa.token; import com.sap.cloud.security.xsuaa.XsuaaServiceConfiguration; import com.sap.cloud.security.xsuaa.XsuaaServiceConfigurationDefault; import com.sap.cloud.security.xsuaa.extractor.IasXsuaaExchangeBroker; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.junit.Before; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import java.io.IOException; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @ContextConfiguration(classes = XsuaaServiceConfigurationDefault.class) public class IasXsuaaExchangeBrokerTest { @Autowired XsuaaServiceConfiguration serviceConfiguration; private static String encodedIasToken; private static String encodedXsuaaToken; private static IasXsuaaExchangeBroker tokenWrapper; @Before public void setup() throws IOException { encodedIasToken = IOUtils.resourceToString("/token_cc.txt", StandardCharsets.UTF_8); encodedXsuaaToken = IOUtils.resourceToString("/token_xsuaa.txt", StandardCharsets.UTF_8); tokenWrapper = mock(IasXsuaaExchangeBroker.class); } @Test public void isXsuaaTokenFalseTest() { when(tokenWrapper.isXsuaaToken(encodedIasToken)).thenCallRealMethod(); assertFalse(tokenWrapper.isXsuaaToken(encodedIasToken)); } @Test public void isXsuaaTokenTrueTest() { when(tokenWrapper.isXsuaaToken(encodedXsuaaToken)).thenCallRealMethod(); assertTrue(tokenWrapper.isXsuaaToken(encodedXsuaaToken)); } }
33.9375
91
0.828729
86c52707a1f52e51b0734b1a65994e3efa3006a2
3,483
package dev.anhcraft.craftkit.cb_1_17_r1.services; import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; import dev.anhcraft.craftkit.cb_1_17_r1.CBModule; import dev.anhcraft.craftkit.cb_common.internal.backend.CBPlayerBackend; import dev.anhcraft.craftkit.common.Skin; import dev.anhcraft.jvmkit.utils.ReflectionUtil; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.minecraft.network.PacketDataSerializer; import net.minecraft.network.protocol.game.*; import net.minecraft.resources.MinecraftKey; import net.minecraft.server.level.EntityPlayer; import net.minecraft.world.entity.player.EntityHuman; import org.bukkit.craftbukkit.v1_17_R1.CraftWorld; import org.bukkit.craftbukkit.v1_17_R1.entity.CraftPlayer; import org.bukkit.entity.Player; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class PlayerBackend extends CBModule implements CBPlayerBackend { @Override public Object toNmsEntityPlayer(Player player) { return ((CraftPlayer) player).getHandle(); } @Override public List<Object> toNmsEntityPlayers(List<Player> players) { return players.stream().map(player -> ((CraftPlayer) player).getHandle()).collect(Collectors.toList()); } @Override public int getPing(Player player) { return player.getPing(); } @Override public GameProfile getProfile(Player player) { return ((CraftPlayer) player).getHandle().getProfile(); } @Override public void setProfile(Player player, GameProfile profile) { ReflectionUtil.setDeclaredField(EntityHuman.class, ((CraftPlayer) player).getHandle(), "cs", profile); } @Override public void changeSkin(Player player, Skin skin, List<Player> viewers) { CraftPlayer cp = (CraftPlayer) player; EntityPlayer ent = cp.getHandle(); List<EntityPlayer> vws = toEntityPlayers(viewers); sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.e, ent), vws); sendPacket(new PacketPlayOutEntityDestroy(ent.getId()), vws); ent.getProfile().getProperties().removeAll("textures"); ent.getProfile().getProperties().put("textures", new Property("textures", skin.getValue(), skin.getSignature())); sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.a, ent), vws); sendPacket(new PacketPlayOutNamedEntitySpawn(ent), vws); craftServer.getHandle().moveToWorld(ent, ((CraftWorld) player.getWorld()).getHandle(), true, player.getLocation(), true); } @Override public void setCamera(int entityId, Player viewer) { PacketPlayOutCamera packet = new PacketPlayOutCamera(Objects.requireNonNull(((CraftWorld) viewer.getWorld()).getHandle().getEntity(entityId))); sendPacket(packet, toEntityPlayer(viewer)); } @Override public void openBook(Player player, int slot) { ByteBuf buf = Unpooled.buffer(256); buf.setByte(0, slot); buf.writerIndex(1); sendPacket(new PacketPlayOutCustomPayload(new MinecraftKey("minecraft:book_open"), new PacketDataSerializer(buf)), toEntityPlayer(player)); } @Override public void fakeExp(float expBar, int level, int totalExp, Player player) { expBar = Math.min(1, Math.max(0, level)); sendPacket(new PacketPlayOutExperience(expBar, level, totalExp), toEntityPlayer(player)); } }
41.464286
151
0.735286
c27b34a310dd54999a8bdc7ce614897fef0d8002
1,095
package basic.other; import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @describe 测试特殊运算符 */ public class TestString { public static void main(String[] args) { } @Test public void test1() { Pattern p = Pattern.compile("\\(.*\\)"); Matcher m = p.matcher("1.2.0(23)"); if (m.find()) { System.out.println(m.start() + " " + m.end()); } } @Test public void test2() { Pattern p = Pattern.compile("dispatch/afterhandle/(.*)/"); Matcher m = p.matcher("http://200.200.6.22:8887/lxyisa/dispatch/afterhandle/5d5bcedd/main?name=val"); if (m.find()) { String group = m.group(); System.out.println(group); System.out.println(m.start() + " " + m.end()); } } @Test public void test3() { String url = "http://200.200.6.22:8887/lxyisa/dispatch/afterhandle/5d5bcedd/main?name=val"; int i = url.indexOf("dispatch/afterhandle/"); System.out.println(i); int beginIndex = i + "dispatch/afterhandle/".length(); String substring = url.substring(beginIndex, beginIndex + 8); System.out.println(substring); } }
20.277778
103
0.645662
d554ad32a89d26b899279f5a5075d84182089bb7
1,020
package net.violet.platform.dataobjects; import java.util.HashMap; import java.util.List; import java.util.Map; import net.violet.platform.datamodel.Lang; public class HumeurDataFactory { private static final String[] FREQS_LABELS = new String[] { "srv_humeur/freq_rare", "srv_humeur/freq_normal", "srv_humeur/freq_often", "srv_humeur/freq_very_often" }; private static final String[] FREQS_IDS = new String[] { "1", "3", "6", "10" }; private static final Map<Lang, List<FrequenceData>> listFrequence = new HashMap<Lang, List<FrequenceData>>(); /** * Generates a list of frequenceData object from a LangImpl object * * @param inFreqs * @return */ public static List<FrequenceData> generateListFrequence(Lang inLang) { if (!HumeurDataFactory.listFrequence.containsKey(inLang)) { HumeurDataFactory.listFrequence.put(inLang, FrequenceData.generateListFrequence(HumeurDataFactory.FREQS_LABELS, HumeurDataFactory.FREQS_IDS, inLang)); } return HumeurDataFactory.listFrequence.get(inLang); } }
34
167
0.762745
97183b69d39377e7e9998271a66b514a04cb9698
1,365
package xyy.java.note.mt; /** * @author xyy * @version 1.0 2017/6/14. * @since 1.0 */ public class VmDemo { public static void main(String[] args) { ThreadGroup group = Thread.currentThread().getThreadGroup(); if(group != null) { Thread[] threads = new Thread[(int)(group.activeCount() * 1.2)]; int count = group.enumerate(threads, true); System.out.println(count); for(int i = 0; i < count; i++) { System.out.println(threads[i].getName()); } } while (true){ try { Thread.sleep(1000*60*10); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 通过线程组获得线程 * * @param threadId * @return */ public static Thread findThread(long threadId) { ThreadGroup group = Thread.currentThread().getThreadGroup(); while(group != null) { Thread[] threads = new Thread[(int)(group.activeCount() * 1.2)]; int count = group.enumerate(threads, true); for(int i = 0; i < count; i++) { if(threadId == threads[i].getId()) { return threads[i]; } } group = group.getParent(); } return null; } }
26.25
76
0.485714
9257f4e3d6d7b5427b47a2bb4911aec24c145fd3
105
package com.latte.controller.domain.history.service; public enum SortOrder { ASC, DESC, ; }
13.125
52
0.67619
e6a8907c35e18477410d63d4512f72937d3ce477
21,582
/* * Copyright 2003-2020 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.mps.nodeEditor.cells; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.ui.ColorUtil; import com.intellij.ui.DarculaColors; import com.intellij.ui.JBColor; import jetbrains.mps.editor.runtime.style.Measure; import jetbrains.mps.editor.runtime.style.Padding; import jetbrains.mps.editor.runtime.style.StyleAttributes; import jetbrains.mps.editor.runtime.style.StyleImpl; import jetbrains.mps.nodeEditor.EditorComponentSettingsImpl; import jetbrains.mps.nodeEditor.EditorSettings; import jetbrains.mps.openapi.editor.EditorComponentSettings; import jetbrains.mps.openapi.editor.cells.EditorFontMetrics; import jetbrains.mps.openapi.editor.style.Style; import jetbrains.mps.openapi.editor.style.StyleAttribute; import jetbrains.mps.openapi.editor.style.StyleRegistry; import org.jetbrains.annotations.NotNull; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.font.TextAttribute; import java.text.AttributedCharacterIterator.Attribute; import java.util.HashMap; import java.util.Map; import java.util.Set; public class TextLine { // COLORS: Remove hardcoded color private static final Color SELECTED_OR_BACKGROUND_ERROR_COLOR = new JBColor(new Color(255, 220, 220, 128), ColorUtil.mix(StyleRegistry.getInstance().getEditorBackground(), DarculaColors.RED, 0.1)); private static final Color ERROR_FOREGROUND_COLOR = new JBColor(new Color(168, 30, 30, 255), DarculaColors.RED); private String myText; private int myDescent = 0; private Font myFont = EditorSettings.getInstance().getDefaultEditorFont(); private final EditorComponentSettings myEditorComponentSettings; private EditorFontMetrics myFontMetrics; private int myCaretPosition = 0; private int myCaretX = -1; private int mySelectionStartX = -1; private int mySelectionEndX = -1; private int myTextEndX = -1; private int myMinWidth = -1; private int myStartTextSelectionPosition = 0; private int myEndTextSelectionPosition = 0; private int myWidth = 0; private int myHeight = 0; private int myTextHeight = 0; private boolean myCaretEnabled = true; private int myMinimalLength = 0; private final double myLineSpacing = EditorSettings.getInstance().getLineSpacing(); private Color mySelectedTextColor = EditorSettings.getInstance().getSelectionForegroundColor(); private final Color myTextSelectedTextColor = EditorSettings.getInstance().getSelectionForegroundColor(); private final Color myTextSelectedBackgroundColor = EditorSettings.getInstance().getSelectionBackgroundColor(); private boolean myShowsErrorColor = false; private boolean myNull; private Style myStyle; private int myPaddingLeft; private int myPaddingRight; private int myPaddingTop; private int myPaddingBottom; private boolean myControlOvered; private boolean myStrikeOut; private boolean myUnderlined; private Color myTextColor; private Color myNullTextColor; private Color myTextBackground; private Color myNullTextBackground; private Color mySelectedTextBackground; private Color myNulLSelectedTextBackground; private boolean myShowCaret; private boolean mySelected; private boolean myInitialized; private int myFontCorrectionRightGap; private int myFontCorrectionTextShift; public TextLine(String text, EditorComponentSettings editorComponentSettings) { this(text, new StyleImpl(), false, editorComponentSettings); } /** * Used by mps extensions. * @deprecated use {@link #TextLine(String, Style, boolean, EditorComponentSettings)} instead */ @Deprecated public TextLine(String text, @NotNull Style style, boolean isNull) { this(text, style, isNull, EditorComponentSettingsImpl.DEFAULT_SETTINGS); } public TextLine(String text, @NotNull Style style, boolean isNull, EditorComponentSettings editorComponentSettings) { setText(text); myNull = isNull; myStyle = style; showTextColor(); myEditorComponentSettings = editorComponentSettings; } public String getText() { return myText; } public void setText(String text) { if (text == null) { text = ""; } if (text.equals(myText)) { return; } doSetText(text); doSetCaretPosition(Math.min(myText.length(), getCaretPosition())); setStartTextSelectionPosition(getCaretPosition()); setEndTextSelectionPosition(getCaretPosition()); } private void doSetText(String text) { myText = text; myCaretX = -1; mySelectionStartX = -1; mySelectionEndX = -1; myTextEndX = -1; } public String getTextBeforeCaret() { return myText.substring(0, getCaretPosition()); } public String getTextAfterCaret() { return myText.substring(getCaretPosition(), myText.length()); } public int getWidth() { return myWidth; } public int getHeight() { return myHeight; } public int getStartTextSelectionPosition() { return myStartTextSelectionPosition; } public int getEndTextSelectionPosition() { return myEndTextSelectionPosition; } /** * @param length Minimal size of the text edit field in chars. */ public void setMinimalLength(int length) { myMinimalLength = length; myMinWidth = -1; } private void updateStyle(Set<StyleAttribute> attributes) { myStrikeOut = myStyle.get(StyleAttributes.STRIKE_OUT); myUnderlined = myStyle.get(StyleAttributes.UNDERLINED); if (attributes == null || attributes.contains(StyleAttributes.FONT_SIZE) || attributes.contains(StyleAttributes.FONT_STYLE) || attributes.contains(StyleAttributes.FONT_FAMILY)) { //this is the most expensive calculation EditorSettings settings = EditorSettings.getInstance(); Integer styleFontSize = myStyle.get(StyleAttributes.FONT_SIZE); String styleFontFamily = myStyle.get(StyleAttributes.FONT_FAMILY); if (styleFontFamily != null && !FontRegistry.getInstance().getAvailableFontFamilyNames().contains(styleFontFamily)) { FontRegistry.getInstance().reportUnknownFontFamily(styleFontFamily); styleFontFamily = null; } Integer style = myStyle.get(StyleAttributes.FONT_STYLE); String family = styleFontFamily != null ? styleFontFamily : settings.getFontFamily(); int fontSize = styleFontSize != null ? styleFontSize : settings.getFontSize(); fontSize = myEditorComponentSettings.getFontSizeScaled(fontSize); final Font font = FontRegistry.getInstance().getFont(family, style, fontSize); Map<Attribute, Object> fontAttributes = new HashMap<>(); if (ApplicationManager.getApplication() != null && EditorColorsManager.getInstance().getGlobalScheme().getFontPreferences().useLigatures()) { fontAttributes.put(TextAttribute.LIGATURES, TextAttribute.LIGATURES_ON); } if (myStrikeOut) { fontAttributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); } myFont = fontAttributes.isEmpty() ? font : font.deriveFont(fontAttributes); myFontMetrics = myEditorComponentSettings.getFontMetrics(family, style, fontSize); myFontCorrectionRightGap = FontRegistry.getInstance().isFakeItalic(family, style) ? 1 : 0; myFontCorrectionTextShift = (style & Font.ITALIC) > 0 ? -1 : 0; } myPaddingLeft = getHorizontalInternalInset(myStyle.get(StyleAttributes.PADDING_LEFT)); myPaddingRight = getHorizontalInternalInset(myStyle.get(StyleAttributes.PADDING_RIGHT)); myPaddingTop = getVerticalInternalInset(myStyle.get(StyleAttributes.PADDING_TOP)); myPaddingBottom = getVerticalInternalInset(myStyle.get(StyleAttributes.PADDING_BOTTOM)); myControlOvered = myStyle.get(StyleAttributes.CONTROL_OVERED_REFERENCE); myTextColor = myStyle.get(StyleAttributes.TEXT_COLOR); myNullTextColor = myStyle.get(StyleAttributes.NULL_TEXT_COLOR); myTextBackground = myStyle.get(StyleAttributes.TEXT_BACKGROUND_COLOR); myNullTextBackground = myStyle.get(StyleAttributes.NULL_TEXT_BACKGROUND_COLOR); mySelectedTextBackground = myStyle.get(StyleAttributes.SELECTED_TEXT_BACKGROUND_COLOR); myNulLSelectedTextBackground = myStyle.get(StyleAttributes.NULL_SELECTED_TEXT_BACKGROUND_COLOR); } private void init() { if (myInitialized) { return; } myInitialized = true; updateStyle(null); myStyle.addListener(e -> { Set<StyleAttribute> changedAttributes = e.getChangedAttributes(); updateStyle(changedAttributes); }); } public void relayout() { EditorFontMetrics metrics = getEditorFontMetrics(); myHeight = (int) (metrics.getHeight() * myLineSpacing + getPaddingTop() + getPaddingBottom()); myTextHeight = (int) (metrics.getHeight() * myLineSpacing); int minWidth = calculateMinWidth(); int width = metrics.getWidth(myText) + myFontCorrectionRightGap + getPaddingLeft() + getPaddingRight(); myWidth = Math.max(minWidth, width); myDescent = metrics.getDescent(); } int getEffectiveWidth() { int minWidth = calculateMinWidth(); int effectiveWidth = myWidth - getPaddingLeft() - getPaddingRight(); return Math.max(minWidth, effectiveWidth); } private int calculateMinWidth() { if (myMinWidth == -1) { myMinWidth = Math.max(myMinimalLength * charWidth(), myStyle.get(StyleAttributes.SELECTABLE) ? 2 : 0); } return myMinWidth; } private int getHorizontalInternalInset(Padding p) { double value = p.getValue(); Measure type = p.getType(); if (type == null) { type = Measure.SPACES; } if (type == Measure.SPACES) { return (int) (charWidth() * value); } if (type == Measure.PIXELS) { return (int) value; } return 0; } private int getVerticalInternalInset(Padding p) { double value = p.getValue(); Measure type = p.getType(); if (type == null) { type = Measure.SPACES; } if (type == Measure.SPACES) { return (int) (charHeight() * value); } if (type == Measure.PIXELS) { return (int) value; } return 0; } public int getPaddingLeft() { init(); return myPaddingLeft; } public int getPaddingRight() { init(); return myPaddingRight; } public int getPaddingTop() { init(); return myPaddingTop; } public int getPaddingBottom() { init(); return myPaddingBottom; } public int charWidth() { return getEditorFontMetrics().getWidth("w"); } public int charHeight() { return getEditorFontMetrics().getHeight(); } public boolean isCaretEnabled() { return myCaretEnabled; } public void setCaretEnabled(boolean caretEnabled) { myCaretEnabled = caretEnabled; } public void home() { setCaretPosition(0); } public void end() { setCaretPosition(getText().length()); } public void showErrorColor() { myShowsErrorColor = true; } public void showTextColor() { myShowsErrorColor = false; } public Color getBackgroundColor() { if (myShowsErrorColor) { return SELECTED_OR_BACKGROUND_ERROR_COLOR; } return null; } public Color getTextColor() { init(); if (myControlOvered) { return EditorSettings.getInstance().getHyperlinkColor(); } if (!myNull && myTextColor != null) { return myTextColor; } else { return myNullTextColor; } } public Color getEffectiveTextColor() { if (myShowsErrorColor) { return ERROR_FOREGROUND_COLOR; } else { return getTextColor(); } } public Color getEffectiveSelectedTextColor() { if (myShowsErrorColor) { return SELECTED_OR_BACKGROUND_ERROR_COLOR; } else { return mySelectedTextColor != null ? mySelectedTextColor : getTextColor(); } } public Color getTextBackgroundColor() { init(); if (myShowsErrorColor) { return SELECTED_OR_BACKGROUND_ERROR_COLOR; } else { if (!myNull) { return myTextBackground; } else { return myNullTextBackground; } } } public void setSelectedTextColor(Color selectedTextColor) { mySelectedTextColor = selectedTextColor; } public Color getSelectedTextBackgroundColor() { init(); if (!myNull) { return mySelectedTextBackground; } else { return myNulLSelectedTextBackground; } } public Font getFont() { init(); return myFont; } public boolean isSelected() { return mySelected; } public void setSelected(boolean isSelected) { mySelected = isSelected; } public boolean isShowCaret() { return myShowCaret; } public void setShowCaret(boolean showCaret) { myShowCaret = showCaret; } public void paint(Graphics g, int shiftX, int shiftY) { paint(g, shiftX, shiftY, null); } public void paint(Graphics g, int shiftX, int shiftY, Color forcedTextColor) { Color backgroundColor; Color textColor; Color textBackgroundColor; backgroundColor = getBackgroundColor(); if (forcedTextColor != null) { textColor = forcedTextColor; textBackgroundColor = null; } else { if (mySelected) { textColor = getEffectiveSelectedTextColor(); textBackgroundColor = getSelectedTextBackgroundColor(); } else { textColor = getEffectiveTextColor(); textBackgroundColor = getTextBackgroundColor(); } } if (backgroundColor != null && !g.getColor().equals(backgroundColor) && !mySelected) { g.setColor(backgroundColor); g.fillRect(shiftX + getPaddingLeft(), shiftY + getPaddingTop(), getEffectiveWidth(), myTextHeight); } if (textBackgroundColor != null) { g.setColor(textBackgroundColor); g.fillRect(shiftX + getPaddingLeft(), shiftY + getPaddingTop(), getEffectiveWidth(), myTextHeight); } g.setFont(getFont()); if (!g.getColor().equals(textColor)) { g.setColor(textColor); } int selectionStartX = shiftX + getPaddingLeft() + getSelectionStartX(); int selectionEndX = shiftX + getPaddingLeft() + getSelectionEndX(); int endLineX = shiftX + getPaddingLeft() + getTextEndX(); int baselineY = shiftY + myHeight - myDescent - getPaddingBottom(); int centerLineY = shiftY + (myHeight - getPaddingBottom() + getPaddingTop()) / 2; if (getStartTextSelectionPosition() > 0) { g.drawString(myText.substring(0, getStartTextSelectionPosition()), shiftX + getPaddingLeft() + myFontCorrectionTextShift, baselineY); if (isUnderlined()) { g.drawLine(shiftX + getPaddingLeft(), baselineY + 1, selectionStartX, baselineY + 1); } } if (getEndTextSelectionPosition() <= myText.length()) { g.drawString(myText.substring(getEndTextSelectionPosition()), selectionEndX + myFontCorrectionTextShift, baselineY); if (isUnderlined()) { g.drawLine(selectionEndX, baselineY + 1, endLineX, baselineY + 1); } } if (getStartTextSelectionPosition() < getEndTextSelectionPosition()) { //drawing textual selection String selectedText = getTextuallySelectedText(); g.setColor(myTextSelectedBackgroundColor); // Filling smaller rectangle to not cover frames created by other messages if (selectionEndX - selectionStartX - 2 + myFontCorrectionRightGap > 0) { g.fillRect(selectionStartX + 1, shiftY + getPaddingTop() + 1, selectionEndX - selectionStartX - 2 + myFontCorrectionRightGap, myTextHeight - 2); } g.setColor(myTextSelectedTextColor != null ? myTextSelectedTextColor : getTextColor()); g.drawString(selectedText, selectionStartX + myFontCorrectionTextShift, baselineY); if (isUnderlined()) { g.drawLine(selectionStartX, baselineY + 1, selectionEndX, baselineY + 1); } g.setColor(textColor); } if (myShowCaret) { drawCaret(g, shiftX, shiftY); } } private void drawCaret(Graphics g, int shiftX, int shiftY) { if (!myCaretEnabled) { return; } int x = getCaretX(shiftX); if (getCaretPosition() != 0) { x--; } g.setColor(EditorSettings.getInstance().getCaretColor()); g.fillRect(x, shiftY + getPaddingTop(), 2, myTextHeight); } public void repaintCaret(Component component, int shiftX, int shiftY) { int x = getCaretX(shiftX); component.repaint(x - 1, shiftY + getPaddingTop() - 1, x + 2, myTextHeight + 2); } public int getCaretX(int shiftX) { if (myCaretX == -1) { myCaretX = getTextWidth(getCaretPosition()); } return shiftX + getPaddingLeft() + myCaretX; } private int getSelectionStartX() { if (mySelectionStartX == -1) { mySelectionStartX = getTextWidth(getStartTextSelectionPosition()); } return mySelectionStartX; } private int getSelectionEndX() { if (mySelectionEndX == -1) { mySelectionEndX = getTextWidth(getEndTextSelectionPosition()); } return mySelectionEndX; } private int getTextEndX() { if (myTextEndX == -1) { myTextEndX = getTextWidth(getText().length()); } return myTextEndX; } private int getTextWidth(int caretPosition) { return getEditorFontMetrics().getWidth(myText, 0, caretPosition); } public EditorFontMetrics getEditorFontMetrics() { init(); return myFontMetrics; } /** * @deprecated use {@link #getEditorFontMetrics()} instead */ @Deprecated public FontMetrics getFontMetrics() { return ((EditorFontMetricsImpl) getEditorFontMetrics()).getFontMetrics(); } public String getTextuallySelectedText() { if (getStartTextSelectionPosition() > getEndTextSelectionPosition()) { return ""; } return myText.substring(getStartTextSelectionPosition(), getEndTextSelectionPosition()); } public void resetSelection() { setStartTextSelectionPosition(getCaretPosition()); setEndTextSelectionPosition(getCaretPosition()); } public boolean hasNonTrivialSelection() { return (getStartTextSelectionPosition() != getCaretPosition() || getEndTextSelectionPosition() != getCaretPosition()); } public void setStartTextSelectionPosition(int i) { assert i >= 0; this.myStartTextSelectionPosition = Math.min(i, myText.length()); mySelectionStartX = -1; } public void setEndTextSelectionPosition(int i) { assert i >= 0; this.myEndTextSelectionPosition = Math.min(i, myText.length()); mySelectionEndX = -1; } public void selectAll() { setStartTextSelectionPosition(0); setEndTextSelectionPosition(getText().length()); } public void deselectAll() { setStartTextSelectionPosition(getCaretPosition()); setEndTextSelectionPosition(getCaretPosition()); } public boolean isEverythingSelected() { return getStartTextSelectionPosition() == 0 && getEndTextSelectionPosition() == getText().length(); } public void setCaretByXCoord(int x) { setCaretPosition(getCaretPositionByXCoord(x)); } public int getCaretPositionByXCoord(int _x) { int x = _x - getPaddingLeft(); EditorFontMetrics metrics = getEditorFontMetrics(); int caretPosition = myText.length(); int len = 0; for (int i = 0; i < myText.length(); i++) { int newLen = metrics.getWidth(myText, 0, i + 1); if (x <= (len + newLen + 1) / 2) { caretPosition = i; break; } len = newLen; } return caretPosition; } public int getCaretPosition() { return myCaretPosition; } public void setCaretPosition(int i) { setCaretPosition(i, false); } private void doSetCaretPosition(int position) { myCaretPosition = position; myCaretX = -1; } public void setCaretPosition(int position, boolean duringSelection) { assert position >= 0; if (!duringSelection) { doSetCaretPosition(Math.min(myText.length(), position)); setStartTextSelectionPosition(getCaretPosition()); setEndTextSelectionPosition(getCaretPosition()); return; } int old = getCaretPosition(); doSetCaretPosition(Math.min(myText.length(), position)); if (getEndTextSelectionPosition() == old) { setEndTextSelectionPosition(getCaretPosition()); } else { setStartTextSelectionPosition(getCaretPosition()); } if (getEndTextSelectionPosition() < getStartTextSelectionPosition()) { int temp = getEndTextSelectionPosition(); setEndTextSelectionPosition(getStartTextSelectionPosition()); setStartTextSelectionPosition(temp); } } public boolean isUnderlined() { init(); if (myControlOvered) { return true; } return myUnderlined; } public boolean isStrikeOut() { init(); return myStrikeOut; } public int getAscent() { return myTextHeight - myDescent; } public int getDescent() { return myDescent; } }
30.01669
147
0.702345
298da35803769f57fad32fa86ad8bd2503f977f1
753
import java.io.*; class sort_11 { void input()throws IOException { DataInputStream in=new DataInputStream(System.in); int n; System.out.println("enter array size"); n=Integer.parseInt(in.readLine()); int a[]=new int[n]; int i; for(i=0;i<n;i++) { System.out.println("Enter number"); a[i]=Integer.parseInt(in.readLine()); } int j=0,temp=0,pos=0,mid=0,k=1,t=1; int b[]=new int [n]; for(i=0;i<n-1;i++) { pos=i; for(j=i+1;j<n;j++) { if(a[j]>a[pos]) pos=j; } temp=a[pos]; a[pos]=a[i]; a[i]=temp; } mid=n/2; t=1; b[mid]=a[0]; for(i=1;i<n;i=i+2) { b[mid+k]=a[i]; b[mid-k]=a[i+1]; k=k+1; } System.out.println("Newly Sorted Array"); for(i=0;i<n;i++) { for(j=0;j<=30000;j++) { } System.out.print(b[i]+" "); } } }
14.764706
51
0.565737
98dfe13b67d5494fba4376f640b6ea1c51df117c
830
/* * Decompiled with CFR 0.152. * * Could not load the following classes: * com.intellij.ui.ColorUtil * com.intellij.util.xmlb.Converter * org.jetbrains.annotations.NotNull * org.jetbrains.annotations.Nullable */ package com.github.copilot.settings; import com.intellij.ui.ColorUtil; import com.intellij.util.xmlb.Converter; import java.awt.Color; public class ColorConverter extends Converter<Color> { public Color fromString(String value) { if (value == null) { throw new IllegalStateException("value cannot be null!"); } try { return ColorUtil.fromHex((String) value); } catch (Exception e) { return null; } } public String toString(Color value) { if (value == null) { throw new IllegalStateException("value cannot be null!"); } return ColorUtil.toHtmlColor((Color) value); } }
23.055556
60
0.714458
8173ad0c093fe451d44036f62717d8db1e2e3528
1,169
/* * Copyright (C) 2013 Artur Termenji * * 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.distantfuture.iconicdroid.icon; import android.graphics.Typeface; import com.distantfuture.iconicdroid.util.TypefaceManager; import java.io.Serializable; /** * An interface which every icon font wrapper should implement. */ public interface Icon extends Serializable { /** * Gets a {@link Typeface} for an Icon. * * @return {@link IconicTypeface} */ public TypefaceManager.IconicTypeface getIconicTypeface(); /** * Returns UTF value of an Icon. * * @return UTF value of an Icon */ public int getIconUtfValue(); }
26.568182
75
0.723695
630f731eeac621c08aeb84d9c780d1ecfd1833b7
791
package com.mchekin.designpatterns.abstractfactory; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class AnimalAbstractFactoryTest { @Test public void africanAnimalsGreetings() { Application application = new Application(new AfricanAnimalFactory()); assertEquals("African elephant trumpets.", application.elephantGreeting()); assertEquals("African rhino raises horn.", application.rhinoGreeting()); } @Test public void asianAnimalsGreetings() { Application application = new Application(new AsianAnimalFactory()); assertEquals("Asian elephant trumpets.", application.elephantGreeting()); assertEquals("Asian rhino raises horn.", application.rhinoGreeting()); } }
31.64
83
0.733249
82aee61d76674b58a6c2eecf16c4cbb212916233
349
package com.egoveris.deo.base.exception; import org.terasoluna.plus.common.exception.ApplicationException; public class NoEsDocumentoSadePapelException extends ApplicationException{ /** * */ private static final long serialVersionUID = 3648524018593622835L; public NoEsDocumentoSadePapelException(final String msg){ super(msg); } }
20.529412
74
0.796562
18ec08a516f26b60a797484421264f74d9499f63
6,669
// Copyright 2011-2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.security.zynamics.binnavi.Plugins; import com.google.common.base.Preconditions; import com.google.security.zynamics.zylib.general.Pair; import com.google.security.zynamics.zylib.gui.ProgressDialogs.IStandardDescriptionUpdater; import com.google.security.zynamics.zylib.io.DirUtils; import com.google.security.zynamics.zylib.io.IDirectoryTraversalCallback; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** * Class that loads all plugins that can be found in the plugins directory. */ public final class PluginLoader { /** * You are not supposed to instantiate this class. */ private PluginLoader() {} /** * Loads all plugin files of a given directory. * * @param pluginPath The path to the plugins directory. * @param pluginFiles The plugin files to load. * @param descriptionUpdater Receives updates about the load progress. This argument can be null. * * @return The result of the load process. */ private static <T> LoadResult<T> loadPluginFiles(final String pluginPath, final Set<File> pluginFiles, final IStandardDescriptionUpdater descriptionUpdater) { final ArrayList<Pair<com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T>, PluginStatus>> loadedPlugins = new ArrayList<>(); final ArrayList<Pair<String, Throwable>> failedPlugins = new ArrayList<>(); for (final File pluginFile : pluginFiles) { if (pluginFile.getName().endsWith(".jar")) { descriptionUpdater.next(); descriptionUpdater.setDescription( String.format("Loading plugin JAR file '%s'", pluginFile.getName())); JarPluginLoader.processJarFile(pluginFile, loadedPlugins, failedPlugins); } else if (pluginFile.getName().endsWith(".class")) { descriptionUpdater.next(); descriptionUpdater.setDescription( String.format("Loading plugin CLASS file '%s'", pluginFile.getName())); ClassPluginLoader.processClassFile(pluginPath, pluginFile, loadedPlugins, failedPlugins); } } return new LoadResult<T>(loadedPlugins, failedPlugins); } /** * Validates the loaded plugins and disables those which are invalid. * * @param result Result of previous load operation. * * @return New load result that includes validation state. */ private static <T> LoadResult<T> validateLoadedPlugins(final LoadResult<T> result) { // Load all plugins final HashSet<Long> guids = new HashSet<>(); final ArrayList<Pair<com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T>, PluginStatus>> validatedPlugins = new ArrayList<>(); // Check the validity of the loaded plugins and remove those // which have problems. This part enforces the existence // of a proper plugin name and a unique GUID. for (final Pair<com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T>, PluginStatus> pluginPair : result.getLoadedPlugins()) { final com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T> plugin = pluginPair.first(); final String name = plugin.getName(); final long guid = plugin.getGuid(); if ((name == null) && (guid == 0)) { validatedPlugins.add(new Pair<com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T>, PluginStatus>(plugin, PluginStatus.InvalidNameGuid)); } else if (name == null) { validatedPlugins.add(new Pair<com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T>, PluginStatus>(plugin, PluginStatus.InvalidName)); } else if (guid == 0) { validatedPlugins.add(new Pair<com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T>, PluginStatus>(plugin, PluginStatus.InvalidGuid)); } else if (guids.contains(guid)) { validatedPlugins.add(new Pair<com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T>, PluginStatus>(plugin, PluginStatus.DuplicateGuid)); } else { validatedPlugins.add(new Pair<com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T>, PluginStatus>(plugin, PluginStatus.Valid)); } guids.add(guid); } return new LoadResult<T>(validatedPlugins, result.getFailedPlugins()); } /** * Collects all plugin files from the plugin directory. * * @param directory The plugin directory. * * @return The collected plugin files. */ public static Set<File> collectPluginFiles(final String directory) { final Set<File> pluginFiles = new HashSet<File>(); final File file = new File(directory); DirUtils.traverse(file, new IDirectoryTraversalCallback() { @Override public void entering(final File directory) { System.out.println(directory.getName()); // Unused } @Override public void leaving(final File directory) { // Unused } @Override public void nextFile(final File pluginFile) { System.out.println(pluginFile.getName()); if (pluginFile.getName().endsWith(".jar") || pluginFile.getName().endsWith(".class")) { pluginFiles.add(pluginFile); } } }); return pluginFiles; } /** * Loads the plugins, validates them and initializes those that are valid. * * @param pluginPath The path to the plugins directory. * @param pluginFiles The plugin files to load. * @param descriptionUpdater Receives updates about the load progress. This argument can be null. * * @return The result of the load operation. */ public static <T> LoadResult<T> loadPlugins(final String pluginPath, final Set<File> pluginFiles, final IStandardDescriptionUpdater descriptionUpdater) { Preconditions.checkNotNull(pluginFiles, "IE00832: Plugin files can't be null"); descriptionUpdater.reset(); descriptionUpdater.setMaximum(pluginFiles.size()); final LoadResult<T> loadResult = loadPluginFiles(pluginPath, pluginFiles, descriptionUpdater); return validateLoadedPlugins(loadResult); } }
37.892045
99
0.701454
64a371e66b4062d4d34c9dedd1e5876e0b26b72a
739
package net.rodrigoamaral.algorithms.smpso; import org.uma.jmetal.problem.DoubleProblem; import org.uma.jmetal.solution.DoubleSolution; import org.uma.jmetal.util.archive.BoundedArchive; public class SMPSO_MABuilder extends SMPSOBuilder { public SMPSO_MABuilder(DoubleProblem problem, BoundedArchive<DoubleSolution> leaders) { super(problem, leaders); } public SMPSO build() { return new SMPSO_MA(getProblem(), getSwarmSize(), leaders, getMutationOperator(), getMaxIterations(), getR1Min(), getR1Max(), getR2Min(), getR2Max(), getC1Min(), getC1Max(), getC2Min(), getC2Max(), getWeightMin(), getWeightMax(), getChangeVelocity1(), getChangeVelocity2(), getEvaluator()); } }
41.055556
121
0.719892
fb02ad19b1aefc8a80b36099a221772ff8e034eb
214
package test; public class B { private A bf; public B() { A a = new A(); this.bf = a; } public int get() { A a = this.bf; return a.get(); } public void set(int i) { A a = this.bf; a.set(i); } }
11.888889
25
0.528037
493e65f715afc6443f8bef9928e010d95beba8c2
297
package Main; import javax.swing.JFrame; public class MainFrame extends JFrame{ public MainFrame() { this.setContentPane(new GameEngine()); this.setSize(1200+16, 600+38); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setResizable(false); this.setVisible(true); } }
18.5625
54
0.740741
7a9b5ddf4ed95f980c08469f2cae4cc0dc1be0db
639
package org.yugzan.amqp.core; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.stereotype.Component; import org.yugzan.amqp.config.RabbitConfiguration; import org.yugzan.amqp.model.Item; /** * @author yongzan * @date 2018/11/05 */ @Component @RabbitListener(queues = RabbitConfiguration.queueName) public class ReceiverTask { @RabbitHandler public void findItem(@Payload Item message) { System.out.println("<Receiver item:" + message.getId()); } }
26.625
65
0.790297
33d422bc7ab64297bcc8963b1d338a41700cdf8b
2,158
package ca.bc.gov.open.ecrc.service; import java.util.Map; import ca.bc.gov.open.ecrc.exception.EcrcServiceException; import ca.bc.gov.open.ecrc.model.*; import javassist.NotFoundException; import org.json.JSONObject; import org.springframework.http.ResponseEntity; /** * * Interface for ECRC Service * * @author shaunmillargov * */ public interface EcrcServices { public ResponseEntity<String> doAuthenticateUser(String orgTicketNumber, String requestGuid) throws EcrcServiceException, NotFoundException; public Map<String, String> getLinks() throws EcrcServiceException; public ResponseEntity<String> getProvinceList(String requestGuid) throws EcrcServiceException; public ResponseEntity<String> getNextSessionId(String orgTicketNumber, String requestGuid) throws EcrcServiceException; public ResponseEntity<String> createApplicant(RequestCreateApplicant applicantInfo) throws EcrcServiceException; public ResponseEntity<String> createNewCRCService(RequestNewCRCService crcService) throws EcrcServiceException; public ResponseEntity<String> updateServiceFinancialTxn(RequestUpdateServiceFinancialTxn updateServiceFinancialTxn) throws EcrcServiceException; public ResponseEntity<String> getServiceFeeAmount(String orgTicketNumber, String scheduleTypeCd, String scopeLevelCd, String requestGuid) throws EcrcServiceException; public ResponseEntity<String> logPaymentFailure(RequestLogPaymentFailure paymentFailure) throws EcrcServiceException; public ResponseEntity<String> getNextInvoiceId(String orgTicketNumber, String requestGuid) throws EcrcServiceException; public JSONObject getJwtDetails() throws EcrcServiceException; public ResponseEntity<String> checkApplicantForPrevCrc(RequestCheckApplicantForPrevCrc applicantInfo) throws EcrcServiceException; public ResponseEntity<String> createSharingService(RequestCreateSharingService serviceInfo) throws EcrcServiceException; public ResponseEntity<String> createNewCRCApplicant(RequestNewCRCApplicant requestNewCRCApplicant) throws EcrcServiceException; public ResponseEntity<String> createCRCShare(RequestCRCShare requestCRCShare) throws EcrcServiceException; }
40.716981
167
0.859129
3c770dd17b5cd442fb93dec8bca612c1f5cc8fc5
2,758
package uk.co.compendiumdev.restlisticator.api.action; import uk.co.compendiumdev.restlisticator.api.ApiRequest; import uk.co.compendiumdev.restlisticator.api.ApiResponse; import uk.co.compendiumdev.restlisticator.api.UserAuthenticator; import uk.co.compendiumdev.restlisticator.api.payloads.UserPayload; import uk.co.compendiumdev.restlisticator.api.payloads.convertor.PayloadConvertor; import uk.co.compendiumdev.restlisticator.domain.users.User; import uk.co.compendiumdev.restlisticator.domain.users.UserAccessPermission; import uk.co.compendiumdev.restlisticator.http.ApiEndPoint; public class GetUserDetailsApiAction implements ApiAction{ private final ApiResponse apiResponse; private final ApiRequest apiRequest; private PayloadConvertor payloadConvertor; private UserAuthenticator userAuthenticator; private User authenticatedUser; public GetUserDetailsApiAction(ApiRequest apiRequest, ApiResponse apiResponse) { this.apiRequest = apiRequest; this.apiResponse = apiResponse; } public GetUserDetailsApiAction setConvertor(PayloadConvertor convertor) { this.payloadConvertor = convertor; return this; } public GetUserDetailsApiAction setUserAuthenticator(UserAuthenticator userAuthenticator) { this.userAuthenticator = userAuthenticator; return this; } public GetUserDetailsApiAction setAuthenticatedUser(User authenticatedUser) { this.authenticatedUser = authenticatedUser; return this; } public ApiResponse perform() { String username = apiRequest.getPathParts()[0]; User targetUser = userAuthenticator.getUser(username); // make sure this is permission protected and user can access this user's details if(targetUser!=null){ if(!authenticatedUser.getUsername().contentEquals(targetUser.getUsername())){ // not same user - make sure they can do this if(!authenticatedUser.permissions().can(UserAccessPermission.READ_ANY_USER, ApiEndPoint.USERS)){ apiResponse.setAsUnauthorized(); return apiResponse; }; } } // if target user does not exist then return 404 if(targetUser==null){ apiResponse.setAsNotFound(); return apiResponse; } UserPayload userDetails = new UserPayload(); userDetails.username = targetUser.getUsername(); userDetails.apikey = targetUser.getApikey(); String payload= payloadConvertor.convert(userDetails, apiRequest.getResponseFormat()); apiResponse.setBody(payload); apiResponse.setAsSuccessful_OK(); return apiResponse; } }
34.475
112
0.715373
f65556bdab2e352bf61bd32b8dca540e09b9b85b
3,336
/** * ------------------------------------------------------------ * QuickTodo Lite * ------------------------------------------------------------ * * 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.jetpad.quicktodofree; import android.net.Uri; import android.provider.BaseColumns; /** * Convenience definitions for TodoProvider */ public final class QuickTodo { public static final String AUTHORITY = "org.jetpad.provider.QuickTodoFree"; // This class cannot be instantiated private QuickTodo() {} /** * Todo table */ public static final class Todo implements BaseColumns { // This class cannot be instantiated private Todo() {} /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/todos"); /** * The MIME type of {@link #CONTENT_URI} providing a directory of notes. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.jetpad.todof"; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single note. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.jetpad.todof"; /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "completed,hasduedate DESC,duedate"; /** * The title of the note * <P>Type: TEXT</P> */ public static final String TITLE = "title"; /** * The note itself * <P>Type: TEXT</P> */ public static final String NOTE = "note"; /** * The timestamp for when the note was created * <P>Type: INTEGER (long from System.curentTimeMillis())</P> */ public static final String CREATED_DATE = "created"; /** * The timestamp for when the note was last modified * <P>Type: INTEGER (long from System.curentTimeMillis())</P> */ public static final String MODIFIED_DATE = "modified"; public static final String DUE_DATE = "duedate"; public static final String COMPLETED = "completed"; public static final String FOLDER = "folder"; public static final String NOTIFY_DATE = "notify_date"; public static final String ICON = "icon"; public static final String CONTEXT = "context"; public static final String HAS_DUE_DATE = "hasduedate"; public static final String HAS_REMINDER = "hasreminder"; public static final String IS_SCHEDULED = "isscheduled"; public static final String PRIORITY = "priority"; public static final String SCHEDULE_DATE = "scheduledate"; public static final String INBOX = "inbox"; } }
33.69697
98
0.618405
88175d3e4a38c3cec279f132b55f703bc317b3b7
1,133
package org.apache.rocketmq.common.protocol.header; import org.apache.rocketmq.remoting.CommandCustomHeader; import org.apache.rocketmq.remoting.annotation.CFNotNull; import org.apache.rocketmq.remoting.annotation.CFNullable; import org.apache.rocketmq.remoting.exception.RemotingCommandException; public class UnregisterClientRequestHeader implements CommandCustomHeader { @CFNotNull private String clientID; @CFNullable private String producerGroup; @CFNullable private String consumerGroup; public String getClientID() { return clientID; } public void setClientID(String clientID) { this.clientID = clientID; } public String getProducerGroup() { return producerGroup; } public void setProducerGroup(String producerGroup) { this.producerGroup = producerGroup; } public String getConsumerGroup() { return consumerGroup; } public void setConsumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; } @Override public void checkFields() throws RemotingCommandException { } }
23.604167
75
0.728155
cb6b1291010f28524497a54d361b7957b9769a68
237
package com.cier.base.sta; public class Test1 { static int x = 10; static { x += 5; } static { x /= 3; } public static void main(String[] args) { System.out.println("x=" + x); } }
12.473684
44
0.476793
eca2cf34ea3cbdb529a502fc22be001f1fe9145e
297
package ar.com.tandilweb.exchange.gameProtocol.texasHoldem.inGame; import ar.com.tandilweb.exchange.gameProtocol.texasHoldem.InGameSchema; public class CardDist extends InGameSchema { public int position; public boolean[] cards; public CardDist() { super("cardDist"); } }
21.214286
72
0.744108
dd6e97933004067a35a9dc65762147ef9b483370
4,568
package cc.mrbird.febs.check.controller; import cc.mrbird.febs.common.annotation.Log; import cc.mrbird.febs.common.controller.BaseController; import cc.mrbird.febs.common.domain.router.VueRouter; import cc.mrbird.febs.common.exception.FebsException; import cc.mrbird.febs.common.domain.QueryRequest; import cc.mrbird.febs.check.service.ICheckDTitleService; import cc.mrbird.febs.check.entity.CheckDTitle; import cc.mrbird.febs.common.utils.FebsUtil; import cc.mrbird.febs.system.domain.User; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.wuwenze.poi.ExcelKit; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * * @author viki * @since 2021-01-22 */ @Slf4j @Validated @RestController @RequestMapping("checkDTitle") public class CheckDTitleController extends BaseController{ private String message; @Autowired public ICheckDTitleService iCheckDTitleService; /** INSERT into t_menu(parent_id,menu_name,path,component,perms,icon,type,order_num,CREATE_time) VALUES (0,'指标表','/dca/CheckDTitle/CheckDTitle','dca/CheckDTitle/CheckDTitle','checkDTitle:view','fork',0,1,NOW()) SELECT MAX(MENU_ID) from t_menu; INSERT into t_menu(parent_id,MENU_NAME,perms,type,order_num,CREATE_time) VALUES(0,'指标表新增','checkDTitle:add',1,1,NOW()) INSERT into t_menu(parent_id,MENU_NAME,perms,type,order_num,CREATE_time) VALUES(0,'指标表编辑','checkDTitle:update',1,1,NOW()) INSERT into t_menu(parent_id,MENU_NAME,perms,type,order_num,CREATE_time) VALUES(0,'指标表删除','checkDTitle:delete',1,1,NOW()) */ /** * 分页查询数据 * * @param request 分页信息 * @param checkDTitle 查询条件 * @return */ @GetMapping @RequiresPermissions("checkDTitle:view") public Map<String, Object> List(QueryRequest request, CheckDTitle checkDTitle){ return getDataTable(this.iCheckDTitleService.findCheckDTitles(request, checkDTitle)); } /** * 添加 * @param checkDTitle * @return */ @Log("新增/按钮") @PostMapping @RequiresPermissions("checkDTitle:add") public void addCheckDTitle(@Valid CheckDTitle checkDTitle)throws FebsException{ try{ User currentUser= FebsUtil.getCurrentUser(); checkDTitle.setCreateUserId(currentUser.getUserId()); this.iCheckDTitleService.createCheckDTitle(checkDTitle); }catch(Exception e){ message="新增/按钮失败" ; log.error(message,e); throw new FebsException(message); } } /** * 修改 * @param checkDTitle * @return */ @Log("修改") @PutMapping @RequiresPermissions("checkDTitle:update") public void updateCheckDTitle(@Valid CheckDTitle checkDTitle)throws FebsException{ try{ User currentUser= FebsUtil.getCurrentUser(); checkDTitle.setModifyUserId(currentUser.getUserId()); this.iCheckDTitleService.updateCheckDTitle(checkDTitle); }catch(Exception e){ message="修改失败" ; log.error(message,e); throw new FebsException(message); } } @Log("删除") @DeleteMapping("/{ids}") @RequiresPermissions("checkDTitle:delete") public void deleteCheckDTitles(@NotBlank(message = "{required}") @PathVariable String ids)throws FebsException{ try{ String[]arr_ids=ids.split(StringPool.COMMA); this.iCheckDTitleService.deleteCheckDTitles(arr_ids); }catch(Exception e){ message="删除失败" ; log.error(message,e); throw new FebsException(message); } } @PostMapping("excel") @RequiresPermissions("checkDTitle:export") public void export(QueryRequest request, CheckDTitle checkDTitle, HttpServletResponse response) throws FebsException { try { List<CheckDTitle> checkDTitles = this.iCheckDTitleService.findCheckDTitles(request, checkDTitle).getRecords(); ExcelKit.$Export(CheckDTitle.class, response).downXlsx(checkDTitles, false); } catch (Exception e) { message = "导出Excel失败"; log.error(message, e); throw new FebsException(message); } } @GetMapping("/{id}") public CheckDTitle detail(@NotBlank(message = "{required}") @PathVariable String id) { CheckDTitle checkDTitle=this.iCheckDTitleService.getById(id); return checkDTitle; } }
32.628571
122
0.733363
fe92a98c5ec6fb00ca04ec2b0745f34e945ff0a7
5,344
/* * Copyright 2014 Guidewire Software, Inc. */ package gw.lang.annotation; import gw.lang.GosuShop; import gw.lang.reflect.IAnnotationInfo; import gw.lang.reflect.IType; import gw.lang.reflect.TypeSystem; import gw.lang.reflect.java.IJavaType; import gw.lang.reflect.java.JavaTypes; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public enum UsageModifier { /** * Use None to specify this annotation cannot exist on a class */ None, /** * Use None to specify this annotation can only appear once on a class */ One, /** * Use None to specify this annotation can appear many times on a class */ Many; public static UsageModifier getUsageModifier( UsageTarget targetType, IType annotationType ) { UsageModifier modifier = null; //First look for gosu-style usage annotations ArrayList<IAnnotationInfo> usageInfos = getExplicitUsageAnnotations(annotationType); if( usageInfos != null && usageInfos.size() > 0 ) { return getUsageModifier( targetType, modifier, usageInfos ); } // if it's a java annotation with no explicit annotation usage, translate the java element type information else if( JavaTypes.ANNOTATION().isAssignableFrom( annotationType ) ) { return translateJavaElementTypeToUsageModifier( targetType, annotationType ); } else { // By default, gosu annotations can appear multiple times return UsageModifier.Many; } } private static ArrayList<IAnnotationInfo> getExplicitUsageAnnotations(IType type) { ArrayList<IAnnotationInfo> lst = new ArrayList<IAnnotationInfo>(); List<IAnnotationInfo> usageAnnotations = type.getTypeInfo().getAnnotationsOfType( JavaTypes.ANNOTATION_USAGE() ); if( usageAnnotations != null ) { lst.addAll(usageAnnotations); } List<IAnnotationInfo> usagesAnnotations = type.getTypeInfo().getAnnotationsOfType( JavaTypes.ANNOTATION_USAGES() ); if( usagesAnnotations != null ) { for( IAnnotationInfo iAnnotationInfo : usagesAnnotations ) { IAnnotationInfo[] values = (IAnnotationInfo[]) GosuShop.getAnnotationFieldValueAsArray(iAnnotationInfo, "value"); lst.addAll( Arrays.asList(values) ); } } return lst; } private static UsageModifier getUsageModifier( UsageTarget targetType, UsageModifier modifier, ArrayList<IAnnotationInfo> annotationInfos ) { //If there are usages, then we must examine each one to find the one that most specifically applies for( IAnnotationInfo usage : annotationInfos ) { String target = (String) usage.getFieldValue("target"); String usageModifier = (String) usage.getFieldValue("usageModifier"); // If usage applies to all, and we haven't had a more specific match yet, get the modifier for it if( target.equals(UsageTarget.AllTarget.name()) && modifier == null ) { modifier = UsageModifier.valueOf(usageModifier); } // If usage applies to the given target, it always overrides whatever else we've seen if( target.equals(targetType.name()) ) { modifier = UsageModifier.valueOf(usageModifier); } } // if no usage matched, then that implies that the usage is None. if( modifier == null ) { modifier = UsageModifier.None; } return modifier; } private static UsageModifier translateJavaElementTypeToUsageModifier( UsageTarget targetType, IType annotationType ) { IAnnotationInfo targetAnnotation = annotationType.getTypeInfo().getAnnotation( TypeSystem.get( Target.class ) ); boolean bRepeatable = annotationType.getTypeInfo().hasAnnotation( JavaTypes.REPEATABLE() ); if( targetAnnotation == null ) { return bRepeatable ? UsageModifier.Many : UsageModifier.One; } else { Object v = targetAnnotation.getFieldValue( "value" ); String[] value; if( v == null ) { value = null; } else if( v.getClass().isArray() ) { value = (String[])v; } else { value = new String[]{(String)v}; } if( value == null || value.length == 0 ) { return bRepeatable ? UsageModifier.Many : UsageModifier.One; // If there are no targets, it can be used everywhere } // otherwise, look for a target that matches our own UsageTarget for( String elementTypeConst : value ) { if( elementTypeConst.equals( ElementType.CONSTRUCTOR.name() ) && targetType == UsageTarget.ConstructorTarget || elementTypeConst.equals( ElementType.FIELD.name() ) && targetType == UsageTarget.PropertyTarget || elementTypeConst.equals( ElementType.ANNOTATION_TYPE.name() ) && targetType == UsageTarget.TypeTarget || elementTypeConst.equals( ElementType.TYPE.name() ) && targetType == UsageTarget.TypeTarget || elementTypeConst.equals( ElementType.METHOD.name() ) && (targetType == UsageTarget.MethodTarget || targetType == UsageTarget.PropertyTarget) || elementTypeConst.equals( ElementType.PARAMETER.name() ) && targetType == UsageTarget.ParameterTarget ) { return bRepeatable ? UsageModifier.Many : UsageModifier.One; } } return UsageModifier.None; } } }
36.60274
155
0.69143
84ced61f61259754bdc8237b7feda0054e056b44
7,138
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.andes.store.cache; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.Weigher; import com.gs.collections.api.iterator.MutableLongIterator; import com.gs.collections.impl.list.mutable.primitive.LongArrayList; import com.gs.collections.impl.map.mutable.primitive.LongObjectHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.andes.configuration.AndesConfigurationManager; import org.wso2.andes.configuration.enums.AndesConfiguration; import org.wso2.andes.kernel.AndesMessage; import org.wso2.andes.kernel.AndesMessagePart; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Message cache implementation based on Guava {@link Cache} */ public class GuavaBasedMessageCacheImpl implements AndesMessageCache { private static final Log log = LogFactory.getLog(GuavaBasedMessageCacheImpl.class); /** * By default cache values will be kept using strong/ordinary references. */ private static final String CACHE_VALUE_REF_TYPE_STRONG = "strong"; /** * Cache values can be kept using weak references. */ private static final String CACHE_VALUE_REF_TYPE_WEAK = "weak"; /** * Size of the cache is determined via configuration. For example cache can * keep 1GB 'worth of' message payloads (and its meta data) in the memory. */ private final Cache<Long, AndesMessage> cache; /** * Used to schedule a cache clean up task and print cache statistics ( used for debugging perposes) */ private ScheduledExecutorService maintenanceExecutor; /** * Flag indicating guava cache statistics should be printed on logs */ private final boolean printStats; /** * Max chunk size of the stored content in Andes. This is needed to count the index * of a particular chunk in the chunk list when the offset is given. */ private static int DEFAULT_CONTENT_CHUNK_SIZE; public GuavaBasedMessageCacheImpl() { DEFAULT_CONTENT_CHUNK_SIZE = AndesConfigurationManager .readValue(AndesConfiguration.PERFORMANCE_TUNING_MAX_CONTENT_CHUNK_SIZE); long cacheSizeInBytes = 1024L * 1024L * ((int) AndesConfigurationManager.readValue(AndesConfiguration.PERSISTENCE_CACHE_SIZE)); int cacheConcurrency = AndesConfigurationManager .readValue(AndesConfiguration.PERSISTENCE_CACHE_CONCURRENCY_LEVEL); int cacheExpirySeconds = AndesConfigurationManager .readValue(AndesConfiguration.PERSISTENCE_CACHE_EXPIRY_SECONDS); String valueRefType = AndesConfigurationManager .readValue(AndesConfiguration.PERSISTENCE_CACHE_VALUE_REFERENCE_TYPE); printStats = AndesConfigurationManager.readValue(AndesConfiguration.PERSISTENCE_CACHE_PRINT_STATS); CacheBuilder<Long, AndesMessage> builder = CacheBuilder.newBuilder().concurrencyLevel(cacheConcurrency) .expireAfterAccess(cacheExpirySeconds, TimeUnit.SECONDS).maximumWeight(cacheSizeInBytes) .weigher(new Weigher<Long, AndesMessage>() { @Override public int weigh(Long l, AndesMessage m) { return m.getMetadata().getMessageContentLength(); } }); if (printStats) { builder = builder.recordStats(); } if (CACHE_VALUE_REF_TYPE_WEAK.equalsIgnoreCase(valueRefType)) { builder = builder.weakValues(); } this.cache = builder.build(); maintenanceExecutor = Executors.newSingleThreadScheduledExecutor(); maintenanceExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { cache.cleanUp(); if (printStats) { log.info("cache stats:" + cache.stats().toString()); } } }, 2, 2, TimeUnit.MINUTES); } /** * {@inheritDoc} */ @Override public void addToCache(AndesMessage message) { cache.put(message.getMetadata().getMessageID(), message); } /** * {@inheritDoc} */ @Override public void removeFromCache(LongArrayList messagesToRemove) { ArrayList<Long> arrayList = new ArrayList<>(); MutableLongIterator iterator = messagesToRemove.longIterator(); while (iterator.hasNext()) { arrayList.add(iterator.next()); } cache.invalidateAll(arrayList); } /** * {@inheritDoc} */ @Override public void removeFromCache(long messageToRemove) { cache.invalidate(messageToRemove); } /** * {@inheritDoc} */ @Override public AndesMessage getMessageFromCache(long messageId) { return cache.getIfPresent(messageId); } /** * {@inheritDoc} */ @Override public void fillContentFromCache(LongArrayList messageIDList, LongObjectHashMap<List<AndesMessagePart>> contentList) { MutableLongIterator iterator = messageIDList.longIterator(); while (iterator.hasNext()) { Long messageID = iterator.next(); AndesMessage andesMessage = cache.getIfPresent(messageID); if (null != andesMessage) { contentList.put(messageID, andesMessage.getContentChunkList()); iterator.remove(); } } } /** * {@inheritDoc} */ @Override public AndesMessagePart getContentFromCache(long messageId, int offsetValue) { AndesMessage cachedMessage = getMessageFromCache(messageId); AndesMessagePart part = null; if (null != cachedMessage) { //the offset comes as a multiple of DEFAULT_CONTENT_CHUNK_SIZE after being converted in method //'fillBufferFromContent' in {@link org.wso2.andes.amqp.AMQPUtils} //therefore, offsetValue / DEFAULT_CONTENT_CHUNK_SIZE gives the correct index of a particular chunk // in the content chunk list part = getMessageFromCache(messageId).getContentChunkList().get(offsetValue / DEFAULT_CONTENT_CHUNK_SIZE); } return part; } }
33.046296
119
0.6761
d3ef22b52ba70fd24b18ca7ba0d95bdcced7f05e
1,706
package org.c4c.eventstorej.api; import org.c4c.eventstorej.Event; import java.util.List; import java.util.UUID; public interface EventStore { void init() throws Throwable; int saveEvent(Event event) throws Throwable; <T> int saveEvent(List<Event<T>> eventList) throws Throwable; <T> List<Event<T>> getEventList(String aggregateId, final Class<T> classType) throws Throwable; <T> List<Event<T>> getEventList(UUID aggregateId, final Class<T> classType) throws Throwable; <T> List<Event<T>> getEventList(String aggregateId, int fromRevision, int toRevision, final Class<T> classType) throws Throwable; <T> List<Event<T>> getEventList(UUID aggregateId, int fromRevision, int toRevision, final Class<T> classType) throws Throwable; <T> Event<T> getLastEvent(String aggregateId, final Class<T> classType) throws Throwable; <T> Event<T> getLastEvent(UUID aggregateId, final Class<T> classType) throws Throwable; <T> List<Event<T>> getUnpublishedEventList(final Class<T> classType) throws Throwable; int updateToPublished(String aggregateId, int fromRevision, int toRevision) throws Throwable; <T> int updateToPublished(UUID aggregateId, int fromRevision, int toRevision) throws Throwable; int saveSnapShot(String aggregateId, int revision, Object state) throws Throwable; int saveSnapShot(UUID aggregateId, int revision, Object state) throws Throwable; <T> T getSnapShot(String aggregateId, final Class<T> classType) throws Throwable; <T> T getSnapShot(UUID aggregateId, final Class<T> classType) throws Throwable; <T> List<Event<T>> getReplay(int fromPosition, int toPosition, final Class<T> classType) throws Throwable; }
38.772727
133
0.756155