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
36870482ce8c4c04ec51aa80d9b77fe76a827689
4,120
package org.team2168.utils; import java.util.TimerTask; import org.team2168.Robot; import org.team2168.RobotMap; import org.team2168.subsystems.Tusks; import org.team2168.subsystems.Vision; import org.team2168.subsystems.Winch; import org.team2168.subsystems.Drivetrain; import org.team2168.subsystems.IntakePosition; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class ConsolePrinter { // tread executor private java.util.Timer executor; private long period; public ConsolePrinter(long period) { this.period = period; } public void startThread() { this.executor = new java.util.Timer(); this.executor.schedule(new ConsolePrintTask(this), 0L, this.period); } public void print() { if(RobotMap.debug.getInt() == 1) { // System.out.println("Left Encoder: " + Drivetrain.getInstance().getLeftEncoderDistance()); // System.out.println("Right Encoder: " + Drivetrain.getInstance().getRightEncoderDistance()); // System.out.println("GYRO Angle: " + Drivetrain.getInstance().getGyroAngle()); // System.out.println(); // System.out.println("Winch Distance: " + CatapultWinch.getInstance().getWinchEncoderDistance()); // System.out.println("Winch Speed : " + CatapultWinch.getInstance().getWinchSpeed()); // System.out.println(); // System.out.println("Winch Limit :" + CatapultWinch.getInstance().isCatapultRetracted()); // System.out.println("Pot Voltage :" + CatapultWinch.getInstance().getWinchPotentiometerVoltage()); // System.out.println("Catapult Angle: " + CatapultWinch.getInstance().getCatapultAngle()); SmartDashboard.putNumber("Left Encoder Distance",Drivetrain.getInstance().getLeftEncoderDistance()); SmartDashboard.putNumber("Right Encoder Distance:",Drivetrain.getInstance().getRightEncoderDistance()); SmartDashboard.putNumber("GYRO Angle:", Drivetrain.getInstance().getGyroAngle()); SmartDashboard.putNumber("Winch Distance:",Winch.getInstance().getWinchEncoderDistance()); SmartDashboard.putNumber("Winch Speed:",Winch.getInstance().getWinchSpeed()); SmartDashboard.putBoolean("Winch Limit:", Winch.getInstance().isCatapultRetracted()); SmartDashboard.putBoolean("Intake Limit:", IntakePosition.getInstance().getIntakeLimitSwitch()); SmartDashboard.putNumber("Pot Voltage:", Winch.getInstance().getWinchPotentiometerVoltage()); SmartDashboard.putNumber("Catapult Angle", Winch.getInstance().getCatapultAngle()); SmartDashboard.putString("AutoName", Robot.getAutoName()); SmartDashboard.putNumber("Intake Ball presence", Winch.getInstance().getIntakeBallSensorVoltage()); SmartDashboard.putNumber("Winch ball presence", Winch.getInstance().getWinchBallSensorVoltage()); SmartDashboard.putBoolean("Camera Status", Vision.getInstance().isCameraConnected()); SmartDashboard.putBoolean("Bone Status", Vision.getInstance().isBoneConnected()); SmartDashboard.putBoolean("Processing Status", Vision.getInstance().isProcessingTreadRunning()); SmartDashboard.putBoolean("HotGoal Status", Vision.getInstance().isHotinView()); SmartDashboard.putBoolean("Truss Status", Tusks.getInstance().isTrussShot()); SmartDashboard.putBoolean("Wall Status", Tusks.getInstance().isShortRangeShot()); SmartDashboard.putBoolean("Far Status", Tusks.getInstance().isLongRangeShot()); // SmartDashboard.putBoolean("isAuto", DriverStation.getInstance().isAutonomous()); // SmartDashboard.putBoolean("isDisabled", DriverStation.getInstance().isDisabled()); // SmartDashboard.putBoolean("isEnabled", DriverStation.getInstance().isEnabled()); // SmartDashboard.putBoolean("isOperator", DriverStation.getInstance().isOperatorControl()); // SmartDashboard.putBoolean("matchStarted", Robot.matchStarted); } } private class ConsolePrintTask extends TimerTask { private ConsolePrinter console; private ConsolePrintTask(ConsolePrinter printer) { if (printer == null) { throw new NullPointerException("printer was null"); } this.console = printer; } /** * Called periodically in its own thread */ public void run() { console.print(); } } }
42.040816
108
0.753398
0d458b7782ee669c049e5c656b9f4a7c873a3519
1,245
// AddProductItem.java // Copyright © 2019 NextStep IT Training. All rights reserved. // package com.tc3.tc3service; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; public class AddProductItem { @Given("The client has a customer login") public void the_client_has_a_customer_login() { // Write code here that turns the phrase above into concrete actions throw new cucumber.api.PendingException(); } @When("The customer is logged in") public void the_customer_is_logged_in() { // Write code here that turns the phrase above into concrete actions throw new cucumber.api.PendingException(); } @When("The client application adds a product to the cart") public void the_client_application_adds_a_product_to_the_cart() { // Write code here that turns the phrase above into concrete actions throw new cucumber.api.PendingException(); } @Then("The client's shopping cart will contain the product") public void the_client_s_shopping_cart_will_contain_the_product() { // Write code here that turns the phrase above into concrete actions throw new cucumber.api.PendingException(); } }
33.648649
76
0.720482
eedd3ce13482acbde53213c76741e2760469c542
899
package com.prowidesoftware.swift.model.mx.dic; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for AssetClassSubProductType28Code. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="AssetClassSubProductType28Code"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="RNNG"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "AssetClassSubProductType28Code") @XmlEnum public enum AssetClassSubProductType28Code { /** * Commodity of type renewable energy. * */ RNNG; public String value() { return name(); } public static AssetClassSubProductType28Code fromValue(String v) { return valueOf(v); } }
21.404762
95
0.678532
d7b4750f7182ec93badb0f6e035af89b7de5d519
2,668
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.intercept; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; /** * <p>This is a {@link javax.inject.Provider} especially * made for &#064;ApplicationScoped beans.</p> * * <p>Since there is only one single contextual instance of an &#064;ApplicationScoped bean, * we can simply cache this instance inside our bean. We only need to reload this instance * if it is null. This happens at the first usage and after the MethodHandler got deserialized</p> * * <p>Also if the application uses the {@link javax.enterprise.context.spi.AlterableContext#destroy(javax.enterprise.context.spi.Contextual)} * method on any ApplicationScoped bean, then the standard NormalScopedBeanInterceptorHandler must be configured to prevent any caching. * Be careful as this might slow down your application!</p> */ public class ApplicationScopedBeanInterceptorHandler extends NormalScopedBeanInterceptorHandler { /**default serial id*/ private static final long serialVersionUID = 1L; /** * Cached bean instance. Please note that it is only allowed to * use this special proxy if you don't use OpenWebBeans in an EAR * scenario. In this case we must not cache &#064;ApplicationScoped * contextual instances because they could be injected into EJBs or other * shared instances which span over multiple web-apps. */ private transient Object cachedInstance; public ApplicationScopedBeanInterceptorHandler(BeanManager beanManager, Bean<?> bean) { super(beanManager, bean); } /** * {@inheritDoc} */ @Override protected Object getContextualInstance() { if (cachedInstance == null) { cachedInstance = super.getContextualInstance(); } return cachedInstance; } }
37.055556
141
0.730135
df403ceb78eba59c7fc5e5d4d6be010ba21490c2
1,817
package com.vaadin.tests.components.form; import com.vaadin.data.util.BeanItem; import com.vaadin.tests.components.TestBase; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Form; public class FormClearDatasourceRepaint extends TestBase { public static class MyBean { private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } } public static class MySecondBean extends MyBean { private String value2; public String getValue2() { return value2; } public void setValue2(String value) { value2 = value; } } @Override protected void setup() { final Form form = new Form(); form.setFooter(null); form.setItemDataSource(new BeanItem<MySecondBean>(new MySecondBean())); addComponent(form); addComponent(new Button("Clear datasource", new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { form.setItemDataSource(null); } })); addComponent(new Button("Change data source", new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { form.setItemDataSource(new BeanItem<MyBean>( new MyBean())); } })); } @Override protected String getDescription() { return "The form should adjust its size when clearing and setting data sources"; } @Override protected Integer getTicketNumber() { return 7626; } }
24.554054
88
0.577325
aff1b9e24df309b8d9ef30f2876500f26880e9d3
2,419
package org.filmticketorderingsystem.controller.user; import org.filmticketorderingsystem.bean.OrderBean; import org.filmticketorderingsystem.bean.OrderDetailBean; import org.filmticketorderingsystem.service.UserOrderingService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; /** * Created by 健勤 on 2016/7/5. */ @Controller @RequestMapping(value = "/user/ordering") public class UserOrderingController { @Resource(name = "userOrderingService") private UserOrderingService userOrderingService; public void setUserOrderingService(UserOrderingService userOrderingService) { this.userOrderingService = userOrderingService; } public UserOrderingService getUserOrderingService() { return userOrderingService; } /** * * @param filmSessionId * @param selectedSeat * @return */ @RequestMapping(value = "/handInOrder.do") @ResponseBody public OrderDetailBean handInOrder(@RequestParam Integer filmSessionId, @RequestParam String selectedSeat, HttpServletRequest request){ //获取当前登录用户id String id = (String)request.getSession().getAttribute("user_id"); String[] selectedSeats = selectedSeat.split(","); String[] result = userOrderingService.handInOrder(id, filmSessionId, selectedSeats); if(result != null){ OrderDetailBean orderDetailBean = new OrderDetailBean(); if(result[0] == "1"){ orderDetailBean.setOrderNum(result[1]); } //设置调用服务结果状态 orderDetailBean.setState(Integer.valueOf(result[0])); return orderDetailBean; } return null; } @RequestMapping(value = "/pay.do") @ResponseBody public OrderBean pay(@RequestParam String orderNum, HttpServletRequest request){ //获取当前登录用户id String id = (String)request.getSession().getAttribute("user_id"); int flag = userOrderingService.pay(id, orderNum); OrderBean orderBean = new OrderBean(); orderBean.setState(flag); return orderBean; } }
29.864198
92
0.686234
e9971e37ead1785c8a75ec467acca03410734703
155
& | ^ ~ //bitwise AND, OR, XOR, and NOT >> << //bitwise arithmetic shift >>> //bitwise logical shift + - * / = % //+ can be used for String concatenation)
31
53
0.6
90b8220afa357ec2aa76f28c833708a3b10f7a94
1,545
package com.demo.model; public class Person { private Integer id; private Long created; private String username; private String address; private String phone; private String remark; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Long getCreated() { return created; } public void setCreated(Long created) { this.created = created; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } @Override public String toString() { return "Person{" + "id=" + id + ", created=" + created + ", username='" + username + '\'' + ", address='" + address + '\'' + ", phone='" + phone + '\'' + ", remark='" + remark + '\'' + '}'; } }
20.6
66
0.520388
10fe3ac4480bd667ac71805c1b9c0e5532296bff
5,558
/* * Copyright 2017-2018 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.gchq.gaffer.hbasestore.coprocessor; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.CoprocessorEnvironment; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.coprocessor.ObserverContext; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.regionserver.InternalScanner; import org.apache.hadoop.hbase.regionserver.RegionScanner; import org.apache.hadoop.hbase.regionserver.ScanType; import org.apache.hadoop.hbase.regionserver.Store; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Before; import org.junit.Test; import uk.gov.gchq.gaffer.commonutil.StringUtil; import uk.gov.gchq.gaffer.commonutil.TestGroups; import uk.gov.gchq.gaffer.hbasestore.coprocessor.scanner.QueryScanner; import uk.gov.gchq.gaffer.hbasestore.coprocessor.scanner.StoreScanner; import uk.gov.gchq.gaffer.hbasestore.utils.HBaseStoreConstants; import uk.gov.gchq.gaffer.serialisation.implementation.StringSerialiser; import uk.gov.gchq.gaffer.store.schema.Schema; import uk.gov.gchq.gaffer.store.schema.SchemaEdgeDefinition; import uk.gov.gchq.gaffer.store.schema.SchemaEntityDefinition; import uk.gov.gchq.gaffer.store.schema.TypeDefinition; import uk.gov.gchq.koryphe.impl.binaryoperator.StringConcat; import java.io.IOException; import static org.junit.Assert.assertNotNull; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; public class GafferCoprocessorTest { private static final Schema SCHEMA = new Schema.Builder() .type("string", new TypeDefinition.Builder() .clazz(String.class) .aggregateFunction(new StringConcat()) .build()) .type("type", Boolean.class) .edge(TestGroups.EDGE, new SchemaEdgeDefinition.Builder() .source("string") .destination("string") .directed("true") .build()) .entity(TestGroups.ENTITY, new SchemaEntityDefinition.Builder() .vertex("string") .build()) .vertexSerialiser(new StringSerialiser()) .build(); private GafferCoprocessor coprocessor; @Before public void setup() throws IOException { coprocessor = new GafferCoprocessor(); final CoprocessorEnvironment coEnv = mock(CoprocessorEnvironment.class); final Configuration conf = mock(Configuration.class); given(coEnv.getConfiguration()).willReturn(conf); given(conf.get(HBaseStoreConstants.SCHEMA)).willReturn(StringUtil.escapeComma(Bytes.toString(SCHEMA.toCompactJson()))); coprocessor.start(coEnv); } @Test public void shouldDelegatePreFlushToStoreScanner() throws IOException { // Given final ObserverContext<RegionCoprocessorEnvironment> e = mock(ObserverContext.class); final Store store = mock(Store.class); final InternalScanner scanner = mock(InternalScanner.class); // When final StoreScanner storeScanner = (StoreScanner) coprocessor.preFlush(e, store, scanner); // Then assertNotNull(storeScanner); } @Test public void shouldDelegatePreCompactWithRequestToStoreScanner() throws IOException { // Given final ObserverContext<RegionCoprocessorEnvironment> e = mock(ObserverContext.class); final Store store = mock(Store.class); final InternalScanner scanner = mock(InternalScanner.class); final CompactionRequest request = mock(CompactionRequest.class); // When final StoreScanner storeScanner = (StoreScanner) coprocessor.preCompact(e, store, scanner, ScanType.COMPACT_DROP_DELETES, request); // Then assertNotNull(storeScanner); } @Test public void shouldDelegatePreCompactToStoreScanner() throws IOException { // Given final ObserverContext<RegionCoprocessorEnvironment> e = mock(ObserverContext.class); final Store store = mock(Store.class); final InternalScanner scanner = mock(InternalScanner.class); // When final StoreScanner storeScanner = (StoreScanner) coprocessor.preCompact(e, store, scanner, ScanType.COMPACT_DROP_DELETES); // Then assertNotNull(storeScanner); } @Test public void shouldDelegatePostScannerOpenToQueryScanner() throws IOException { // Given final ObserverContext<RegionCoprocessorEnvironment> e = mock(ObserverContext.class); final Scan scan = mock(Scan.class); final RegionScanner scanner = mock(RegionScanner.class); // When final QueryScanner queryScanner = (QueryScanner) coprocessor.postScannerOpen(e, scan, scanner); // Then assertNotNull(queryScanner); } }
40.275362
139
0.717344
02f88cb829a4c48c25e61b700c58fc5b779c7d1a
1,368
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 // See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.06.19 at 01:08:40 PM CEST // package com.wroom.rentingservice.soap.xsd; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for status. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="status"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="PENDING"/&gt; * &lt;enumeration value="RESERVED"/&gt; * &lt;enumeration value="CANCELED"/&gt; * &lt;enumeration value="PAID"/&gt; * &lt;enumeration value="PHYSICALLY_RESERVED"/&gt; * &lt;enumeration value="COMPLETED"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "status") @XmlEnum public enum Status { PENDING, RESERVED, CANCELED, PAID, PHYSICALLY_RESERVED, COMPLETED; public String value() { return name(); } public static Status fromValue(String v) { return valueOf(v); } }
25.333333
109
0.663012
dc9bcfc5dfc34bbd26f4cde72eacd57d39b8f639
1,195
package com.greek.shop.api.data; import java.io.Serializable; import java.util.List; /** * 数据分页使用的对象 * * @author Zhaofeng Zhou * @date 2021/11/17/017 17:46 */ public class Page<T> implements Serializable { int pageNum; int pageSize; int totalPage; List<T> data; public Page() { } public static <T> Page<T> of(int pageNum, int pageSize, int totalPage, List<T> data) { Page<T> result = new Page<>(); result.setTotalPage(totalPage); result.setPageNum(pageNum); result.setPageSize(pageSize); result.setData(data); return result; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } }
18.968254
90
0.595816
09d6d5fcc502438c9085cf385048b7a3d27d14c5
4,628
package com.jibug.frpc.boot.registar; import com.jibug.frpc.boot.registar.annotation.RpcReferenceFieldElement; import com.jibug.frpc.common.annotation.RpcReference; import com.jibug.frpc.common.cluster.registry.Registry; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import java.lang.reflect.Modifier; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author heyingcai */ public class RpcReferenceAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements InitializingBean, PriorityOrdered, ApplicationContextAware { public static final String BEAN_NAME = "rpcReferenceAnnotationBeanPostProcessor"; private int order = Ordered.LOWEST_PRECEDENCE - 2; private ApplicationContext applicationContext; private Registry registry; private final Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<>(256); @Override public int getOrder() { return order; } @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException { InjectionMetadata referenceMetadata = findReferenceMetadata(beanName, bean.getClass(), pvs); try { referenceMetadata.inject(bean, beanName, pvs); } catch (BeanCreationException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException(beanName, "Injection of @RpcReference dependencies failed", ex); } return pvs; } private InjectionMetadata findReferenceMetadata(String beanName, Class<?> clazz, PropertyValues pvs) { String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); InjectionMetadata injectionMetadata = injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(injectionMetadata, clazz)) { synchronized (this.injectionMetadataCache) { injectionMetadata = injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(injectionMetadata, clazz)) { if (injectionMetadata != null) { injectionMetadata.clear(pvs); } try { injectionMetadata = buildReferenceMetadata(clazz); this.injectionMetadataCache.put(cacheKey, injectionMetadata); } catch (NoClassDefFoundError err) { throw new IllegalStateException("Failed to introspect bean class [" + clazz.getName() + "] for reference metadata: could not find class that it depends on", err); } } } } return injectionMetadata; } private InjectionMetadata buildReferenceMetadata(final Class<?> clazz) { return new InjectionMetadata(clazz, findFieldReferenceMetadata(clazz)); } private List<InjectionMetadata.InjectedElement> findFieldReferenceMetadata(final Class<?> beanClass) { final List<InjectionMetadata.InjectedElement> elements = new LinkedList<>(); ReflectionUtils.doWithFields(beanClass, field -> { RpcReference rpcReference = field.getAnnotation(RpcReference.class); if (rpcReference != null) { if (Modifier.isStatic(field.getModifiers())) { return; } elements.add(new RpcReferenceFieldElement(field, rpcReference, registry)); } }); return elements; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void afterPropertiesSet() throws Exception { registry = (Registry) applicationContext.getBean(FrpcRegistrar.REGISTRY_CENTER); } }
41.693694
175
0.704624
67c073786a37f60fd584b602b953e9ea8f5c3bc0
491
import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner cin=new Scanner(System.in); int test = cin.nextInt(); for (int t = 0; t < test; t++) { int num = cin.nextInt(); int[] item = new int[num]; for (int i = 0; i < num; i++) { item[i] = cin.nextInt(); } Arrays.sort(item); int sum = 0; for (int i = num - 3; i >= 0; i-=3) sum+=item[i]; System.out.println(sum); } } }
19.64
57
0.521385
6039f6c838f63065dcf59499e00aa48892b69a65
921
package b.h.a.m.u; import android.content.ContentResolver; import android.content.res.AssetFileDescriptor; import android.net.Uri; import androidx.annotation.NonNull; import java.io.FileNotFoundException; public final class a extends l<AssetFileDescriptor> { public a(ContentResolver contentResolver, Uri uri) { super(contentResolver, uri); } @NonNull public Class<AssetFileDescriptor> a() { return AssetFileDescriptor.class; } public void c(Object obj) { ((AssetFileDescriptor) obj).close(); } public Object d(Uri uri, ContentResolver contentResolver) { AssetFileDescriptor openAssetFileDescriptor = contentResolver.openAssetFileDescriptor(uri, "r"); if (openAssetFileDescriptor != null) { return openAssetFileDescriptor; } throw new FileNotFoundException(b.e.a.a.a.k("FileDescriptor is null for: ", uri)); } }
29.709677
104
0.704669
cd158e10da345f5989dcac0a769ccdf45f307aaa
16,843
package top.naccl.gamebox.activity; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.header.BezierRadarHeader; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.RequestBody; import okhttp3.Response; import top.naccl.gamebox.R; import top.naccl.gamebox.api.ApiConfig; import top.naccl.gamebox.bean.Article; import top.naccl.gamebox.bean.Comment; import top.naccl.gamebox.bean.Image; import top.naccl.gamebox.bean.User; import top.naccl.gamebox.dialog.InputTextMsgDialog; import top.naccl.gamebox.service.ArticleService; import top.naccl.gamebox.service.ImageService; import top.naccl.gamebox.service.UserService; import top.naccl.gamebox.service.impl.ArticleServiceImpl; import top.naccl.gamebox.service.impl.ImageServiceImpl; import top.naccl.gamebox.service.impl.UserServiceImpl; import top.naccl.gamebox.util.Base64Utils; import top.naccl.gamebox.util.HtmlUtils; import top.naccl.gamebox.util.ImageUtils; import top.naccl.gamebox.util.OkHttpUtils; import top.naccl.gamebox.util.ToastUtils; public class ArticleActivity extends AppCompatActivity { private ArticleService articleService = new ArticleServiceImpl(this); private ImageService imageService = new ImageServiceImpl(this); private UserService userService = new UserServiceImpl(this); private Long articleId; private Article article; private User user; private Boolean articleFavorite = false; private Drawable add; private ImageView firstPicture_iv; private TextView title_tv; private TextView authorName_tv; private TextView articleDate_tv; private Button favorite1_btn; private Button favorite2_btn; private Button star_btn; private TextView views_tv; private TextView content_tv; private TextView comment_tv; private Toolbar toolbar; private InputTextMsgDialog inputTextMsgDialog; private String token; private List<Comment> commentList; private RecyclerView recyclerView; private ArticleActivity.MyRecyclerviewAdapter adapter; private int count; private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_article); toolbar = findViewById(R.id.toolbar_article); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(view -> finish()); add = this.getResources().getDrawable(R.drawable.icon_article_add); add.setBounds(0, 0, add.getMinimumWidth(), add.getMinimumHeight()); this.articleId = getIntent().getExtras().getLong("articleId", 0); if (articleId == 0) { ToastUtils.showToast(this, "异常错误"); } this.user = userService.getUser(); findView(); setOnClick(); setRefreshLayout(); SharedPreferences sharedPreferences = getSharedPreferences("jwt", Context.MODE_PRIVATE); this.token = sharedPreferences.getString("token", ""); setArticle(articleId); getCommentList(articleId); } class MyRecyclerviewAdapter extends RecyclerView.Adapter<ArticleActivity.MyRecyclerviewAdapter.MyRecyclerViewHolder> { private Context context; private List<Comment> commentList; public MyRecyclerviewAdapter(Context context, List<Comment> commentList) { this.context = context; this.commentList = commentList; } @Override public ArticleActivity.MyRecyclerviewAdapter.MyRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.comment_item, parent, false); return new ArticleActivity.MyRecyclerviewAdapter.MyRecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull final ArticleActivity.MyRecyclerviewAdapter.MyRecyclerViewHolder holder, final int position) { holder.content.setText(commentList.get(position).getContent()); holder.date.setText(simpleDateFormat.format(commentList.get(position).getCreateTime())); holder.username.setText(commentList.get(position).getUsername()); if (commentList.get(position).getAvatar() != null) { holder.avatar.setImageBitmap(Base64Utils.base64ToBitmap(commentList.get(position).getAvatar())); } } @Override public int getItemCount() { if (commentList != null) { return commentList.size(); } return 0; } private class MyRecyclerViewHolder extends RecyclerView.ViewHolder { private TextView username; private TextView date; private TextView content; private ImageView avatar; public MyRecyclerViewHolder(View itemView) { super(itemView); username = itemView.findViewById(R.id.textView_commentUsername); date = itemView.findViewById(R.id.textView_commentTime); content = itemView.findViewById(R.id.textView_commentContent); avatar = itemView.findViewById(R.id.roundImageView_commentAvatar); } } } private void init() { this.runOnUiThread(new Runnable() { public void run() { recyclerView = findViewById(R.id.commentList); //设置布局管理器 recyclerView.setLayoutManager(new LinearLayoutManager(ArticleActivity.this)); //设置RecycleView的Adapter adapter = new ArticleActivity.MyRecyclerviewAdapter(ArticleActivity.this, commentList); recyclerView.setAdapter(adapter); //设置分割线,非必须 recyclerView.addItemDecoration(new DividerItemDecoration(ArticleActivity.this, DividerItemDecoration.VERTICAL)); //设置item的增删动画,非必须 recyclerView.setItemAnimator(new DefaultItemAnimator()); comment_tv.setText("评论(已有" + count + "条评论)"); } }); } private void setRefreshLayout() { RefreshLayout refreshLayout = findViewById(R.id.refreshLayout); refreshLayout.setRefreshHeader(new BezierRadarHeader(this)); refreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(RefreshLayout refreshlayout) { ArticleActivity.this.article = null; if (articleService.deleteArticle(articleId)) { setArticle(articleId); } else { refreshlayout.finishRefresh(false);//传入false表示刷新失败 } refreshlayout.finishRefresh(1000/*,false*/);//传入false表示刷新失败 } }); } private void findView() { firstPicture_iv = findViewById(R.id.imageView_articleFirstPicture); title_tv = findViewById(R.id.textView_articleTitle); authorName_tv = findViewById(R.id.textView_authorName); articleDate_tv = findViewById(R.id.textView_articleDate); favorite1_btn = findViewById(R.id.button_favorite1); star_btn = findViewById(R.id.button_star); favorite2_btn = findViewById(R.id.button_favorite2); views_tv = findViewById(R.id.textView_views); content_tv = findViewById(R.id.textView_content); comment_tv = findViewById(R.id.textView_comment); } private void setOnClick() { star_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (user != null) { postStar(articleId); } else { ToastUtils.showToast(ArticleActivity.this, "请登录"); } } }); comment_tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (user != null) { comment_tv.setVisibility(View.INVISIBLE); inputTextMsgDialog.show(); } else { ToastUtils.showToast(ArticleActivity.this, "请登录"); } } }); inputTextMsgDialog = new InputTextMsgDialog(this, R.style.dialog_center, comment_tv); inputTextMsgDialog.setOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() { @Override public void onTextSend(String msg) { if (user != null) { postComment(msg); } else { ToastUtils.showToast(ArticleActivity.this, "请登录"); } } }); favorite1_btn.setOnClickListener(favorite); favorite2_btn.setOnClickListener(favorite); } View.OnClickListener favorite = new View.OnClickListener() { @Override public void onClick(View v) { if (user != null) { AlertDialog.Builder builder = new AlertDialog.Builder(ArticleActivity.this); builder.setTitle("收藏"); builder.setMessage(articleFavorite ? "确定要取消收藏吗?" : "确定要收藏此文章吗?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { postFavorite(articleId); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); builder.create().show(); } else { ToastUtils.showToast(ArticleActivity.this, "请登录"); } } }; private void setArticle(Long id) { Article article = articleService.getArticle(id); if (article == null) { getArticleFromServer(id); } else { this.article = article; article.setViews(article.getViews() + 1); setArticleInfo(); setArticleContent(); getFavorite(id); } } private void checkFavorite(JSONObject jsonResult) { if (user != null) { boolean favorite = jsonResult.getBoolean("favorite"); this.articleFavorite = favorite; this.runOnUiThread(new Runnable() { @Override public void run() { if (articleFavorite) { favorite1_btn.setCompoundDrawables(null, null, null, null); favorite1_btn.setText("已收藏"); favorite2_btn.setText("已收藏"); } else { favorite1_btn.setCompoundDrawables(add, null, null, null); favorite1_btn.setText("收藏"); favorite2_btn.setText("收藏"); } } }); } } private void setArticleInfo() { Image image = imageService.getImage("\'" + article.getFirstPicture() + "\'"); if (image != null) { final Bitmap bitmap = Base64Utils.base64ToBitmap(image.getBase64()); ArticleActivity.this.runOnUiThread(new Runnable() { public void run() { firstPicture_iv.setImageBitmap(bitmap); } }); } else { ImageUtils.setImageViewFromNetwork(firstPicture_iv, article.getFirstPicture(), this); } ArticleActivity.this.runOnUiThread(new Runnable() { public void run() { title_tv.setText(article.getTitle()); authorName_tv.setText(article.getAuthor()); articleDate_tv.setText(article.getDate()); star_btn.setText("赞 " + article.getStar()); views_tv.setText("阅读 " + article.getViews()); } }); } private void setArticleContent() { ArticleActivity.this.runOnUiThread(new Runnable() { public void run() { HtmlUtils.setTextFromHtml(ArticleActivity.this, content_tv, article.getContent()); } }); } private void getArticleFromServer(Long id) { OkHttpUtils.getRequest(ApiConfig.ARTICLE_URL + id, token, new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { final String result = response.body().string(); JSONObject jsonResult = JSON.parseObject(result); int code = jsonResult.getInteger("code"); String msg = jsonResult.getString("msg"); JSONObject data = jsonResult.getJSONObject("data"); if (code == 200) {//请求成功 final Article article = JSON.parseObject(data.getString("article"), Article.class); ArticleActivity.this.article = article; checkFavorite(data); setArticleInfo(); setArticleContent(); articleService.saveArticle(article); } else { ToastUtils.showToast(ArticleActivity.this, msg); } } @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { ToastUtils.showToast(ArticleActivity.this, "请求失败"); } }); } private void getCommentList(Long id) { OkHttpUtils.getRequest(ApiConfig.COMMENT_LIST_URL + id, new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { final String result = response.body().string(); JSONObject jsonResult = JSON.parseObject(result); int code = jsonResult.getInteger("code"); String msg = jsonResult.getString("msg"); String data = jsonResult.getString("data"); if (code == 200) {//请求成功 List<Comment> comment = JSON.parseArray(data, Comment.class); handleData(comment); } else { ToastUtils.showToast(ArticleActivity.this, msg); } } @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { ToastUtils.showToast(ArticleActivity.this, "请求失败"); } }); } private void handleData(List<Comment> comment) { if (comment.size() == 0) { return; } count = comment.size(); this.commentList = comment; ArticleActivity.this.runOnUiThread(new Runnable() { public void run() { init(); } }); } private void postStar(Long id) { OkHttpUtils.postRequest(ApiConfig.ARTICLE_STAR_URL + id, token, new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { final String result = response.body().string(); JSONObject jsonResult = JSON.parseObject(result); int code = jsonResult.getInteger("code"); String msg = jsonResult.getString("msg"); if (code == 200) {//点赞成功,更新点赞数 article.setStar(article.getStar() + 1); ArticleActivity.this.runOnUiThread(new Runnable() { public void run() { star_btn.setText("赞 " + article.getStar()); } }); articleService.updateStar(article); } else {//登录失效,请重新登录 ToastUtils.showToast(ArticleActivity.this, msg); } } @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { ToastUtils.showToast(ArticleActivity.this, "请求失败"); } }); } private void postFavorite(Long id) { OkHttpUtils.postRequest(ApiConfig.FAVORITE_URL + id, token, new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { final String result = response.body().string(); JSONObject jsonResult = JSON.parseObject(result); int code = jsonResult.getInteger("code"); String msg = jsonResult.getString("msg"); JSONObject data = jsonResult.getJSONObject("data"); ToastUtils.showToast(ArticleActivity.this, msg); if (code == 200) {//收藏/取消收藏成功 checkFavorite(data); } } @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { ToastUtils.showToast(ArticleActivity.this, "请求失败"); } }); } private void getFavorite(Long id) { OkHttpUtils.getRequest(ApiConfig.ARTICLE_UPDATE_VIEW_URL + id, token, new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { final String result = response.body().string(); JSONObject jsonResult = JSON.parseObject(result); int code = jsonResult.getInteger("code"); String msg = jsonResult.getString("msg"); JSONObject data = jsonResult.getJSONObject("data"); if (code == 200) {//请求成功 checkFavorite(data); articleService.updateViews(article); } else { ToastUtils.showToast(ArticleActivity.this, msg); } } @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { ToastUtils.showToast(ArticleActivity.this, "请求失败"); } }); } private void postComment(String content) { RequestBody requestBody = new FormBody.Builder() .add("content", content) .build(); OkHttpUtils.postRequest(ApiConfig.COMMENT_POST_URL + articleId, token, requestBody, new Callback() { @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { final String result = response.body().string(); JSONObject jsonResult = JSON.parseObject(result); int code = jsonResult.getInteger("code"); String msg = jsonResult.getString("msg"); if (code == 200) { getCommentList(articleId); } else {//登录失效,请重新登录 ToastUtils.showToast(ArticleActivity.this, msg); } } @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { ToastUtils.showToast(ArticleActivity.this, "请求失败"); } }); } }
33.220907
134
0.734074
4dce8a9431066a3b16c4bf4433461d89d09a275f
2,895
package edu.harvard.nlp.moarcoref; import edu.berkeley.nlp.coref.lang.Language; import edu.berkeley.nlp.futile.util.Logger; import edu.berkeley.nlp.futile.fig.basic.Option; import edu.berkeley.nlp.futile.fig.exec.Execution; import edu.berkeley.nlp.coref.ConjType; /* * A minimal version of BCS's Driver.java */ public class MiniDriver implements Runnable { @Option(gloss = "Which experiment to run?") public static Mode mode = Mode.SMALLER; @Option(gloss = "Language choice") public static Language lang = Language.ENGLISH; // DATA AND PATHS @Option(gloss = "Path to number/gender data") public static String numberGenderDataPath = "gender.data"; @Option(gloss = "Path to Stanford Coref's animate unigrams") public static String animacyPath = "animate.unigrams.txt"; @Option(gloss = "Path to Stanford Coref's inanimate unigrams") public static String inanimacyPath = "inanimate.unigrams.txt"; @Option(gloss = "Path to training set") public static String trainPath = "flat_train_2012"; @Option(gloss = "Training set size, -1 for all") public static int trainSize = -1; @Option(gloss = "Path to dev set") public static String devPath = "flat_dev_2012"; @Option(gloss = "Dev set size, -1 for all") public static int devSize = -1; @Option(gloss = "Path to test set") public static String testPath = "flat_test_2012"; @Option(gloss = "Test set size, -1 for all") public static int testSize = -1; @Option(gloss = "Suffix to use for documents") public static String docSuffix = "auto_conll"; @Option(gloss = "Randomize the order of train documents") public static boolean randomizeTrain = true; @Option(gloss = "True if we should train on the documents with gold annotations, false if we should use auto annotations") public static boolean trainOnGold = false; @Option(gloss = "Use gold mentions.") public static boolean useGoldMentions = false; @Option(gloss = "Features to use; default is SURFACE, write \"+FINAL\" for FINAL") public static String pairwiseFeats = ""; @Option(gloss = "Conjunction type") public static ConjType conjType = ConjType.CANONICAL; @Option(gloss = "Cutoff below which lexical features fire POS tags instead") public static int lexicalFeatCutoff = 20; @Option(gloss = "Cutoff below which bilexical features fire backoff indicator feature") public static int bilexicalFeatCutoff = 10; public static enum Mode { SMALLER; } public static void main(String[] args) { MiniDriver main = new MiniDriver(); Execution.run(args, main); // add .class here if that class should receive command-line args } public void run() { Logger.setFig(); if (mode.equals(Mode.SMALLER)) { FeatureExtractor.writeSeparatedFeatsAndOraclePredClustering(true); } else { FeatureExtractor.writeSeparatedFeatsAndOraclePredClustering(false); } } }
38.092105
124
0.724007
1042d8d678c35ed9f7244a52f82632ec27fa964a
1,096
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.transition; import android.animation.ObjectAnimator; import android.graphics.Path; import android.util.Property; // Referenced classes of package android.support.transition: // ObjectAnimatorUtilsImpl class ObjectAnimatorUtilsApi21 implements ObjectAnimatorUtilsImpl { ObjectAnimatorUtilsApi21() { // 0 0:aload_0 // 1 1:invokespecial #13 <Method void Object()> // 2 4:return } public ObjectAnimator ofPointF(Object obj, Property property, Path path) { return ObjectAnimator.ofObject(obj, property, ((android.animation.TypeConverter) (null)), path); // 0 0:aload_1 // 1 1:aload_2 // 2 2:aconst_null // 3 3:aload_3 // 4 4:invokestatic #22 <Method ObjectAnimator ObjectAnimator.ofObject(Object, Property, android.animation.TypeConverter, Path)> // 5 7:areturn } }
30.444444
139
0.67427
552f7974ae533f7b81a9d41b388010130f7ea109
88
package gauntlet.model; public enum ParseResult { success, failed, missing, error }
17.6
35
0.75
474855d4a3e45dec7e046eab070175fc3aa20578
3,457
package trikita.anvil.gridlayout.v7; import android.support.v7.widget.GridLayout; import android.util.Printer; import android.view.View; import java.lang.Boolean; import java.lang.Integer; import java.lang.Object; import java.lang.String; import java.lang.Void; import trikita.anvil.Anvil; import trikita.anvil.BaseDSL; /** * DSL for creating views and settings their attributes. * This file has been generated by {@code gradle generateGridLayoutv7DSL}. * It contains views and their setters from the library gridlayout-v7. * Please, don't edit it manually unless for debugging. */ public final class GridLayoutv7DSL implements Anvil.AttributeSetter { static { Anvil.registerAttributeSetter(new GridLayoutv7DSL()); } public static BaseDSL.ViewClassResult gridLayout() { return BaseDSL.v(GridLayout.class); } public static Void gridLayout(Anvil.Renderable r) { return BaseDSL.v(GridLayout.class, r); } public static Void alignmentMode(int arg) { return BaseDSL.attr("alignmentMode", arg); } public static Void columnCount(int arg) { return BaseDSL.attr("columnCount", arg); } public static Void columnOrderPreserved(boolean arg) { return BaseDSL.attr("columnOrderPreserved", arg); } public static Void orientation(int arg) { return BaseDSL.attr("orientation", arg); } public static Void printer(Printer arg) { return BaseDSL.attr("printer", arg); } public static Void rowCount(int arg) { return BaseDSL.attr("rowCount", arg); } public static Void rowOrderPreserved(boolean arg) { return BaseDSL.attr("rowOrderPreserved", arg); } public static Void useDefaultMargins(boolean arg) { return BaseDSL.attr("useDefaultMargins", arg); } public boolean set(View v, String name, final Object arg, final Object old) { switch (name) { case "alignmentMode": if (v instanceof GridLayout && arg instanceof Integer) { ((GridLayout) v).setAlignmentMode((int) arg); return true; } break; case "columnCount": if (v instanceof GridLayout && arg instanceof Integer) { ((GridLayout) v).setColumnCount((int) arg); return true; } break; case "columnOrderPreserved": if (v instanceof GridLayout && arg instanceof Boolean) { ((GridLayout) v).setColumnOrderPreserved((boolean) arg); return true; } break; case "orientation": if (v instanceof GridLayout && arg instanceof Integer) { ((GridLayout) v).setOrientation((int) arg); return true; } break; case "printer": if (v instanceof GridLayout && arg instanceof Printer) { ((GridLayout) v).setPrinter((Printer) arg); return true; } break; case "rowCount": if (v instanceof GridLayout && arg instanceof Integer) { ((GridLayout) v).setRowCount((int) arg); return true; } break; case "rowOrderPreserved": if (v instanceof GridLayout && arg instanceof Boolean) { ((GridLayout) v).setRowOrderPreserved((boolean) arg); return true; } break; case "useDefaultMargins": if (v instanceof GridLayout && arg instanceof Boolean) { ((GridLayout) v).setUseDefaultMargins((boolean) arg); return true; } break; } return false; } }
29.05042
79
0.648539
0ffef1fc3662168121880af7ee023ec1d9215b9f
456
package com.preemptive.moneybank.data.model; import java.util.Objects; public class Account { private final String accountNumber; private final double balance; public Account(String accountNumber, double balance) { this.accountNumber = accountNumber; this.balance = balance; } public String getAccountNumber() { return accountNumber; } public double getBalance() { return balance; } }
19
58
0.675439
62124caf4844012ba68fae9e78f09deba61d7548
2,461
/* * Matrix is the Two-Dimensional Model * Matrix is the combination of rows and columns,here the rows are n & columns are m * size = n x m * Transpose of the matrix is swapping of the rows and columns in the given matrix * Following code gives the output of the transpose of the matrix */ import java.util.Scanner; public class Matrix_Transpose { //Function for the transpose public static void transpose(int[][] a,int[][] b, int n , int m) { int i=0, j=0; for(i=0;i<m;i++) { for(j=0;j<n;j++) { //Each element of the transpose is assigned b[i][j]=a[j][i]; } } } public static void main(String[] args) { //To read inputs from the users Scanner is used Scanner sc = new Scanner(System.in); //To read number of rows required in the matrix as per user System.out.println("Enter number of rows:"); int n = sc.nextInt(); //To read number of columns required in the matrix as per user System.out.println("Enter number of columns:"); int m = sc.nextInt(); int i=0,j=0; //Assigning the memory to the 2-D array according to given matrix size int[][] a = new int[n][m]; int[][] b = new int[m][n]; System.out.println("Enter matrix elements:"); for(i=0;i<n;i++) { for(j=0;j<m;j++) { //Taking user inputs(elements) of the matrix a[i][j]=sc.nextInt(); } System.out.println(); } System.out.println("Given Matrix elements are:"); for(i=0;i<n;i++) { for(j=0;j<m;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } transpose(a, b , n , m); System.out.println("Transpose of Matrix:"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { //Printing the elements of the matrix after transpose calculation System.out.print(b[i][j]+" "); } System.out.println(); } } } /* Sample Input: Enter number of rows: 2 Enter number of columns: 3 Enter matrix elements: 10 20 30 40 50 60 Sample Output: Given Matrix elements are: 10 20 30 40 50 60 Transpose of Matrix: 10 40 20 50 30 60 Explanation: *Inputs, rows are 2 and columns are 3 * On the next line all the elements of the matrix have been entered 10 20 30 40 50 60 * Then, the code gives output for the transpose. Time Complexity : theta(nm) where, n = number of rows & m = number of columns Space Complexity : Transpose matrix requires extra memory space, theta(nm) */
22.372727
83
0.621292
4cb1d6912706b515e9751ca537062707c945b11e
323
package stubidp.utils.rest.common; public class ServiceNameDto { private String serviceName; // Needed for JAXB public ServiceNameDto() {} public ServiceNameDto(String serviceName) { this.serviceName = serviceName; } public String getServiceName() { return serviceName; } }
17.944444
47
0.671827
e0f150ec482cd59ef148037ab8c3842fa384c13a
24,811
package com.example.gungde.reminder_medicine.ActivityChats; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.esafirm.imagepicker.features.ImagePicker; import com.esafirm.imagepicker.features.ReturnMode; import com.esafirm.imagepicker.model.Image; import com.example.gungde.reminder_medicine.R; import com.example.gungde.reminder_medicine.adapter.MessageAdapter; import com.example.gungde.reminder_medicine.model.GetTimeAgo; import com.example.gungde.reminder_medicine.model.Messages; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ServerValue; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import de.hdodenhof.circleimageview.CircleImageView; import id.zelory.compressor.Compressor; public class ChatsRoom extends AppCompatActivity { private File imageFile = null; private Toolbar mtoolbar; private String mChatuser; private String musername; private DatabaseReference mRootDatabaseReference; private TextView mTitleView; private TextView mLastView; private CircleImageView mProfilImage; // private DatabaseReference firebaseUser; private DatabaseReference mUserRef; private RecyclerView mMessagesList; private FirebaseAuth mAuth; private String mCurrentUserId; private ImageButton mChatSendBtn; private final List<Messages> messagesList = new ArrayList<>(); private LinearLayoutManager mLinearLayout; private MessageAdapter mAdapter; private EditText mChatMessageView; private TextView time_text_layout; private SwipeRefreshLayout mRefreshLayout; private static final int TOTAL_ITEMS_TO_LOAD = 10; private int mCurrentPage = 1; private static final int GALLERY_PICK = 1; private static final int MY_CAMERA_REQUEST_CODE = 100; static final int REQUEST_IMAGE_CAPTURE = 1; // Storage Firebase private StorageReference mImageStorage; //New Solution private int itemPos = 0; private String mLastKey = ""; private String mPrevKey = ""; private ImageButton mChatAddBtn; //VARIABEL UNTUK TAKE PICTURE private Uri imageUri; private Uri newsImageUri; private File photofile = null; private File thumb_file; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chats_room); //Navigation Toolbar mtoolbar = (Toolbar) findViewById(R.id.tampungchat_app_bar); setSupportActionBar(mtoolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mtoolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); /* ==========Custom action bar item==========*/ ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowCustomEnabled(true); LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View actionbar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null); actionBar.setCustomView(actionbar_view); /* =================Get informasi user dari friend fragment ==========*/ mChatuser = getIntent().getStringExtra("user_id"); musername = getIntent().getStringExtra("user_name"); /* =======================Inisialisasi Layout =============*/ mTitleView = (TextView) findViewById(R.id.custom_bar_title); mLastView = (TextView) findViewById(R.id.custom_bar_seen); mProfilImage = (CircleImageView) findViewById(R.id.custom_bar_image); mChatMessageView = (EditText) findViewById(R.id.chat_message_view); mChatSendBtn = (ImageButton) findViewById(R.id.chat_send_btn); mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_btn); time_text_layout = findViewById(R.id.time_text_layout); /*==================FIREBASE Insisualisasi =================*/ //inisialisasi root database refference mRootDatabaseReference = FirebaseDatabase.getInstance().getReference(); //inisilisasi get currrent user (User yang login) mAuth = FirebaseAuth.getInstance(); mCurrentUserId = mAuth.getCurrentUser().getUid(); /*===========Adapter FOR TAMPILIN PESAN ============*/ mAdapter = new MessageAdapter(messagesList); mMessagesList = (RecyclerView) findViewById(R.id.messages_list); mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout); mLinearLayout = new LinearLayoutManager(this); mMessagesList.setHasFixedSize(true); mMessagesList.setLayoutManager(mLinearLayout); mMessagesList.setAdapter(mAdapter); mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid()); //------- IMAGE STORAGE --------- mImageStorage = FirebaseStorage.getInstance().getReference(); mRootDatabaseReference.child("Chat").child(mCurrentUserId).child(mChatuser).child("seen").setValue(true); /* ==========CallLog FUNCTION FirebaseStorage =========*/ loadMessages(); mTitleView.setText(musername); /* ====== MENDAPATKAN INFORMASI DARI DATAABASE TENTANG USER YANG DI chAT ====*/ mRootDatabaseReference.child("Users").child(mChatuser).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String online = dataSnapshot.child("online").getValue().toString(); //jika dia online if (online.equals("true")) { mLastView.setText("Online"); } else { //mendapatkan waktu kapan terakhir dia online GetTimeAgo getTimeAgo = new GetTimeAgo(); long lastTime = Long.parseLong(online); String lastSeenTime = getTimeAgo.getTimeAgo(lastTime, getApplicationContext()); //settext kapan terakhir dia online mLastView.setText(lastSeenTime); } } @Override public void onCancelled(DatabaseError databaseError) { } }); /* ==========APAKAH PESAN SUDAH DI BACA (Unread) =========*/ mRootDatabaseReference.child("Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (!dataSnapshot.hasChild(mChatuser)) { Map chatAddMap = new HashMap(); chatAddMap.put("seen", false); chatAddMap.put("timestamp", ServerValue.TIMESTAMP); Map chatUserMap = new HashMap(); chatUserMap.put("Chat/" + mCurrentUserId + "/" + mChatuser, chatAddMap); chatUserMap.put("Chat/" + mChatuser + "/" + mCurrentUserId, chatAddMap); mRootDatabaseReference.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { if (databaseError != null) { Log.d("CHAT_LOG", databaseError.getMessage().toString()); } } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); /* ========== Action Kirim pesan =========*/ mChatSendBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sendMessage(); // loadMessages(); } }); /* ==========Action Intent Get Image Form Galery (Tidak DI PAKAI)=========*/ //TAKE PICTURE FROM GALERY PICK /* mChatAddBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent galleryIntent = new Intent(); galleryIntent.setType("image/*"); galleryIntent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK); } });*/ /* ==========Action Intent Pick Image Form CAMERA =========*/ mChatAddBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { galleryIntent(REQUEST_IMAGE_CAPTURE); //CHEK PERMISSION ACCES CAMERA // if (ContextCompat.checkSelfPermission(ChatsRoom.this, Manifest.permission.CAMERA) // == PackageManager.PERMISSION_DENIED) { // // //Meminta Akses Camera // ActivityCompat.requestPermissions(ChatsRoom.this, new String[]{Manifest.permission.CAMERA}, REQUEST_IMAGE_CAPTURE); // // } // //CHEK Permission MENYIMPAN FILE (Storage) // else if (ContextCompat.checkSelfPermission(ChatsRoom.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) // == PackageManager.PERMISSION_DENIED) { // // //MEMINTA ACCES // ActivityCompat.requestPermissions(ChatsRoom.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_IMAGE_CAPTURE); // } else { // // // /* ==========Jika AKses diberikan, maka penggil Intent Camera =========*/ // Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // // //Generate Name // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); // photofile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), timeStamp + "anu.jpg"); // // //Chek photofile tidak null; // if (photofile != null) { // // //Mendapatkan Alamat URi dari foto File // imageUri = Uri.fromFile(photofile); // // //Mengirim ALamat Uri // takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // // //Memanggil Activity Onresult dari Camera Intent // startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); // // // } else { // Toast.makeText(ChatsRoom.this, "PHOTO FILE NULL", Toast.LENGTH_LONG).show(); // } // // } // } } }); /* ==========Method Refresh recycleview =========*/ mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mCurrentPage++; itemPos = 0; loadMoreMessages(); } }); } private void galleryIntent(int requestCode) { ImagePicker.create(this) .returnMode(ReturnMode.ALL) // set whether pick and / or camera action should return immediate result or not. .folderMode(true) // folder mode (false by default) .toolbarFolderTitle("Folder") // folder selection title .toolbarImageTitle("Tap to select") // image selection title .toolbarArrowColor(Color.WHITE) // Toolbar 'up' arrow color .single() // single mode .showCamera(true) // show camera or not (true by default) .imageDirectory("Camera") // directory name for captured image ("Camera" folder by default) .enableLog(false) // disabling log .start(requestCode); // start image picker activity with request code } //Onactivity Result dari Intent Camera && Galery or Anyting (Tergantung request code) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //Jika Request nya ImageCapture(Camera) dan user menekan OK (Selesai mengambil foto) if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Image image = ImagePicker.getFirstImageOrNull(data); imageFile = new File(image.getPath()); imageUri = Uri.fromFile(imageFile); //jika image Uri tidak kosong if (imageUri != null) { try { //Kompress File asal kedalam File Baru dengan ukuran lebih ringan File newsfile = new Compressor(ChatsRoom.this) .compressToFile(imageFile); //Mendapatkan Uri file baru setelah di kompress newsImageUri = Uri.fromFile(newsfile); } catch (IOException e) { e.printStackTrace(); } //Path penyimpanan message disimpan untuk current user final String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatuser; //Path penyimpanan message untuk other user final String chat_user_ref = "messages/" + mChatuser + "/" + mCurrentUserId; //mengenerate CHATS Id DatabaseReference user_message_push = mRootDatabaseReference.child("messages") .child(mCurrentUserId).child(mChatuser).push(); //Mendapatkan hasil generate CHATs ID final String push_id = user_message_push.getKey(); //Path penyimpanan FILE Pada FIrebas Storage StorageReference filepath = mImageStorage.child("message_images").child(push_id + ".jpg"); /* ========== Method upload file ke Firebase Storage =========*/ filepath.putFile(newsImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() { @Override public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) { if (task.isSuccessful()) { //menthod mendapatkan URi download gambar String download_url = task.getResult().getDownloadUrl().toString(); //simapn hasil kedatabase Map messageMap = new HashMap(); messageMap.put("message", download_url); messageMap.put("seen", false); messageMap.put("type", "image"); messageMap.put("time", ServerValue.TIMESTAMP); messageMap.put("from", mCurrentUserId); Map messageUserMap = new HashMap(); //struktur database simpan message untku current user messageUserMap.put(current_user_ref + "/" + push_id, messageMap); //struktur database simpan message untku current user messageUserMap.put(chat_user_ref + "/" + push_id, messageMap); mChatMessageView.setText(""); mRootDatabaseReference.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { if (databaseError != null) { Log.d("CHAT_LOG", databaseError.getMessage().toString()); } } }); } } }); } else { Toast.makeText(ChatsRoom.this, "URI IS NULL", Toast.LENGTH_LONG).show(); } } } /* ========== Method laod message on Refresh swipe =========*/ private void loadMoreMessages() { DatabaseReference messageRef = mRootDatabaseReference.child("messages").child(mCurrentUserId).child(mChatuser); messageRef.keepSynced(true); Query messageQuery = messageRef.orderByKey().endAt(mLastKey).limitToLast(10); messageQuery.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { Messages message = dataSnapshot.getValue(Messages.class); String messageKey = dataSnapshot.getKey(); if (!mPrevKey.equals(messageKey)) { messagesList.add(itemPos++, message); } else { mPrevKey = mLastKey; } if (itemPos == 1) { mLastKey = messageKey; } Log.d("TOTALKEYS", "Last Key : " + mLastKey + " | Prev Key : " + mPrevKey + " | Message Key : " + messageKey); mAdapter.notifyDataSetChanged(); mRefreshLayout.setRefreshing(false); mLinearLayout.scrollToPositionWithOffset(itemPos, 0); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); } /* ========== Method Load Message Ketika BUkan Swipe refresh =========*/ private void loadMessages() { DatabaseReference messageRef = mRootDatabaseReference.child("messages").child(mCurrentUserId).child(mChatuser); messageRef.keepSynced(true); Query messageQuery = messageRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD); messageQuery.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { Messages message = dataSnapshot.getValue(Messages.class); itemPos++; if (itemPos == 1) { String messageKey = dataSnapshot.getKey(); mLastKey = messageKey; mPrevKey = messageKey; } messagesList.add(message); mAdapter.notifyDataSetChanged(); // setTime_text_layout(Long.parseLong(message.getMessage())); mMessagesList.scrollToPosition(messagesList.size() - 1); mRefreshLayout.setRefreshing(false); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void onStart() { super.onStart(); //Set status online FirebaseUser currentUser = mAuth.getCurrentUser(); mUserRef.child("online").setValue("true"); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { //Online is Over super.onDestroy(); mUserRef.child("online").setValue(ServerValue.TIMESTAMP); } /* ========== Method Mengirim pesan (Ketika Send Button Click) =========*/ private void sendMessage() { String message = mChatMessageView.getText().toString(); if (!TextUtils.isEmpty(message)) { //Path simpan message untuk current user (User yang login) String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatuser; //path simpan message untuk other user String chat_user_ref = "messages/" + mChatuser + "/" + mCurrentUserId; //generate Message ID DatabaseReference user_message_push = mRootDatabaseReference.child("messages").child(mCurrentUserId).child(mChatuser).push(); //Get Message ID String push_id = user_message_push.getKey(); //Map untuk menampung message Map messageMap = new HashMap(); messageMap.put("message", message); messageMap.put("seen", false); messageMap.put("type", "text"); messageMap.put("time", ServerValue.TIMESTAMP); messageMap.put("from", mCurrentUserId); //Map Untuk menyimpan Message dalam database secara sekalian Map messageUserMap = new HashMap(); messageUserMap.put(current_user_ref + "/" + push_id, messageMap); //Path simpan untuk current user messageUserMap.put(chat_user_ref + "/" + push_id, messageMap); //path simpan untk other user mChatMessageView.setText(" "); //Set kapan pessan dibaca mRootDatabaseReference.child("Chat").child(mCurrentUserId).child(mChatuser).child("seen").setValue(true); mRootDatabaseReference.child("Chat").child(mCurrentUserId).child(mChatuser).child("timestamp").setValue(ServerValue.TIMESTAMP); mRootDatabaseReference.child("Chat").child(mChatuser).child(mCurrentUserId).child("seen").setValue(false); mRootDatabaseReference.child("Chat").child(mChatuser).child(mCurrentUserId).child("timestamp").setValue(ServerValue.TIMESTAMP); mRootDatabaseReference.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { if (databaseError != null) { Log.d("CHAT_LOG", databaseError.getMessage().toString()); } } }); } } /* ========== Method SetTime Textlayout =========*/ public void setTime_text_layout(final long timesend) { time_text_layout.setText(String.valueOf(timesend)); } }
37.649469
153
0.602878
9ccaaef31e846bc4ad37c89345506b301d3351ba
3,272
package net.starwix; import java.awt.AWTException; import java.awt.Graphics; import java.awt.Point; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; /** * @author starwix */ public class ImageArray { private int[][] data; private int type; private long[][] hashData; private long[][][] integralData; public ImageArray(BufferedImage image, int type) { int w = image.getWidth(); int h = image.getHeight(); if (image.getType() != type) { BufferedImage temp = new BufferedImage(w, h, type); Graphics g = temp.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); image = temp; } this.type = type; DataBuffer t = image.getRaster().getDataBuffer(); // work fast data = new int[h][w]; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { data[y][x] = t.getElem(y * w + x); } } } public ImageArray(BufferedImage image) throws AWTException { this(image, image.getType()); } public int[][] getData() { return data; } public int getType() { return type; } public int getHeight() { return data.length; } public int getWidth() { return data[0].length; } public Point findByHash(ImageArray image) { return null; } public Point findByIntegral(ImageArray image, int diff, int part) { int ny = getHeight() - image.getHeight(); int nx = getWidth() - image.getWidth(); Point p = null; long minDifference = Long.MAX_VALUE; for (int y = 0; y < ny; y++) { for (int x = 0; x < nx; x++) { long t = findDifference(x, y, image, 0, 0, image.getWidth(), image.getHeight(), part); if (t < minDifference) { minDifference = t; p = new Point(x, y); } } } return minDifference > diff ? null : p; } private long findDifference(int x, int y, ImageArray image, int ix, int iy, int w, int h, int part) { if (--part == 0) { long sum = 0; for (int i = 0; i < 4; i++) { sum += Math.abs(getIntegral(i, x, y, x + w - 1, y + h - 1) - image.getIntegral(i, ix, iy, ix + w - 1, iy + h - 1)); } return sum; } if (h > w) { int nh = h / 2; return findDifference(x, y, image, ix, iy, w, nh, part) + findDifference(x, y + nh, image, ix, iy + nh, w, h - nh, part); } else { int nw = w / 2; return findDifference(x, y, image, ix, iy, nw, h, part) + findDifference(x + nw, y, image, ix + nw, iy, w - nw, h, part); } } private void findIntegral() { integralData = new long[4][getHeight()][getWidth()]; for (int y = 0; y < getHeight(); y++) { for (int x = 0; x < getWidth(); x++) { int t = data[y][x]; for (int i = 0; i < 4; i++) { integralData[i][y][x] = getIntegral(i, x, y - 1) + getIntegral(i, 0, y, x - 1, y) + (t & 0xFF); t >>= 8; } } } } private long getIntegral(int i, int ex, int ey) { if (integralData == null) { findIntegral(); } if (ex < 0 || ey < 0) { return 0; } return integralData[i][ey][ex]; } private long getIntegral(int i, int bx, int by, int ex, int ey) { if (integralData == null) { findIntegral(); } if (bx > ex || by > ey || bx < 0 || by < 0) { return 0; } return integralData[i][ey][ex] - getIntegral(i, ex, by - 1) - getIntegral(i, bx - 1, ey) + getIntegral(i, bx - 1, by - 1); } }
23.539568
124
0.57335
0a58638563de713f640c19012fdb366941af5a27
1,555
package io.github.oliviercailloux.y2018.jbiblio.j_biblio.responsibleentity; import java.util.Objects; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "publisher") @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) public class ResponsibleEntity { private Person person; private CorporateBody corporateBody; public ResponsibleEntity(){ } public ResponsibleEntity(Person person) throws NullPointerException { this.person = Objects.requireNonNull(person); } public ResponsibleEntity(CorporateBody corporateBody) throws NullPointerException { this.corporateBody = Objects.requireNonNull(corporateBody); } /** * asPerson throw a IllegalStateException if corporatbody is different of null */ public Person asPerson() throws IllegalStateException { if (corporateBody != null) { throw new IllegalStateException(); } return this.person; } public CorporateBody asCorporateBody() throws IllegalStateException { if (person != null) { throw new IllegalStateException(); } return this.corporateBody; } @XmlElement(name="publisher", type= Person.class) public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public CorporateBody getCorporateBody() { return corporateBody; } public void setCorporateBody(CorporateBody corporateBody) { this.corporateBody = corporateBody; } }
21.901408
84
0.773633
b5839f94905ff87cdc43aea13c3a75ee5ba1fc86
391
package com.yarin.android.MusicPlayer; import android.app.Application; public class MusicPlayerApp extends Application { private MusicInfoController mMusicInfoController = null; public void onCreate() { super.onCreate(); mMusicInfoController = MusicInfoController.getInstance(this); } public MusicInfoController getMusicInfoController() { return mMusicInfoController; } }
17.772727
63
0.795396
2971fe6e48998bb6d48605287f6c106508dec3a1
6,162
package com.daxiang.taojin.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.daxiang.taojin.R; public class HttpTestActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_http_test); initViews(); } private void initViews() { findViewById(R.id.httpClientGet).setOnClickListener(this); findViewById(R.id.httpClientPost).setOnClickListener(this); findViewById(R.id.okGet).setOnClickListener(this); findViewById(R.id.okHttps).setOnClickListener(this); findViewById(R.id.okHttpPostString).setOnClickListener(this); findViewById(R.id.okPostStream).setOnClickListener(this); findViewById(R.id.okPostFile).setOnClickListener(this); findViewById(R.id.okPostForm).setOnClickListener(this); findViewById(R.id.okPostMultipart).setOnClickListener(this); findViewById(R.id.okGetParseGson).setOnClickListener(this); findViewById(R.id.testCache).setOnClickListener(this); findViewById(R.id.testTimeout).setOnClickListener(this); findViewById(R.id.testSingleCall).setOnClickListener(this); } @Override public void onClick(View v) { Intent intent; switch (v.getId()) { case R.id.httpClientGet: intent = new Intent(this, HttpClientRequestActivity.class); intent.putExtra("url", "http://api.91touba.com/api/search/report?pageSize=5&keyword=20"); intent.putExtra("method", "GET"); startActivity(intent); break; case R.id.httpClientPost: intent = new Intent(this, HttpClientRequestActivity.class); intent.putExtra("url", "http://en.wikipedia.org/w/index.php"); intent.putExtra("method", "POST"); startActivity(intent); break; case R.id.okGet: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "http://api.91touba.com/api/search/report?pageSize=5&keyword=20"); intent.putExtra("method", "GET"); startActivity(intent); break; case R.id.okHttps: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "https://192.168.1.22:8443/HttpsServer/loginHttpServlet"); intent.putExtra("method", OkHttpRequestActivity.HTTPS_POST); startActivity(intent); break; case R.id.okHttpPostString: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "https://api.github.com/markdown/raw"); intent.putExtra("method", OkHttpRequestActivity.POST_STRING); startActivity(intent); break; case R.id.okPostStream: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "https://api.github.com/markdown/raw"); intent.putExtra("method", OkHttpRequestActivity.POST_STREAM); startActivity(intent); break; case R.id.okPostFile: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "https://api.github.com/markdown/raw"); intent.putExtra("method", OkHttpRequestActivity.POST_FILE); startActivity(intent); break; case R.id.okPostForm: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "https://www.baidu.com/s"); intent.putExtra("method", OkHttpRequestActivity.POST_FORM); startActivity(intent); break; case R.id.okPostMultipart: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "https://api.imgur.com/3/image"); intent.putExtra("method", OkHttpRequestActivity.POST_MultiPart); startActivity(intent); break; case R.id.okGetParseGson: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "https://api.github.com/gists/c2a7c39532239ff261be"); intent.putExtra("method", OkHttpRequestActivity.Parse_Gson); startActivity(intent); break; case R.id.testCache: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "http://publicobject.com/helloworld.txt"); intent.putExtra("method", OkHttpRequestActivity.Test_Cache); startActivity(intent); break; case R.id.testTimeout: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "http://httpbin.org/delay/12"); intent.putExtra("method", OkHttpRequestActivity.Test_Timeout); startActivity(intent); break; case R.id.testSingleCall: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "http://httpbin.org/delay/12"); intent.putExtra("method", OkHttpRequestActivity.Test_Single_Call); startActivity(intent); break; case R.id.downloadFile: intent = new Intent(this, OkHttpRequestActivity.class); intent.putExtra("url", "http://publicobject.com/helloworld.txt"); intent.putExtra("method", OkHttpRequestActivity.DOWNLOAD_FILE); startActivity(intent); break; } } }
42.205479
90
0.590068
acd76e7cfefe0d3a01b3475a4c83dcfe74a66854
91
package network.warzone.tgm.match; public enum MatchStatus { PRE, MID, POST }
11.375
34
0.659341
c1ba0094fbc7582f03948d51471a965f895b5a56
1,132
package com.sequenceiq.redbeams.converter; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import com.sequenceiq.cloudbreak.auth.crn.Crn; import com.sequenceiq.cloudbreak.auth.crn.CrnParseException; import com.sequenceiq.redbeams.TestData; public class CrnConverterTest { private static final String RESOURCE_NAME = "resourceName"; private CrnConverter underTest; private Crn validCrn; @Before public void setup() { underTest = new CrnConverter(); validCrn = TestData.getTestCrn("database", "name"); } @Test public void testConvertToDbField() { String dbField = underTest.convertToDatabaseColumn(validCrn); assertEquals(validCrn.toString(), dbField); } @Test public void testConvertToEntityAttribute() { Crn dbCrn = underTest.convertToEntityAttribute(validCrn.toString()); assertEquals(validCrn, dbCrn); } @Test(expected = CrnParseException.class) public void testConvertToEntityAttributeInvalidCrnString() { underTest.convertToEntityAttribute("nope"); } }
24.608696
76
0.720848
293b21d76e4d82dc0fdf810c521bddd90a60efdb
444
/** * @IObjectRefHandle.java * @author sodaChen E-mail:asframe@qq.com * @version 1.0 * <br>Copyright (C) * <br>This program is protected by copyright laws. * <br>Program Name:KeepArea * <br>Date:2020/2/22 */ package com.asframe.ref; /** * Object反射属性的操作 * @author sodaChen * @version 1.0 * <br>Date:2020/2/22 */ public interface IObjectRefHandle<T> { /** * 对属性进行操作 * @param value */ void handle(T value); }
17.076923
51
0.628378
7dfbacd42d18aeed69ef8707ae7fc86e1456d93d
1,128
package org.kobjects.fluentdom.api; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; public class ElementBuilder<N, E extends N, T extends N, B extends ElementBuilder<N, E, T, ?>> { private NodeFactory<N, E, T> nodeFactory; private final String name; private final LinkedHashMap<String, Object> attributes = new LinkedHashMap<>(); ElementBuilder(NodeFactory<N, E, T> factory, String name) { this.nodeFactory = factory; this.name = name; } public E withText(String content) { return nodeFactory.createElement(name, attributes, Collections.singletonList(nodeFactory.createTextNode(content))); } @SuppressWarnings("unchecked") public B id(String id) { attributes.put("id", id); return (B) this; } @SuppressWarnings("unchecked") public E withChildren(N... children) { return withChildren(Arrays.asList(children)); } public E withChildren(List<N> children) { return nodeFactory.createElement(name, attributes, children); } public E empty() { return nodeFactory.createElement(name, attributes, Collections.emptyList()); } }
27.512195
118
0.739362
3042a474eab3e089fd568d0b2cb0cf3250ee9aee
17,623
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.model; import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.ESBDEBUGGER_EVENT_TOPIC; import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.ESB_DEBUGGER_EVENT_BROKER_DATA_NAME; import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.ESB_DEBUG_TARGET_EVENT_TOPIC; import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.SUSPEND_POINT_MODEL_ID; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarkerDelta; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.IDebugTarget; import org.eclipse.debug.core.model.IMemoryBlock; import org.eclipse.debug.core.model.IProcess; import org.eclipse.e4.core.services.events.IEventBroker; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.WorkbenchException; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import org.wso2.developerstudio.eclipse.carbonserver44microei.register.product.servers.MicroIntegratorInstance; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.Activator; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.debugpoint.impl.ESBDebugPoint; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.exception.DebugPointMarkerNotFoundException; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.exception.ESBDebuggerException; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.internal.communication.IESBDebuggerInternalEvent; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.internal.communication.events.DebuggerStartedEvent; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.internal.communication.events.MediationFlowCompleteEvent; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.internal.communication.events.PropertyRecievedEvent; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.internal.communication.events.ResumedEvent; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.internal.communication.events.SuspendedEvent; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.internal.communication.events.TerminatedEvent; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.internal.communication.requests.DebugPointRequest; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.internal.communication.requests.FetchVariablesRequest; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.messages.response.PropertyRespondMessage; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.messages.util.AbstractESBDebugPointMessage; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.suspendpoint.ESBSuspendPoint; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.DebugPointEventAction; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerResumeType; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerUtil; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBPropertyScopeType; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.Messages; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.OpenEditorUtil; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; import com.google.gson.JsonObject; /** * This is the root of the ESB Mediation Debugger debug element hierarchy. It * supports terminate, suspend , resume, breakpoint, skip points * */ public class ESBDebugTarget extends ESBDebugElement implements IDebugTarget, EventHandler { private IEventBroker debugTargetEventBroker; private final ESBDebugProcess esbDebugProcess; private final List<ESBDebugThread> esbDebugThreads = new ArrayList<ESBDebugThread>(); private final ILaunch esbDebugerLaunch; private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID); private static final String ESB_GRAPHICAL_PERSPECTIVE_ID = "org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.perspective"; public ESBDebugTarget(final ILaunch launch) { super(null); debugTargetEventBroker = (IEventBroker) PlatformUI.getWorkbench().getService(IEventBroker.class); debugTargetEventBroker.subscribe(ESBDEBUGGER_EVENT_TOPIC, this); esbDebugerLaunch = launch; fireCreationEvent(); esbDebugProcess = new ESBDebugProcess(this); esbDebugProcess.fireCreationEvent(); } @Override public void handleEvent(Event eventFromBroker) { if (!isDisconnected()) { Object eventObject = eventFromBroker.getProperty(ESB_DEBUGGER_EVENT_BROKER_DATA_NAME); if (eventObject instanceof IESBDebuggerInternalEvent) { IESBDebuggerInternalEvent event = (IESBDebuggerInternalEvent) eventObject; if (event instanceof DebuggerStartedEvent) { ESBDebugThread thread = new ESBDebugThread(this); esbDebugThreads.add(thread); thread.fireCreationEvent(); ESBStackFrame stackFrame = new ESBStackFrame(this, thread); thread.addStackFrame(stackFrame); stackFrame.fireCreationEvent(); DebugPlugin.getDefault().getBreakpointManager().addBreakpointListener(this); resume(); } else if (event instanceof SuspendedEvent) { // this get called when ESB came to a breakpoint setState(ESBDebuggerState.SUSPENDED); fireSuspendEvent(0); getThreads()[0].fireSuspendEvent(DebugEvent.BREAKPOINT); try { showDiagram((SuspendedEvent) event); } catch (ESBDebuggerException | CoreException e) { log.error("Error while trying to show diagram : " //$NON-NLS-1$ + e.getMessage(), e); } fireModelEvent(new FetchVariablesRequest()); } else if (event instanceof ResumedEvent) { if (((ResumedEvent) event).getType() == ESBDebuggerResumeType.CONTINUE) { setState(ESBDebuggerState.RESUMED); getThreads()[0].fireResumeEvent(DebugEvent.UNSPECIFIED); } } else if (event instanceof PropertyRecievedEvent) { try { ESBStackFrame stackFrame = getThreads()[0].getTopStackFrame(); PropertyRespondMessage propertyMessage = ((PropertyRecievedEvent) event).getVariables(); stackFrame.setVariables(propertyMessage); } catch (Exception e) { log.error("Error while seting variable values", e); //$NON-NLS-1$ } } else if (event instanceof TerminatedEvent) { // Clear all the stack frames in the debug threads and unsubscribe for (ESBDebugThread debuggerThread : esbDebugThreads) { IEventBroker propertyChangeCommandEB = (IEventBroker) PlatformUI.getWorkbench() .getService(IEventBroker.class); propertyChangeCommandEB.unsubscribe(debuggerThread.getTopStackFrame()); debuggerThread.getTopStackFrame().fireTerminateEvent(); } setState(ESBDebuggerState.TERMINATED); clearSuspendedEventStatus(); DebugPlugin.getDefault().getBreakpointManager().removeBreakpointListener(this); debugTargetEventBroker.unsubscribe(this); this.fireTerminateEvent(); // Switch back to ESB perspective if the user is in the debug perspective String currentPerspective = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getPerspective().getLabel(); try { if ("debug".equalsIgnoreCase(currentPerspective)) PlatformUI.getWorkbench().showPerspective(ESB_GRAPHICAL_PERSPECTIVE_ID, PlatformUI.getWorkbench().getActiveWorkbenchWindow()); } catch (WorkbenchException e) { log.error("Error occurred while switching to ESB perspective " + e.getMessage()); } // Shut down the micro-integrator runtime MicroIntegratorInstance.getInstance().stop(); } else if (event instanceof MediationFlowCompleteEvent) { clearVariableTable(); setState(ESBDebuggerState.RESUMED); clearSuspendedEventStatus(); OpenEditorUtil.resetToolTipMessages(); } } else { log.warn("Unhandled event type detected for Event Broker Topic : " + ESBDEBUGGER_EVENT_TOPIC); } } } private void clearVariableTable() { ESBStackFrame stackFrame = getThreads()[0].getTopStackFrame(); stackFrame.clearEnvelopeViewPropertyTableValues(); for (ESBPropertyScopeType scope : ESBPropertyScopeType.values()) { try { PropertyRespondMessage propertyMessage = getEmptyVariableMessage(scope.toString()); stackFrame.setVariables(propertyMessage); } catch (Exception e) { log.error("Error while seting variable values", e); //$NON-NLS-1$ } } } private PropertyRespondMessage getEmptyVariableMessage(String variableScope) { PropertyRespondMessage variableMessage = new PropertyRespondMessage(variableScope, new JsonObject()); return variableMessage; } /** * This method clear the breakpoint hit mark from the suspended mediators and remove the suspended point from * breakpoint manager */ private void clearSuspendedEventStatus() { OpenEditorUtil.removeBreakpointHitStatus(); try { deletePreviousSuspendPointsFromBreakpointManager(); } catch (CoreException e) { log.error("Error while deleting previous suspend point : " //$NON-NLS-1$ + e.getMessage(), e); } } /** * Pass an event to the {@link InternalEventDispatcher} where it is handled * asynchronously. * * @param event * event to handle */ void fireModelEvent(final IESBDebuggerInternalEvent event) { debugTargetEventBroker.send(ESB_DEBUG_TARGET_EVENT_TOPIC, event); } /** * This method finds the breakpoint registered in Breakpoint Manager which * suspended the ESB Server and call a method to open the source file and * show the associated mediator * * @param event * @throws ESBDebuggerException * @throws CoreException */ private void showDiagram(SuspendedEvent event) throws ESBDebuggerException, CoreException { AbstractESBDebugPointMessage info = event.getDetail(); ESBDebugPoint breakpoint = getMatchingBreakpoint(info); IFile file = (IFile) breakpoint.getResource(); deletePreviousSuspendPointsFromBreakpointManager(); ESBSuspendPoint suspendPoint = new ESBSuspendPoint(file, breakpoint.getLineNumber(), breakpoint); DebugPlugin.getDefault().getBreakpointManager().addBreakpoint(suspendPoint); if (file.exists()) { OpenEditorUtil.openSeparateEditor(file, breakpoint); } } /** * @throws CoreException */ private void deletePreviousSuspendPointsFromBreakpointManager() throws CoreException { IBreakpoint[] suspendPoints = DebugPlugin.getDefault().getBreakpointManager() .getBreakpoints(SUSPEND_POINT_MODEL_ID); for (IBreakpoint suspendPoint : suspendPoints) { DebugPlugin.getDefault().getBreakpointManager().removeBreakpoint(suspendPoint, true); } } private ESBDebugPoint getMatchingBreakpoint(AbstractESBDebugPointMessage info) throws ESBDebuggerException { IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager() .getBreakpoints(getModelIdentifier()); for (IBreakpoint breakpoint : breakpoints) { try { if (((ESBDebugPoint) breakpoint).isMatchedWithDebugPoint(info, true)) { return (ESBDebugPoint) breakpoint; } } catch (CoreException | DebugPointMarkerNotFoundException e) { log.warn("Error while finding matching breakpoint " //$NON-NLS-1$ + e.getMessage(), e); } } throw new ESBDebuggerException("Matching Breakpoint not found in Breakpoint Manager with attributes"); //$NON-NLS-1$ } @Override public ILaunch getLaunch() { return esbDebugerLaunch; } @Override public IProcess getProcess() { return esbDebugProcess; } @Override public ESBDebugThread[] getThreads() { return esbDebugThreads.toArray(new ESBDebugThread[esbDebugThreads.size()]); } @Override public boolean hasThreads() { return !esbDebugThreads.isEmpty(); } @Override public String getName() { return Messages.ESBDebugTarget_ESBDebugTargetNameTag; } @Override public boolean supportsBreakpoint(final IBreakpoint breakpoint) { if (breakpoint instanceof ESBDebugPoint) { return true; } return false; } @Override public ESBDebugTarget getDebugTarget() { return this; } private boolean isEnabledBreakpoint(IBreakpoint breakpoint) throws CoreException { return breakpoint.isEnabled() && (DebugPlugin.getDefault().getBreakpointManager().isEnabled()); } /** * This method get called when Breakpoint Manager got any new breakpoint * Registered. */ @Override public void breakpointAdded(final IBreakpoint breakpoint) { try { if (breakpoint instanceof ESBDebugPoint && supportsBreakpoint(breakpoint) && isEnabledBreakpoint(breakpoint)) { fireModelEvent(new DebugPointRequest((ESBDebugPoint) breakpoint, DebugPointEventAction.ADDED)); } } catch (DebugPointMarkerNotFoundException e) { log.error("Error while creating DebugPointRequest in debug point adding event : " //$NON-NLS-1$ + e.getMessage(), e); ESBDebuggerUtil.removeESBDebugPointFromBreakpointManager(breakpoint); } catch (CoreException e) { log.error("Error while creating DebugPointRequest in debug point adding event : " //$NON-NLS-1$ + e.getMessage(), e); } } /** * This method get called when any breakpoint is removed from the Breakpoint * Manager. */ @Override public void breakpointRemoved(final IBreakpoint breakpoint, final IMarkerDelta delta) { try { if (breakpoint instanceof ESBDebugPoint && supportsBreakpoint(breakpoint) && isEnabledBreakpoint(breakpoint)) { fireModelEvent(new DebugPointRequest((ESBDebugPoint) breakpoint, DebugPointEventAction.REMOVED)); } } catch (DebugPointMarkerNotFoundException e) { log.error("Error while creating DebugPointRequest in debug point removing event : " //$NON-NLS-1$ + e.getMessage(), e); ESBDebuggerUtil.removeESBDebugPointFromBreakpointManager(breakpoint); } catch (CoreException e) { log.error("Error while creating DebugPointRequest in debug point removing event : " //$NON-NLS-1$ + e.getMessage(), e); } } @Override public void breakpointChanged(final IBreakpoint breakpoint, final IMarkerDelta delta) { // no implementation } @Override public boolean supportsStorageRetrieval() { // no implementation return false; } @Override public IMemoryBlock getMemoryBlock(long startAddress, long length) { // no implementation return null; } }
46.254593
135
0.677524
232e3b30894beb5ef38856955cced6f075e37a6b
1,269
package adbm.antidote.ui; import adbm.util.EverythingIsNonnullByDefault; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; /** * */ @EverythingIsNonnullByDefault public class AntidoteModel { private static final Logger log = LogManager.getLogger(AntidoteModel.class); protected PropertyChangeSupport propertyChangeSupport; /** * */ public AntidoteModel() { propertyChangeSupport = new PropertyChangeSupport(this); } /** * * @param listener */ public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(listener); } /** * * @param listener */ public void removePropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(listener); } /** * * @param propertyName * @param oldValue * @param newValue */ protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue); } }
22.263158
94
0.707644
12517cd3e1ab2c5e39614ae5dee56689b15bcd19
6,677
package org.firstinspires.ftc.teamcode.Utility; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import com.vuforia.Image; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; import org.firstinspires.ftc.teamcode.Autonomous.BaseRoverRuckusAuto; import java.io.IOException; import java.util.List; public class BitmapUtilities { public static final int PIXEL_FORMAT_RGB565 = 1; public static BaseRoverRuckusAuto.GoldPosition findWinnerLocation(int[] leftHueTotal, int[] middleHueTotal, int[] rightHueTotal) { BaseRoverRuckusAuto.GoldPosition winner = BaseRoverRuckusAuto.GoldPosition.MIDDLE; int leftColor, middleColor, rightColor; if(leftHueTotal[0]/*yellow counts*/ > leftHueTotal[1]/*white counts*/) { leftColor = Color.YELLOW; winner = BaseRoverRuckusAuto.GoldPosition.LEFT; } else { leftColor= Color.WHITE; } if(middleHueTotal[0]/*yellow counts*/ > middleHueTotal[1]/*white counts*/) { middleColor = Color.YELLOW; winner = BaseRoverRuckusAuto.GoldPosition.MIDDLE; } else { middleColor= Color.WHITE; } if(rightHueTotal[0]/*yellow counts*/ > rightHueTotal[1]/*white counts*/) { rightColor = Color.YELLOW; winner = BaseRoverRuckusAuto.GoldPosition.RIGHT; } else { rightColor= Color.WHITE; } return winner; } public static BaseRoverRuckusAuto.GoldPosition findWinnerLocation(int[] middleHueTotal, int[] rightHueTotal) { BaseRoverRuckusAuto.GoldPosition winner = BaseRoverRuckusAuto.GoldPosition.LEFT; int middleColor, rightColor; if(middleHueTotal[0]/*yellow counts*/ > middleHueTotal[1]/*white counts*/) { middleColor = Color.YELLOW; winner = BaseRoverRuckusAuto.GoldPosition.MIDDLE; } else { middleColor= Color.WHITE; } if(rightHueTotal[0]/*yellow counts*/ > rightHueTotal[1]/*white counts*/) { rightColor = Color.YELLOW; winner = BaseRoverRuckusAuto.GoldPosition.RIGHT; } else { rightColor= Color.WHITE; } return winner; } public static BaseRoverRuckusAuto.GoldPosition findCorrectGoldLocation (int[] middleHueTotal, int[] rightHueTotal) { BaseRoverRuckusAuto.GoldPosition winner = BaseRoverRuckusAuto.GoldPosition.LEFT; int middleColor, rightColor; if(middleHueTotal[0]/*yellow counts*/ > 0) { middleColor = Color.YELLOW; winner = BaseRoverRuckusAuto.GoldPosition.MIDDLE; } else { middleColor= Color.WHITE; } if(rightHueTotal[0]/*yellow counts*/ > 0) { rightColor = Color.YELLOW; winner = BaseRoverRuckusAuto.GoldPosition.RIGHT; } else { rightColor= Color.WHITE; } return winner; } BaseRoverRuckusAuto.GoldPosition findGoldPosition(int leftHueTotal, int middleHueTotal, int rightHueTotal) { //TODO return null; } BaseRoverRuckusAuto.GoldPosition findGoldPosition(int middleHueTotal, int rightHueTotal) { //TODO return null; } public static Bitmap getBabyBitmap(Bitmap bitmap,List<Integer> config) { return getBabyBitmap(bitmap, config.get(0), config.get(1), config.get(2), config.get(3)); } public static Bitmap getBabyBitmap(Bitmap bitmap, int sampleLeftXPct, int sampleTopYPct, int sampleRightXPct, int sampleBotYPct) { int startXPx = (int) ((sampleLeftXPct / 100.0) * bitmap.getWidth()); int startYPx = (int) ((sampleTopYPct / 100.0) * bitmap.getHeight()); int endXPx = (int) ((sampleRightXPct / 100.0) * bitmap.getWidth()); int endYPx = (int) ((sampleBotYPct / 100.0) * bitmap.getHeight()); int width = endXPx - startXPx; int height = endYPx - startYPx; return Bitmap.createBitmap(bitmap, startXPx, startYPx, width, height); } public static Bitmap drawSamplingBox(String filename, Bitmap bitmap, int sampleLeftXPct, int sampleTopYPct, int sampleRightXPct, int sampleBotYPct) throws IOException { double xPercent = (bitmap.getWidth()) / 100.0; double yPercent = (bitmap.getHeight()) / 100.0; Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); Canvas c = new Canvas(mutableBitmap); Paint p = new Paint(); p.setARGB(100, 0, 200, 0); c.drawRect((int) (sampleLeftXPct * xPercent), (int) (sampleTopYPct * yPercent), (int) (sampleRightXPct * xPercent), (int) (sampleBotYPct * yPercent), p); //writeBitmapFile(filename, mutableBitmap); return mutableBitmap; } public static Bitmap getVuforiaImage(VuforiaLocalizer vuforia) { if (vuforia != null) { try { VuforiaLocalizer.CloseableFrame closeableFrame = vuforia.getFrameQueue().take(); for (int i = 0; i < closeableFrame.getNumImages(); i++) { Image image = closeableFrame.getImage(i); if (image.getFormat() == PIXEL_FORMAT_RGB565) { Bitmap bitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.RGB_565); bitmap.copyPixelsFromBuffer(image.getPixels()); Matrix matrix = new Matrix(); matrix.postRotate(90); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } } } catch (Exception e) { return null; } } return null; } }
37.723164
118
0.557286
73eb2e504f898de44269b9ab4d92ea359b2544fa
1,201
package org.spo.svc3.trx.pgs.t03.handler; import org.spo.ifs3.dsl.controller.AbstractHandler; import org.spo.ifs3.dsl.controller.DSLConstants.EventType; import org.spo.ifs3.dsl.controller.NavEvent; import org.spo.svc3.trx.pgs.t03.task.T0301; import org.spo.svc3.trx.pgs.t03.task.T0302; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class T03Handler extends AbstractHandler{ @Autowired T0301 t0301; @Autowired T0302 t0302; //unused public static final NavEvent EV_NAV_MENU = NavEvent.create(EventType.TRXSWITCH, "T01/Wel_msg"); public static final NavEvent EV_INIT_01 = NavEvent.create(EventType.REFRESHPAGE); public static final NavEvent EV_INIT_02 = NavEvent.create(EventType.REFRESHPAGE); public static final NavEvent EV_REG = NavEvent.create(EventType.TASKSET, "02"); public static final NavEvent EV_PVS_MENU = NavEvent.create(EventType.TASKSET, "01"); @Override public void configureChannel() { taskChannel.put("01",t0301); taskChannel.put("02",t0302); } }
25.020833
100
0.706911
58f54cb80c74d216d6aba8c5987fd097b3dff0bf
29,960
/******************************************************************************* * Copyright (c) 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Zend Technologies *******************************************************************************/ package org.eclipse.php.internal.ui.editor.hover; import java.io.*; import java.net.URL; import java.util.*; import org.eclipse.core.runtime.Platform; import org.eclipse.dltk.ast.declarations.ModuleDeclaration; import org.eclipse.dltk.core.*; import org.eclipse.dltk.internal.ui.editor.EditorUtility; import org.eclipse.dltk.ui.DLTKPluginImages; import org.eclipse.dltk.ui.PreferenceConstants; import org.eclipse.dltk.ui.ScriptElementLabels; import org.eclipse.dltk.ui.viewsupport.BasicElementLabels; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.internal.text.html.BrowserInformationControl; import org.eclipse.jface.internal.text.html.BrowserInformationControlInput; import org.eclipse.jface.internal.text.html.BrowserInput; import org.eclipse.jface.internal.text.html.HTMLPrinter; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.*; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.information.IInformationProviderExtension2; import org.eclipse.php.core.compiler.PHPFlags; import org.eclipse.php.internal.core.ast.nodes.*; import org.eclipse.php.internal.core.compiler.ast.nodes.FullyQualifiedReference; import org.eclipse.php.internal.core.compiler.ast.parser.ASTUtils; import org.eclipse.php.internal.core.corext.dom.NodeFinder; import org.eclipse.php.internal.core.typeinference.PHPModelUtils; import org.eclipse.php.internal.ui.PHPUiPlugin; import org.eclipse.php.internal.ui.documentation.PHPDocumentationContentAccess; import org.eclipse.php.internal.ui.documentation.PHPElementLinks; import org.eclipse.php.internal.ui.util.Messages; import org.eclipse.php.internal.ui.util.OpenBrowserUtil; import org.eclipse.php.ui.editor.SharedASTProvider; import org.eclipse.php.ui.editor.hover.IHoverMessageDecorator; import org.eclipse.php.ui.editor.hover.IPHPTextHover; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.editors.text.EditorsUI; import org.osgi.framework.Bundle; @SuppressWarnings("restriction") public class PHPDocumentationHover extends AbstractPHPEditorTextHover implements IPHPTextHover, IInformationProviderExtension2 { public IHoverMessageDecorator getMessageDecorator() { return null; } /** * Action to go back to the previous input in the hover control. * * @since 3.4 */ private static final class BackAction extends Action { private final BrowserInformationControl fInfoControl; public BackAction(BrowserInformationControl infoControl) { fInfoControl = infoControl; setText(PHPHoverMessages.JavadocHover_back); ISharedImages images = PlatformUI.getWorkbench().getSharedImages(); setImageDescriptor(images .getImageDescriptor(ISharedImages.IMG_TOOL_BACK)); setDisabledImageDescriptor(images .getImageDescriptor(ISharedImages.IMG_TOOL_BACK_DISABLED)); update(); } public void run() { BrowserInformationControlInput previous = (BrowserInformationControlInput) fInfoControl .getInput().getPrevious(); if (previous != null) { fInfoControl.setInput(previous); } } public void update() { BrowserInformationControlInput current = fInfoControl.getInput(); if (current != null && current.getPrevious() != null) { BrowserInput previous = current.getPrevious(); setToolTipText(Messages.format( PHPHoverMessages.JavadocHover_back_toElement_toolTip, BasicElementLabels.getJavaElementName(previous .getInputName()))); setEnabled(true); } else { setToolTipText(PHPHoverMessages.JavadocHover_back); setEnabled(false); } } } /** * Action to go forward to the next input in the hover control. * * @since 3.4 */ private static final class ForwardAction extends Action { private final BrowserInformationControl fInfoControl; public ForwardAction(BrowserInformationControl infoControl) { fInfoControl = infoControl; setText(PHPHoverMessages.JavadocHover_forward); ISharedImages images = PlatformUI.getWorkbench().getSharedImages(); setImageDescriptor(images .getImageDescriptor(ISharedImages.IMG_TOOL_FORWARD)); setDisabledImageDescriptor(images .getImageDescriptor(ISharedImages.IMG_TOOL_FORWARD_DISABLED)); update(); } public void run() { BrowserInformationControlInput next = (BrowserInformationControlInput) fInfoControl .getInput().getNext(); if (next != null) { fInfoControl.setInput(next); } } public void update() { BrowserInformationControlInput current = fInfoControl.getInput(); if (current != null && current.getNext() != null) { setToolTipText(Messages .format(PHPHoverMessages.JavadocHover_forward_toElement_toolTip, BasicElementLabels.getJavaElementName(current .getNext().getInputName()))); setEnabled(true); } else { setToolTipText(PHPHoverMessages.JavadocHover_forward_toolTip); setEnabled(false); } } } /** * Action that opens the current hover input element. * * @since 3.4 */ private static final class OpenDeclarationAction extends Action { private final BrowserInformationControl fInfoControl; public OpenDeclarationAction(BrowserInformationControl infoControl) { fInfoControl = infoControl; setText(PHPHoverMessages.JavadocHover_openDeclaration); DLTKPluginImages.setLocalImageDescriptors(this, "goto_input.gif"); //$NON-NLS-1$ //TODO: better images } /* * @see org.eclipse.jface.action.Action#run() */ public void run() { PHPDocumentationBrowserInformationControlInput infoInput = (PHPDocumentationBrowserInformationControlInput) fInfoControl .getInput(); // TODO: check cast fInfoControl.notifyDelayedInputChange(null); fInfoControl.dispose(); // FIXME: should have protocol to hide, // rather than dispose try { // FIXME: add hover location to editor navigation history? IEditorPart editor = EditorUtility.openInEditor( infoInput.getElement(), true); EditorUtility.revealInEditor(editor, infoInput.getElement()); } catch (PartInitException e) { PHPUiPlugin.log(e); } catch (ModelException e) { PHPUiPlugin.log(e); } } } /** * Presenter control creator. * * @since 3.3 */ public static final class PresenterControlCreator extends AbstractReusableInformationControlCreator { /* * @seeorg.eclipse.jdt.internal.ui.text.java.hover. * AbstractReusableInformationControlCreator * #doCreateInformationControl(org.eclipse.swt.widgets.Shell) */ public IInformationControl doCreateInformationControl(Shell parent) { if (BrowserInformationControl.isAvailable(parent)) { ToolBarManager tbm = new ToolBarManager(SWT.FLAT); String font = PreferenceConstants.APPEARANCE_DOCUMENTATION_FONT; BrowserInformationControl iControl = new BrowserInformationControl( parent, font, tbm); final BackAction backAction = new BackAction(iControl); backAction.setEnabled(false); tbm.add(backAction); final ForwardAction forwardAction = new ForwardAction(iControl); tbm.add(forwardAction); forwardAction.setEnabled(false); final OpenDeclarationAction openDeclarationAction = new OpenDeclarationAction( iControl); tbm.add(openDeclarationAction); // final SimpleSelectionProvider selectionProvider = new // SimpleSelectionProvider(); // OpenExternalBrowserAction openExternalJavadocAction = new // OpenExternalBrowserAction( // parent.getDisplay(), selectionProvider); // selectionProvider // .addSelectionChangedListener(openExternalJavadocAction); // selectionProvider.setSelection(new StructuredSelection()); // tbm.add(openExternalJavadocAction); IInputChangedListener inputChangeListener = new IInputChangedListener() { public void inputChanged(Object newInput) { backAction.update(); forwardAction.update(); if (newInput == null) { } else if (newInput instanceof BrowserInformationControlInput) { BrowserInformationControlInput input = (BrowserInformationControlInput) newInput; Object inputElement = input.getInputElement(); boolean isJavaElementInput = inputElement instanceof IModelElement; openDeclarationAction .setEnabled(isJavaElementInput); } } }; iControl.addInputChangeListener(inputChangeListener); tbm.update(true); addLinkListener(iControl); return iControl; } else { return new DefaultInformationControl(parent, true); } } } /** * Hover control creator. * * @since 3.3 */ public static final class HoverControlCreator extends AbstractReusableInformationControlCreator { /** * The information presenter control creator. * * @since 3.4 */ private final IInformationControlCreator fInformationPresenterControlCreator; /** * @param informationPresenterControlCreator * control creator for enriched hover * @since 3.4 */ public HoverControlCreator( IInformationControlCreator informationPresenterControlCreator) { fInformationPresenterControlCreator = informationPresenterControlCreator; } /* * @seeorg.eclipse.jdt.internal.ui.text.java.hover. * AbstractReusableInformationControlCreator * #doCreateInformationControl(org.eclipse.swt.widgets.Shell) */ public IInformationControl doCreateInformationControl(Shell parent) { String tooltipAffordanceString = EditorsUI .getTooltipAffordanceString(); if (BrowserInformationControl.isAvailable(parent)) { String font = PreferenceConstants.APPEARANCE_DOCUMENTATION_FONT; BrowserInformationControl iControl = new BrowserInformationControl( parent, font, tooltipAffordanceString) { /* * @see * org.eclipse.jface.text.IInformationControlExtension5# * getInformationPresenterControlCreator() */ public IInformationControlCreator getInformationPresenterControlCreator() { return fInformationPresenterControlCreator; } }; addLinkListener(iControl); return iControl; } else { return new DefaultInformationControl(parent, tooltipAffordanceString); } } /* * @seeorg.eclipse.jdt.internal.ui.text.java.hover. * AbstractReusableInformationControlCreator * #canReuse(org.eclipse.jface.text.IInformationControl) */ public boolean canReuse(IInformationControl control) { if (!super.canReuse(control)) return false; if (control instanceof IInformationControlExtension4) { String tooltipAffordanceString = EditorsUI .getTooltipAffordanceString(); ((IInformationControlExtension4) control) .setStatusText(tooltipAffordanceString); } return true; } } private static final long LABEL_FLAGS = ScriptElementLabels.ALL_FULLY_QUALIFIED | ScriptElementLabels.M_PRE_RETURNTYPE | ScriptElementLabels.M_PARAMETER_TYPES | ScriptElementLabels.M_PARAMETER_NAMES | ScriptElementLabels.M_EXCEPTIONS | ScriptElementLabels.F_PRE_TYPE_SIGNATURE | ScriptElementLabels.M_PRE_TYPE_PARAMETERS | ScriptElementLabels.T_TYPE_PARAMETERS | ScriptElementLabels.USE_RESOLVED; private static final long LOCAL_VARIABLE_FLAGS = LABEL_FLAGS & ~ScriptElementLabels.F_FULLY_QUALIFIED | ScriptElementLabels.F_POST_QUALIFIED; /** * The style sheet (css). * * @since 3.4 */ private static String fgStyleSheet; /** * The hover control creator. * * @since 3.2 */ private IInformationControlCreator fHoverControlCreator; /** * The presentation control creator. * * @since 3.2 */ private IInformationControlCreator fPresenterControlCreator; /* * @seeorg.eclipse.jface.text.ITextHoverExtension2# * getInformationPresenterControlCreator() * * @since 3.1 */ public IInformationControlCreator getInformationPresenterControlCreator() { if (fPresenterControlCreator == null) fPresenterControlCreator = new PresenterControlCreator(); return fPresenterControlCreator; } /* * @see ITextHoverExtension#getHoverControlCreator() * * @since 3.2 */ public IInformationControlCreator getHoverControlCreator() { if (fHoverControlCreator == null) fHoverControlCreator = new HoverControlCreator( getInformationPresenterControlCreator()); return fHoverControlCreator; } private static void addLinkListener(final BrowserInformationControl control) { control.addLocationListener(PHPElementLinks .createLocationListener(new PHPElementLinks.ILinkHandler() { /* * (non-Javadoc) * * @see * org.eclipse.jdt.internal.ui.viewsupport.JavaElementLinks * .ILinkHandler * #handleInlineJavadocLink(org.eclipse.jdt.core * .IModelElement) */ public void handleInlineLink(IModelElement linkTarget) { PHPDocumentationBrowserInformationControlInput hoverInfo = getHoverInfo( new IModelElement[] { linkTarget }, null, (PHPDocumentationBrowserInformationControlInput) control .getInput()); if (control.hasDelayedInputChangeListener()) control.notifyDelayedInputChange(hoverInfo); else control.setInput(hoverInfo); } /* * (non-Javadoc) * * @see * org.eclipse.jdt.internal.ui.viewsupport.JavaElementLinks * .ILinkHandler * #handleDeclarationLink(org.eclipse.jdt.core. * IModelElement) */ public void handleDeclarationLink(IModelElement linkTarget) { control.notifyDelayedInputChange(null); control.dispose(); // FIXME: should have protocol to // hide, rather than dispose // try { // FIXME: add hover location to editor navigation // history? // JavaUI.openInEditor(linkTarget); // } catch (PartInitException e) { // PHPUiPlugin.log(e); // } catch (ModelException e) { // PHPUiPlugin.log(e); // } } /* * (non-Javadoc) * * @see * org.eclipse.jdt.internal.ui.viewsupport.JavaElementLinks * .ILinkHandler#handleExternalLink(java.net.URL, * org.eclipse.swt.widgets.Display) */ public boolean handleExternalLink(URL url, Display display) { control.notifyDelayedInputChange(null); control.dispose(); // FIXME: should have protocol to // hide, rather than dispose // open external links in real browser: OpenBrowserUtil.open(url, display); //$NON-NLS-1$ return true; } public void handleTextSet() { } })); } /** * @deprecated see * {@link org.eclipse.jface.text.ITextHover#getHoverInfo(ITextViewer, IRegion)} */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { PHPDocumentationBrowserInformationControlInput info = (PHPDocumentationBrowserInformationControlInput) getHoverInfo2( textViewer, hoverRegion); return info != null ? info.getHtml() : null; } /* * @see * org.eclipse.jface.text.ITextHoverExtension2#getHoverInfo2(org.eclipse * .jface.text.ITextViewer, org.eclipse.jface.text.IRegion) */ public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) { return internalGetHoverInfo(textViewer, hoverRegion); } private PHPDocumentationBrowserInformationControlInput internalGetHoverInfo( ITextViewer textViewer, IRegion hoverRegion) { IModelElement[] elements = getElementsAt(textViewer, hoverRegion); if (elements == null || elements.length == 0) return null; // filter the same namespace Set<IModelElement> elementSet = new TreeSet<IModelElement>( new Comparator<IModelElement>() { public int compare(IModelElement o1, IModelElement o2) { if (o1 instanceof IType && o2 instanceof IType) { IType type1 = (IType) o1; IType type2 = (IType) o2; try { if (PHPFlags.isNamespace(type1.getFlags()) && PHPFlags.isNamespace(type2 .getFlags()) && type1.getElementName().equals( type2.getElementName())) { return 0; } } catch (ModelException e) { } } return 1; } }); List<IModelElement> elementList = new ArrayList<IModelElement>(); for (int i = 0; i < elements.length; i++) { if (!elementSet.contains(elements[i])) { elementSet.add(elements[i]); elementList.add(elements[i]); } } elements = elementList.toArray(new IModelElement[elementList.size()]); String constantValue; if (elements.length == 1 && elements[0].getElementType() == IModelElement.FIELD) { constantValue = getConstantValue((IField) elements[0], hoverRegion); if (constantValue != null) constantValue = HTMLPrinter.convertToHTMLContent(constantValue); } else { constantValue = null; } return getHoverInfo(elements, constantValue, null); } /** * Computes the hover info. * * @param elements * the resolved elements * @param constantValue * a constant value iff result contains exactly 1 constant field, * or <code>null</code> * @param previousInput * the previous input, or <code>null</code> * @return the HTML hover info for the given element(s) or <code>null</code> * if no information is available * @since 3.4 */ private static PHPDocumentationBrowserInformationControlInput getHoverInfo( IModelElement[] elements, String constantValue, PHPDocumentationBrowserInformationControlInput previousInput) { StringBuffer buffer = new StringBuffer(); boolean hasContents = false; IModelElement element = null; int leadingImageWidth = 20; for (int i = 0; i < elements.length; i++) { element = elements[i]; if (element instanceof IMember) { IMember member = (IMember) element; HTMLPrinter.addSmallHeader(buffer, getInfoText(member, constantValue, true, i == 0)); Reader reader = null; try { reader = getHTMLContent(member); } catch (ModelException e) { } if (reader != null) { HTMLPrinter.addParagraph(buffer, reader); } if (i != elements.length - 1) { buffer.append("<hr>"); //$NON-NLS-1$ } hasContents = true; } else if (element.getElementType() == IModelElement.FIELD) { HTMLPrinter.addSmallHeader(buffer, getInfoText(element, constantValue, true, i == 0)); hasContents = true; } } if (!hasContents) return null; if (buffer.length() > 0) { HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet()); HTMLPrinter.addPageEpilog(buffer); return new PHPDocumentationBrowserInformationControlInput( previousInput, element, buffer.toString(), leadingImageWidth); } return null; } private static String getInfoText(IModelElement element, String constantValue, boolean allowImage, boolean isFirstElement) { StringBuffer label = getInfoText(element); if (element.getElementType() == IModelElement.FIELD) { if (constantValue != null) { label.append(' '); label.append('='); label.append(' '); label.append(constantValue); } } String imageName = null; if (allowImage) { URL imageUrl = PHPUiPlugin.getDefault().getImagesOnFSRegistry() .getImageURL(element); if (imageUrl != null) { imageName = imageUrl.toExternalForm(); } } StringBuffer buf = new StringBuffer(); addImageAndLabel(buf, imageName, 16, 16, 2, 2, label.toString(), 20, 2, isFirstElement); return buf.toString(); } /* * @since 3.4 */ private static boolean isFinal(IField field) { try { return PHPFlags.isFinal(field.getFlags()); } catch (ModelException e) { PHPUiPlugin.log(e); return false; } } /** * Returns the constant value for the given field. * * @param field * the field * @param hoverRegion * the hover region * @return the constant value for the given field or <code>null</code> if * none * @since 3.4 */ private String getConstantValue(IField field, IRegion hoverRegion) { if (!isFinal(field)) return null; ISourceModule typeRoot = getEditorInputModelElement(); if (typeRoot == null) return null; Object constantValue = null; if (field != null && field.exists()) { try { Program unit = SharedASTProvider.getAST( field.getSourceModule(), SharedASTProvider.WAIT_YES, null); ASTNode node = NodeFinder.perform(unit, field.getNameRange() .getOffset(), field.getNameRange().getLength()); if (node != null) { if (node instanceof Identifier && node.getParent() instanceof ConstantDeclaration) { ConstantDeclaration decl = (ConstantDeclaration) node .getParent(); if (decl.initializers().size() == 1 && decl.initializers().get(0) instanceof Scalar) { Scalar scalar = (Scalar) decl.initializers().get(0); constantValue = scalar.getStringValue(); } } else if (node instanceof Scalar && node.getParent() instanceof FunctionInvocation) { FunctionInvocation invocation = (FunctionInvocation) node .getParent(); Expression function = invocation.getFunctionName() .getName(); String functionName = ""; //$NON-NLS-1$ // for PHP5.3 if (function instanceof NamespaceName) { // global function if (((NamespaceName) function).isGlobal()) { functionName = ((NamespaceName) function) .getName(); if (functionName.charAt(0) == '\\') { functionName = functionName.substring(1); } } else { ModuleDeclaration parsedUnit = SourceParserUtil .getModuleDeclaration( field.getSourceModule(), null); org.eclipse.dltk.ast.ASTNode func = ASTUtils .findMinimalNode(parsedUnit, function.getStart(), function.getEnd()); if (func instanceof FullyQualifiedReference) { functionName = ((FullyQualifiedReference) func) .getFullyQualifiedName(); } // look for the element in current namespace if (functionName.indexOf('\\') == -1) { IType currentNamespace = PHPModelUtils .getCurrentNamespace( field.getSourceModule(), function.getStart()); String fullyQualifiedFuncName = ""; //$NON-NLS-1$ if (currentNamespace != null) { fullyQualifiedFuncName = "\\" //$NON-NLS-1$ + currentNamespace .getElementName() + "\\" + functionName; //$NON-NLS-1$ } else { fullyQualifiedFuncName = functionName; } IMethod[] methods = PHPModelUtils .getFunctions( fullyQualifiedFuncName, field.getSourceModule(), function.getStart(), null); if (methods != null && methods.length > 0) { functionName = fullyQualifiedFuncName; } } } } else if (function instanceof Identifier) { functionName = ((Identifier) function).getName(); } if (functionName.equalsIgnoreCase("define") //$NON-NLS-1$ && invocation.parameters().size() >= 2 && invocation.parameters().get(1) instanceof Scalar) { constantValue = ((Scalar) invocation.parameters() .get(1)).getStringValue(); } } } } catch (ModelException e) { } catch (IOException e) { } } if (constantValue == null) return null; if (constantValue instanceof String) { StringBuffer result = new StringBuffer(); String stringConstant = (String) constantValue; if (stringConstant.length() > 80) { result.append(stringConstant.substring(0, 80)); result.append(ScriptElementLabels.ELLIPSIS_STRING); } else { result.append(stringConstant); } return result.toString(); } else if (constantValue instanceof Integer) { int intValue = ((Integer) constantValue).intValue(); return formatWithHexValue(constantValue, "0x" + Integer.toHexString(intValue)); //$NON-NLS-1$ } else { return constantValue.toString(); } } /** * Creates and returns a formatted message for the given constant with its * hex value. * * @param constantValue * the constant value * @param hexValue * the hex value * @return a formatted string with constant and hex values * @since 3.4 */ private static String formatWithHexValue(Object constantValue, String hexValue) { return Messages.format( PHPHoverMessages.JavadocHover_constantValue_hexValue, new String[] { constantValue.toString(), hexValue }); } /** * Returns the Javadoc hover style sheet with the current Javadoc font from * the preferences. * * @return the updated style sheet * @since 3.4 */ protected static String getStyleSheet() { if (fgStyleSheet == null) fgStyleSheet = loadStyleSheet(); String css = fgStyleSheet; if (css != null) { FontData fontData = JFaceResources.getFontRegistry().getFontData( PreferenceConstants.APPEARANCE_DOCUMENTATION_FONT)[0]; css = HTMLPrinter.convertTopLevelFont(css, fontData); } return css; } /** * Loads and returns the Javadoc hover style sheet. * * @return the style sheet, or <code>null</code> if unable to load * @since 3.4 */ private static String loadStyleSheet() { Bundle bundle = Platform.getBundle(PHPUiPlugin.getPluginId()); URL styleSheetURL = bundle .getEntry("/PHPDocumentationHoverStyleSheet.css"); //$NON-NLS-1$ if (styleSheetURL != null) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader( styleSheetURL.openStream())); StringBuffer buffer = new StringBuffer(1500); String line = reader.readLine(); while (line != null) { buffer.append(line); buffer.append('\n'); line = reader.readLine(); } return buffer.toString(); } catch (IOException ex) { PHPUiPlugin.log(ex); return ""; //$NON-NLS-1$ } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } } } return null; } public static void addImageAndLabel(StringBuffer buf, String imageName, int imageWidth, int imageHeight, int imageLeft, int imageTop, String label, int labelLeft, int labelTop) { addImageAndLabel(buf, imageName, imageWidth, imageHeight, imageLeft, imageTop, label, labelLeft, labelTop, true); } private static void addImageAndLabel(StringBuffer buf, String imageName, int imageWidth, int imageHeight, int imageLeft, int imageTop, String label, int labelLeft, int labelTop, boolean isFirstElement) { // workaround to make the window wide enough label = label + "&nbsp"; //$NON-NLS-1$ if (imageName != null) { StringBuffer imageStyle = new StringBuffer("position: absolute; "); //$NON-NLS-1$ imageStyle.append("width: ").append(imageWidth).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ imageStyle.append("height: ").append(imageHeight).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ if (isFirstElement) { imageStyle.append("top: ").append(imageTop).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ imageStyle.append("left: ").append(imageLeft).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ } else { imageStyle .append("margin-top: ").append(imageTop).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ imageStyle .append("margin-left: ").append(-imageLeft).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ } buf.append("<!--[if lte IE 6]><![if gte IE 5.5]>\n"); //$NON-NLS-1$ buf.append("<span style=\"").append(imageStyle).append("filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='").append(imageName).append("')\"></span>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append("<![endif]><![endif]-->\n"); //$NON-NLS-1$ buf.append("<!--[if !IE]>-->\n"); //$NON-NLS-1$ buf.append("<img style='").append(imageStyle).append("' src='").append(imageName).append("'/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append("<!--<![endif]-->\n"); //$NON-NLS-1$ buf.append("<!--[if gte IE 7]>\n"); //$NON-NLS-1$ buf.append("<img style='").append(imageStyle).append("' src='").append(imageName).append("'/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append("<![endif]-->\n"); //$NON-NLS-1$ } buf.append("<div style='word-wrap:break-word;"); //$NON-NLS-1$ if (imageName != null) { buf.append("margin-left: ").append(labelLeft).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ buf.append("margin-top: ").append(labelTop).append("px; "); //$NON-NLS-1$ //$NON-NLS-2$ } buf.append("'>"); //$NON-NLS-1$ buf.append(label); buf.append("</div>"); //$NON-NLS-1$ } protected static Reader getHTMLContent(IMember curr) throws ModelException { String html = PHPDocumentationContentAccess.getHTMLContent(curr); if (html != null) { return new StringReader(html); } return null; // return ScriptDocumentationAccess.getHTMLContentReader(PHPNature.ID, // curr, true, true); } private static StringBuffer getInfoText(IModelElement member) { long flags = member.getElementType() == IModelElement.FIELD ? LOCAL_VARIABLE_FLAGS : LABEL_FLAGS; String label = ScriptElementLabels.getDefault().getElementLabel(member, flags); return new StringBuffer(label); } }
32.995595
210
0.692023
2efbd0493108710721c534745bcc7c9a7934e623
955
/* * Created on Jan 16, 2010 */ package lia.Monitor.ciena.triggers.repository; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author ramiro * */ class CienaVCGCheckerTask implements Runnable { private static final Logger logger = Logger.getLogger(CienaVCGCheckerTask.class.getName()); final CienaVCGAlarm vcgAlarm; CienaVCGCheckerTask(CienaVCGAlarm vcgAlarm) { if (vcgAlarm == null) { throw new NullPointerException("Null CienaVCGConfigEntry"); } this.vcgAlarm = vcgAlarm; } @Override public void run() { final boolean isFine = logger.isLoggable(Level.FINE); final boolean isFiner = (isFine || logger.isLoggable(Level.FINER)); final boolean isFinest = (isFiner || logger.isLoggable(Level.FINEST)); if (isFinest) { logger.log(Level.FINEST, "Starting CienaVCGCheckerTask for: " + vcgAlarm); } } }
23.875
95
0.658639
931f5e5f0feed6cd9db9e7793410890f5de29c48
832
package com.thirdparty.rabbitmq.base; /** * @author lagon * @time 2017/5/23 11:13 * @description MQ交易状态枚举 */ public enum MQTransStatus { /** * 处理中 */ PROCESSING("0","处理中"), /** * 成功 */ SUCCESS("1", "成功"), /** * 失败 */ ERROR("2", "失败"); private String code; private String desc; MQTransStatus(String code, String desc) { this.code = code; this.desc = desc; } public String getCode() { return code; } public String getDesc() { return desc; } public static MQTransStatus getEnum(String code){ for (MQTransStatus transStatus : MQTransStatus.values()) { if (transStatus.getCode().equals(code)) { return transStatus; } } return null; } }
17.333333
66
0.520433
90c6f8c2e6b5164f3917cdfc06274c59d043deab
2,294
package com.jyc.complieonthefly; import org.junit.Test; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Collectors; public class EvilExecutor { private String readCode(String sourcePath) throws FileNotFoundException { InputStream stream = new FileInputStream(sourcePath); String separator = System.getProperty("line.separator"); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); return reader.lines().collect(Collectors.joining(separator)); } private Path saveSource(String source) throws IOException { String tmpProperty = System.getProperty("java.io.tmpdir"); Path sourcePath = Paths.get(tmpProperty, "Harmless.java"); Files.write(sourcePath, source.getBytes("UTF-8")); return sourcePath; } private Path compileSource(Path javaFile) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); compiler.run(null, null, null, javaFile.toFile().getAbsolutePath()); return javaFile.getParent().resolve("Harmless.class"); } private void runClass(Path javaClass) throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException { URL classUrl = javaClass.getParent().toFile().toURI().toURL(); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{classUrl}); Class<?> clazz = Class.forName("Harmless", true, classLoader); clazz.newInstance(); } public void doEvil(String sourcePath) throws Exception { String source = readCode(sourcePath); Path javaFile = saveSource(source); Path classFile = compileSource(javaFile); runClass(classFile); } public static void main(String... args) throws Exception { new EvilExecutor().doEvil(args[0]); } @Test public void testEvil(){ String classPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); System.out.println(System.getProperty("java.io.tmpdir")); } }
36.412698
114
0.706626
9916a22652752465e8d09b1e06ef222ee19ef8b5
1,226
package de.pnp.manager.model.character.state.implementations.manipulating; import de.pnp.manager.main.LanguageUtility; import de.pnp.manager.model.character.IPnPCharacter; import de.pnp.manager.model.character.PnPCharacter; import de.pnp.manager.model.character.state.IManipulatingMemberState; import de.pnp.manager.model.character.state.MemberStateIcon; import de.pnp.manager.model.character.state.RandomPowerMemberState; import de.pnp.manager.model.character.state.interfaces.IRandomPowerMemberStateImpl; import javafx.beans.property.ReadOnlyStringProperty; public class HealMemberState extends RandomPowerMemberState implements IManipulatingMemberState, IRandomPowerMemberStateImpl { public HealMemberState(String name, int duration, boolean activeRounder, PnPCharacter source, float maxPower, boolean random) { super(name, MemberStateIcon.HEAL, duration, activeRounder, source, maxPower, random); } @Override public void apply(IPnPCharacter character) { ((PnPCharacter) character).heal(Math.round(getEffectPower()), getSource()); } @Override public ReadOnlyStringProperty toStringProperty() { return LanguageUtility.getMessageProperty("state.effect.heal"); } }
43.785714
131
0.801794
9cd0581ca638b14153a07768ed50666715a838f3
13,123
/* * Copyright (c) 2012, 2014, Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * - Neither the name of Oracle Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.oracle.javafx.scenebuilder.kit.editor.panel.content.driver; import com.oracle.javafx.scenebuilder.kit.editor.panel.content.AbstractDecoration; import java.util.List; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.shape.ClosePath; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.PathElement; /** */ public class TabOutline { // // 2 3 // +--------------+ // 0 | | 5 // +-----+ +-----------------+ // | 1 4 | // | | // | | // | | // +--------------------------------------+ // 7 6 // private final Path ringPath = new Path(); private final MoveTo moveTo0 = new MoveTo(); private final LineTo lineTo1 = new LineTo(); private final LineTo lineTo2 = new LineTo(); private final LineTo lineTo3 = new LineTo(); private final LineTo lineTo4 = new LineTo(); private final LineTo lineTo5 = new LineTo(); private final LineTo lineTo6 = new LineTo(); private final LineTo lineTo7 = new LineTo(); private final TabPaneDesignInfoX tabPaneDesignInfo = new TabPaneDesignInfoX(); private final Tab tab; public TabOutline(Tab tab) { assert tab != null; this.tab = tab; final List<PathElement> ringElements = ringPath.getElements(); ringElements.add(moveTo0); ringElements.add(lineTo1); ringElements.add(lineTo2); ringElements.add(lineTo3); ringElements.add(lineTo3); ringElements.add(lineTo4); ringElements.add(lineTo5); ringElements.add(lineTo6); ringElements.add(lineTo7); ringElements.add(new ClosePath()); } public Path getRingPath() { return ringPath; } public void layout(AbstractDecoration<?> hostDecoration) { final TabPane tabPane = tab.getTabPane(); final Bounds headerBounds = tabPaneDesignInfo.computeTabBounds(tabPane, tab); final Bounds contentBounds = tabPaneDesignInfo.computeContentAreaBounds(tabPane); switch (tabPane.getSide()) { default: case TOP: layoutForTopSide(headerBounds, contentBounds, hostDecoration); break; case BOTTOM: layoutForBottomSide(headerBounds, contentBounds, hostDecoration); break; case LEFT: layoutForLeftSide(headerBounds, contentBounds, hostDecoration); break; case RIGHT: layoutForRightSide(headerBounds, contentBounds, hostDecoration); break; } } /* * Private */ private void layoutForTopSide( Bounds headerBounds, Bounds contentBounds, AbstractDecoration<?> hd) { // // x0 x1 x2 x3 // // y0 +--------------+ // | header | // +--------------+ // y1 +--------------------------------------+ // | | // | | // | content | // | | // y2 +--------------------------------------+ // final double x0 = contentBounds.getMinX(); final double x1 = headerBounds.getMinX(); final double x2 = headerBounds.getMaxX(); final double x3 = contentBounds.getMaxX(); final double y0 = headerBounds.getMinY(); final double y1 = contentBounds.getMinY(); final double y2 = contentBounds.getMaxY(); final boolean snapToPixel = true; final Point2D p0 = hd.sceneGraphObjectToDecoration(x0, y1, snapToPixel); final Point2D p1 = hd.sceneGraphObjectToDecoration(x1, y1, snapToPixel); final Point2D p2 = hd.sceneGraphObjectToDecoration(x1, y0, snapToPixel); final Point2D p3 = hd.sceneGraphObjectToDecoration(x2, y0, snapToPixel); final Point2D p4 = hd.sceneGraphObjectToDecoration(x2, y1, snapToPixel); final Point2D p5 = hd.sceneGraphObjectToDecoration(x3, y1, snapToPixel); final Point2D p6 = hd.sceneGraphObjectToDecoration(x3, y2, snapToPixel); final Point2D p7 = hd.sceneGraphObjectToDecoration(x0, y2, snapToPixel); moveTo0.setX(p0.getX()); moveTo0.setY(p0.getY()); lineTo1.setX(p1.getX()); lineTo1.setY(p1.getY()); lineTo2.setX(p2.getX()); lineTo2.setY(p2.getY()); lineTo3.setX(p3.getX()); lineTo3.setY(p3.getY()); lineTo4.setX(p4.getX()); lineTo4.setY(p4.getY()); lineTo5.setX(p5.getX()); lineTo5.setY(p5.getY()); lineTo6.setX(p6.getX()); lineTo6.setY(p6.getY()); lineTo7.setX(p7.getX()); lineTo7.setY(p7.getY()); } private void layoutForBottomSide( Bounds headerBounds, Bounds contentBounds, AbstractDecoration<?> hd) { // // x0 x1 x2 x3 // // y0 +--------------------------------------+ // | | // | | // | content | // | | // y1 +--------------------------------------+ // +--------------+ // | header | // y2 +--------------+ // final double x0 = contentBounds.getMinX(); final double x1 = headerBounds.getMinX(); final double x2 = headerBounds.getMaxX(); final double x3 = contentBounds.getMaxX(); final double y0 = contentBounds.getMinY(); final double y1 = contentBounds.getMaxY(); final double y2 = headerBounds.getMaxY(); final boolean snapToPixel = true; final Point2D p0 = hd.sceneGraphObjectToDecoration(x0, y0, snapToPixel); final Point2D p1 = hd.sceneGraphObjectToDecoration(x3, y0, snapToPixel); final Point2D p2 = hd.sceneGraphObjectToDecoration(x3, y1, snapToPixel); final Point2D p3 = hd.sceneGraphObjectToDecoration(x2, y1, snapToPixel); final Point2D p4 = hd.sceneGraphObjectToDecoration(x2, y2, snapToPixel); final Point2D p5 = hd.sceneGraphObjectToDecoration(x1, y2, snapToPixel); final Point2D p6 = hd.sceneGraphObjectToDecoration(x1, y1, snapToPixel); final Point2D p7 = hd.sceneGraphObjectToDecoration(x0, y1, snapToPixel); moveTo0.setX(p0.getX()); moveTo0.setY(p0.getY()); lineTo1.setX(p1.getX()); lineTo1.setY(p1.getY()); lineTo2.setX(p2.getX()); lineTo2.setY(p2.getY()); lineTo3.setX(p3.getX()); lineTo3.setY(p3.getY()); lineTo4.setX(p4.getX()); lineTo4.setY(p4.getY()); lineTo5.setX(p5.getX()); lineTo5.setY(p5.getY()); lineTo6.setX(p6.getX()); lineTo6.setY(p6.getY()); lineTo7.setX(p7.getX()); lineTo7.setY(p7.getY()); } private void layoutForLeftSide( Bounds headerBounds, Bounds contentBounds, AbstractDecoration<?> hd) { // // x0 x1 x2 // // y0 +---------------------------+ // | | // y1 +--+ | | // | | | | // |h | | | // | | | content | // | | | | // y2 +--+ | | // | | // | | // | | // | | // y3 +---------------------------+ // // final double x0 = headerBounds.getMinX(); final double x1 = contentBounds.getMinX(); final double x2 = contentBounds.getMaxX(); final double y0 = contentBounds.getMinY(); final double y1 = headerBounds.getMinY(); final double y2 = headerBounds.getMaxY(); final double y3 = contentBounds.getMaxY(); final boolean snapToPixel = true; final Point2D p0 = hd.sceneGraphObjectToDecoration(x0, y1, snapToPixel); final Point2D p1 = hd.sceneGraphObjectToDecoration(x1, y1, snapToPixel); final Point2D p2 = hd.sceneGraphObjectToDecoration(x1, y0, snapToPixel); final Point2D p3 = hd.sceneGraphObjectToDecoration(x2, y0, snapToPixel); final Point2D p4 = hd.sceneGraphObjectToDecoration(x2, y3, snapToPixel); final Point2D p5 = hd.sceneGraphObjectToDecoration(x1, y3, snapToPixel); final Point2D p6 = hd.sceneGraphObjectToDecoration(x1, y2, snapToPixel); final Point2D p7 = hd.sceneGraphObjectToDecoration(x0, y2, snapToPixel); moveTo0.setX(p0.getX()); moveTo0.setY(p0.getY()); lineTo1.setX(p1.getX()); lineTo1.setY(p1.getY()); lineTo2.setX(p2.getX()); lineTo2.setY(p2.getY()); lineTo3.setX(p3.getX()); lineTo3.setY(p3.getY()); lineTo4.setX(p4.getX()); lineTo4.setY(p4.getY()); lineTo5.setX(p5.getX()); lineTo5.setY(p5.getY()); lineTo6.setX(p6.getX()); lineTo6.setY(p6.getY()); lineTo7.setX(p7.getX()); lineTo7.setY(p7.getY()); } private void layoutForRightSide( Bounds headerBounds, Bounds contentBounds, AbstractDecoration<?> hd) { // // x0 x1 x2 // // y0 +---------------------------+ // | | // y1 | | +--+ // | | | | // | | |h | // | content | | | // | | | | // y2 | | +--+ // | | // | | // | | // | | // y3 +---------------------------+ // // final double x0 = contentBounds.getMinX(); final double x1 = contentBounds.getMaxX(); final double x2 = headerBounds.getMaxX(); final double y0 = contentBounds.getMinY(); final double y1 = headerBounds.getMinY(); final double y2 = headerBounds.getMaxY(); final double y3 = contentBounds.getMaxY(); final boolean snapToPixel = true; final Point2D p0 = hd.sceneGraphObjectToDecoration(x0, y0, snapToPixel); final Point2D p1 = hd.sceneGraphObjectToDecoration(x1, y0, snapToPixel); final Point2D p2 = hd.sceneGraphObjectToDecoration(x1, y1, snapToPixel); final Point2D p3 = hd.sceneGraphObjectToDecoration(x2, y1, snapToPixel); final Point2D p4 = hd.sceneGraphObjectToDecoration(x2, y2, snapToPixel); final Point2D p5 = hd.sceneGraphObjectToDecoration(x1, y2, snapToPixel); final Point2D p6 = hd.sceneGraphObjectToDecoration(x1, y3, snapToPixel); final Point2D p7 = hd.sceneGraphObjectToDecoration(x0, y3, snapToPixel); moveTo0.setX(p0.getX()); moveTo0.setY(p0.getY()); lineTo1.setX(p1.getX()); lineTo1.setY(p1.getY()); lineTo2.setX(p2.getX()); lineTo2.setY(p2.getY()); lineTo3.setX(p3.getX()); lineTo3.setY(p3.getY()); lineTo4.setX(p4.getX()); lineTo4.setY(p4.getY()); lineTo5.setX(p5.getX()); lineTo5.setY(p5.getY()); lineTo6.setX(p6.getX()); lineTo6.setY(p6.getY()); lineTo7.setX(p7.getX()); lineTo7.setY(p7.getY()); } }
37.927746
85
0.56801
9d22f47acf3f0b69f32e01ce08632e81dedc966f
1,492
/* * Copyright (C) 2015 Andrea Binello ("andbin") * * This file is part of the "Java Examples" project and is licensed under the * MIT License. See one of the license files included in the root of the project * for the full text of the license. */ import java.awt.image.RGBImageFilter; public class ColorMaskImageFilter extends RGBImageFilter { public static final int ALPHA_MASK = 0xFF000000; public static final int RED_MASK = 0x00FF0000; public static final int GREEN_MASK = 0x0000FF00; public static final int BLUE_MASK = 0x000000FF; private final int rgbMask; public ColorMaskImageFilter(int rgbMask) { this.rgbMask = rgbMask; // Sets the 'canFilterIndexColorModel' variable in RGBImageFilter class. // A "true" means that this filter does *not* depend on pixel's location // (x/y) and thus the filter can also be applied to images with an // IndexColorModel (with a color table like GIF images). canFilterIndexColorModel = true; } public int filterRGB(int x, int y, int rgb) { return rgb & rgbMask; // Returns the masked color. } // Factory methods to create ColorMaskImageFilter for common cases. public static ColorMaskImageFilter getRedPass() { return new ColorMaskImageFilter(RED_MASK | ALPHA_MASK); } public static ColorMaskImageFilter getGreenPass() { return new ColorMaskImageFilter(GREEN_MASK | ALPHA_MASK); } public static ColorMaskImageFilter getBluePass() { return new ColorMaskImageFilter(BLUE_MASK | ALPHA_MASK); } }
32.434783
80
0.755362
2234fc957abc77181b1c52fa0328f663549fca8f
3,165
/* * Copyright 2017 The Hyve * * 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.radarcns.application; import android.os.Bundle; import android.support.annotation.NonNull; import org.radarcns.android.RadarConfiguration; import org.radarcns.android.device.DeviceServiceProvider; import java.util.Collections; import java.util.List; public class ApplicationServiceProvider extends DeviceServiceProvider<ApplicationState> { private static final String PREFIX = ApplicationServiceProvider.class.getPackage().getName() + '.'; private static final String UPDATE_RATE = "application_status_update_rate"; private static final String TZ_UPDATE_RATE = "application_time_zone_update_rate"; private static final String SEND_IP = "application_send_ip"; private static final long UPDATE_RATE_DEFAULT = 300L; // seconds == 5 minutes private static final long TZ_UPDATE_RATE_DEFAULT = 86400L; // seconds == 1 day private static final String NTP_SERVER_CONFIG = "ntp_server"; static final String SEND_IP_KEY = PREFIX + SEND_IP; static final String UPDATE_RATE_KEY = PREFIX + UPDATE_RATE; static final String TZ_UPDATE_RATE_KEY = PREFIX + TZ_UPDATE_RATE; static final String NTP_SERVER_KEY = PREFIX + NTP_SERVER_CONFIG; @Override public String getDescription() { return getRadarService().getString(R.string.application_status_description); } @Override public Class<?> getServiceClass() { return ApplicationStatusService.class; } @Override public boolean isDisplayable() { return false; } @NonNull @Override public List<String> needsPermissions() { return Collections.emptyList(); } @Override protected void configure(Bundle bundle) { super.configure(bundle); RadarConfiguration config = getConfig(); bundle.putLong(UPDATE_RATE_KEY, config.getLong(UPDATE_RATE, UPDATE_RATE_DEFAULT)); bundle.putString(NTP_SERVER_KEY, config.getString(NTP_SERVER_CONFIG, null)); bundle.putBoolean(SEND_IP_KEY, config.getBoolean(SEND_IP, false)); bundle.putLong(TZ_UPDATE_RATE_KEY, config.getLong(TZ_UPDATE_RATE, TZ_UPDATE_RATE_DEFAULT)); } @Override public String getDisplayName() { return getRadarService().getString(R.string.applicationServiceDisplayName); } @Override @NonNull public String getDeviceProducer() { return "RADAR"; } @Override @NonNull public String getDeviceModel() { return "pRMT"; } @Override @NonNull public String getVersion() { return BuildConfig.VERSION_NAME; } }
32.96875
103
0.727014
100a2cb238742e9a6ad45fe4fafbd7bd44a3bd35
6,077
package org.mtransit.parser.ca_st_albert_transit_bus; import static org.mtransit.commons.StringUtils.EMPTY; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mtransit.commons.CharUtils; import org.mtransit.commons.CleanUtils; import org.mtransit.commons.StringUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.MTLog; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.mt.data.MAgency; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; // https://stalbert.ca/city/transit/tools/open-data-gtfs/ // https://gtfs.edmonton.ca/TMGTFSRealTimeWebService/GTFS/GTFS.zip public class StAlbertTransitBusAgencyTools extends DefaultAgencyTools { public static void main(@NotNull String[] args) { new StAlbertTransitBusAgencyTools().start(args); } @Nullable @Override public List<Locale> getSupportedLanguages() { return LANG_EN; } @NotNull @Override public String getAgencyName() { return "St AT"; } @Override public boolean defaultExcludeEnabled() { return true; } @Nullable @Override public String getAgencyId() { return "2"; // St. Albert Transit } @NotNull @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @Override public boolean defaultRouteIdEnabled() { return true; } @Override public boolean useRouteShortNameForRouteId() { return true; } @Override public boolean defaultRouteLongNameEnabled() { return true; } @Override public boolean defaultAgencyColorEnabled() { return true; } private static final String AGENCY_COLOR_GREEN = "4AA942"; // GREEN (from web site CSS) private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN; @NotNull @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final Pattern STARTS_WITH_A_ = Pattern.compile("(^A)", Pattern.CASE_INSENSITIVE); private static final String STARTS_WITH_A_REPLACEMENT = EMPTY; @NotNull @Override public String cleanStopOriginalId(@NotNull String gStopId) { gStopId = STARTS_WITH_A_.matcher(gStopId).replaceAll(STARTS_WITH_A_REPLACEMENT); return gStopId; } @Override public boolean directionSplitterEnabled() { return true; // ALLOWED } @Override public boolean directionSplitterEnabled(long routeId) { return false; // DISABLED } @Override public boolean directionFinderEnabled() { return true; } private static final Pattern ENDS_WITH_EXPRESS_ = Pattern.compile("( express$)", Pattern.CASE_INSENSITIVE); private static final String ENDS_WITH_EXPRESS_REPLACEMENT = EMPTY; private static final Pattern EDMONTON_ = Pattern.compile("((\\w+) edmonton)", Pattern.CASE_INSENSITIVE); private static final String EDMONTON_REPLACEMENT = CleanUtils.cleanWordsReplacement("$2 Edm"); private static final Pattern STATS_WITH_ST_ALBERT_CTR_ = Pattern.compile("(^(st albert center|st albert centre|st albert ctr) )", Pattern.CASE_INSENSITIVE); @NotNull @Override public String cleanTripHeadsign(@NotNull String tripHeadsign) { tripHeadsign = CleanUtils.toLowerCaseUpperCaseWords(Locale.ENGLISH, tripHeadsign, getIgnoredWords()); tripHeadsign = CleanUtils.keepToAndRemoveVia(tripHeadsign); tripHeadsign = ENDS_WITH_EXPRESS_.matcher(tripHeadsign).replaceAll(ENDS_WITH_EXPRESS_REPLACEMENT); tripHeadsign = EDMONTON_.matcher(tripHeadsign).replaceAll(EDMONTON_REPLACEMENT); tripHeadsign = STATS_WITH_ST_ALBERT_CTR_.matcher(tripHeadsign).replaceAll(EMPTY); tripHeadsign = CleanUtils.SAINT.matcher(tripHeadsign).replaceAll(CleanUtils.SAINT_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_AT.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); tripHeadsign = CleanUtils.cleanBounds(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private String[] getIgnoredWords() { return new String[]{ "TC", }; } private static final Pattern STARTS_WITH_STOP_CODE = Pattern.compile("(" // + "^[0-9]{4,5}[\\s]*-[\\s]*" // + "|" // + "^[A-Z][\\s]*-[\\s]*" // + ")", Pattern.CASE_INSENSITIVE); @NotNull @Override public String cleanStopName(@NotNull String gStopName) { gStopName = CleanUtils.cleanSlashes(gStopName); gStopName = STARTS_WITH_STOP_CODE.matcher(gStopName).replaceAll(EMPTY); gStopName = EDMONTON_.matcher(gStopName).replaceAll(EDMONTON_REPLACEMENT); gStopName = CleanUtils.SAINT.matcher(gStopName).replaceAll(CleanUtils.SAINT_REPLACEMENT); gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = CleanUtils.cleanBounds(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); return CleanUtils.cleanLabel(gStopName); } @NotNull @Override public String getStopCode(@NotNull GStop gStop) { if (StringUtils.isEmpty(gStop.getStopCode()) || "0".equals(gStop.getStopCode())) { //noinspection deprecation return gStop.getStopId(); } return super.getStopCode(gStop); } @Override public int getStopId(@NotNull GStop gStop) { if (CharUtils.isDigitsOnly(gStop.getStopCode())) { return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID } //noinspection deprecation final String stopId = gStop.getStopId(); if (!CharUtils.isDigitsOnly(stopId)) { switch (stopId) { case "A": return 10_000; case "B": return 20_000; case "C": return 30_000; case "D": return 40_000; case "E": return 50_000; case "F": return 60_000; case "G": return 70_000; case "H": return 80_000; case "I": return 90_000; case "J": return 100_000; case "K": return 110_000; } throw new MTLog.Fatal("Unexpected stop ID for %s!", gStop); } return super.getStopId(gStop); } }
28.938095
157
0.75613
6c02053f8d1e40b5a67b73344e401a22b070f17b
6,009
/* * Copyright (c) 2016, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.dva.argus.util; import java.util.Date; import org.apache.commons.lang.exception.ExceptionUtils; import org.quartz.CronScheduleBuilder; import org.quartz.TriggerBuilder; /** * CRON utilities. * * @author Tom Valine (tvaline@salesforce.com) */ public class Cron { //~ Static fields/initializers ******************************************************************************************************************* private static final String ANNUALLY = "@ANNUALLY"; private static final String YEARLY = "@YEARLY"; private static final String MONTHLY = "@MONTHLY"; private static final String WEEKLY = "@WEEKLY"; private static final String DAILY = "@DAILY"; private static final String MIDNIGHT = "@MIDNIGHT"; private static final String HOURLY = "@HOURLY"; //~ Constructors ********************************************************************************************************************************* private Cron() { } //~ Methods ************************************************************************************************************************************** /** * Determines if the given CRON entry is runnable at this current moment in time. This mimics the original implementation of the CRON table. * * <p>This implementation supports only the following types of entries:</p> * * <ol> * <li>Standard Entries having form: &lt;minutes&gt; &lt;hours&gt; &lt;days&gt; &lt;months&gt; &lt;days of week&gt; * * <ul> * <li>* : All</li> * <li>*\/n : Only mod n</li> * <li>n : Numeric</li> * <li>n-n : Range</li> * <li>n,n,...,n : List</li> * <li>n,n-n,...,n : List having ranges</li> * </ul> * </li> * <li>Special Entries * * <ul> * <li>@annually : equivalent to "0 0 1 1 *"</li> * <li>@yearly : equivalent to "0 0 1 1 *"</li> * <li>@monthly : equivalent to "0 0 1 * *"</li> * <li>@weekly : equivalent to "0 0 * * 0"</li> * <li>@daily : equivalent to "0 0 * * *"</li> * <li>@midnight : equivalent to "0 0 * * *"</li> * <li>@hourly : equivalent to "0 * * * *"</li> * </ul> * </li> * </ol> * * @param entry The CRON entry to evaluate. * @param atTime The time at which to evaluate the entry. * * @return true if the the current time is a valid runnable time with respect to the supplied entry. */ public static boolean shouldRun(String entry, Date atTime) { entry = entry.trim().toUpperCase(); if (ANNUALLY.equals(entry) || (YEARLY.equals(entry))) { entry = "0 0 1 1 *"; } else if (MONTHLY.equals(entry)) { entry = "0 0 1 * *"; } else if (WEEKLY.equals(entry)) { entry = "0 0 * * 0"; } else if (DAILY.equals(entry) || (MIDNIGHT.equals(entry))) { entry = "0 0 * * *"; } else if (HOURLY.equals(entry)) { entry = "0 * * * *"; } return new CronTabEntry(entry).isRunnable(atTime); } /** * Indicates if a CRON entry should run at the current moment in time. * * @param entry The CRON entry to evaluate. * * @return true if the the current time is a valid runnable time with respect to the supplied entry. */ public static boolean shouldRun(String entry) { return Cron.shouldRun(entry, new Date()); } /** * Determines if an entry is valid CRON syntax. * * @param entry The CRON entry. * * @return True if the entry is valid CRON syntax. */ public static boolean isValid(String entry) { boolean result = true; try { shouldRun(entry); } catch (Exception ex) { result = false; } return result; } public static boolean isCronEntryValid(String cronEntry) { String quartzCronEntry = convertToQuartzCronEntry(cronEntry); try { // throws runtime exception if the cronEntry is invalid TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(quartzCronEntry)).build(); }catch(Exception e) { return false; } return true; } public static String convertToQuartzCronEntry(String cronEntry) { // adding seconds field cronEntry = "0 " + cronEntry.trim(); // if day of the week is not specified, substitute it with ?, so as to prevent conflict with month field if(cronEntry.charAt(cronEntry.length() - 1) == '*') { return cronEntry.substring(0, cronEntry.length() - 1) + "?"; }else { return cronEntry; } } } /* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
35.556213
147
0.628224
66c8091924da76fad19edbd3d064d2a2e32a4796
356
package com.miget.hxb.repository; import com.miget.hxb.model.ErrorInfo; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; /** * @Description 异常处理 * @Author ErnestCheng * @Date 2017/6/23. */ @Repository public interface ErrorRepository extends MongoRepository<ErrorInfo,Long> { }
22.25
76
0.789326
2e5a1521f99e8e79f414a5fe9f5cb45a4f15be37
572
package com.oxande.vinci.grammar; public enum VinciClass { // A non-yet defined class. Should be only limited in time // This is the type in case we have an assignment without a previous // variable declaration. AUTO, // The following order MUST be followed (from little one to big ones) BOOLEAN, // a boolean (false = 0, true = 1 or, != 0 when explicit conversion) INTEGER, // 32 bits // INT64, // 64 bits FLOAT, // double // NUMERIC, // Big Decimals VOID, // No type OBJECT, // Object STRING, // A String }
27.238095
79
0.629371
29ce74b815acc66e2f47f7c9bb7975278c323099
8,689
package gov.nih.nci.cananolab.restful; import gov.nih.nci.cananolab.restful.synthesis.SynthesisMaterialBO; import gov.nih.nci.cananolab.restful.util.CommonUtil; import gov.nih.nci.cananolab.util.Constants; import gov.nih.nci.cananolab.restful.view.edit.SimpleSynthesisMaterialBean; import gov.nih.nci.cananolab.security.utils.SpringSecurityUtil; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; @Path("synthesisMaterial") public class MaterialsServices { @GET @Path("/setup") @Produces("application/json") public Response setup(@Context HttpServletRequest httpRequest, @DefaultValue("") @QueryParam("sampleId") String sampleId) { try { SynthesisMaterialBO synthesisMaterialBO = (SynthesisMaterialBO) SpringApplicationContext.getBean(httpRequest, "synthesisMaterialBO"); Map<String, Object> dropdownMap = synthesisMaterialBO.setupNew(sampleId, httpRequest); return Response.ok(dropdownMap).header("Access-Control-Allow-Credentials", "true").header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS").header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization").build(); } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(CommonUtil.wrapErrorMessageInList("Error while setting up drop down lists" + e.getMessage())).build(); } } @GET @Path("/edit") @Produces ("application/json") public Response edit(@Context HttpServletRequest httpRequest, @DefaultValue("") @QueryParam("sampleId") String sampleId, @DefaultValue("") @QueryParam("dataId") String dataId) { try { SynthesisMaterialBO synthesisMaterialBO = (SynthesisMaterialBO) SpringApplicationContext.getBean(httpRequest, "synthesisMaterialBO"); if (!SpringSecurityUtil.isUserLoggedIn()) return Response.status(Response.Status.UNAUTHORIZED) .entity("Session expired").build(); SimpleSynthesisMaterialBean synth = synthesisMaterialBO.setupUpdate(sampleId, dataId, httpRequest); List<String> errors = synth.getErrors(); return (errors == null || errors.size() == 0) ? Response.ok(synth).build() : Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errors).build(); } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(CommonUtil.wrapErrorMessageInList("Error while viewing the Synthesis Entity" + e.getMessage())).build(); } } @POST @Path("/saveSynthesisMaterialElement") @Produces ("application/json") public Response saveSynthesisMaterialElement(@Context HttpServletRequest httpRequest, SimpleSynthesisMaterialBean simpleSynthesisMaterialBean) { //TODO - not sure any of this is right. Why am I using SynthesisMaterialBO? try{ SynthesisMaterialBO synthesisMaterialBO = (SynthesisMaterialBO) SpringApplicationContext.getBean(httpRequest, "synthesisMaterialElementBO"); if(!SpringSecurityUtil.isUserLoggedIn()) return Response.status(Response.Status.UNAUTHORIZED).entity("Session expired").build(); SimpleSynthesisMaterialBean synthesisMaterialBean = synthesisMaterialBO.saveMaterialElement(simpleSynthesisMaterialBean, httpRequest); List<String> errors = synthesisMaterialBean.getErrors(); return(errors ==null || errors.size()==0)? Response.ok(synthesisMaterialBean).build(): Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errors).build(); } catch(Exception e){ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity((CommonUtil.wrapErrorMessageInList("Error while saving Synthesis Material Element "+ e.getStackTrace()))).build(); } } @POST @Path("/removeSynthesisMaterialElement") @Produces ("application/json") public Response removeSynthesisMaterialElement(@Context HttpServletRequest httpRequest, SimpleSynthesisMaterialBean simpleSynthesisMaterialBean, String materialElementId) { try{ SynthesisMaterialBO synthesisMaterialBO = (SynthesisMaterialBO) SpringApplicationContext.getBean(httpRequest, "synthesisMaterialBO"); if(!SpringSecurityUtil.isUserLoggedIn()){ return Response.status(Response.Status.UNAUTHORIZED).entity("Session expired").build(); } SimpleSynthesisMaterialBean synthesisMaterialBean= synthesisMaterialBO.removeMaterialElement(simpleSynthesisMaterialBean,materialElementId,httpRequest); List<String> errors = synthesisMaterialBean.getErrors(); return (errors==null || errors.size()==0)? Response.ok(synthesisMaterialBean).build() : Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errors).build(); }catch(Exception e){ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(CommonUtil.wrapErrorMessageInList("Error while removing Material Element "+ e.getMessage())).build(); } } @POST @Path("/saveFile") @Produces ("application/json") public Response saveFile(@Context HttpServletRequest httpRequest, SimpleSynthesisMaterialBean simpleSynthesisMaterialBean) { try { SynthesisMaterialBO synthesisMaterialBO = (SynthesisMaterialBO) SpringApplicationContext.getBean(httpRequest,"synthesisMaterialBO"); if (!SpringSecurityUtil.isUserLoggedIn()) return Response.status(Response.Status.UNAUTHORIZED) .entity(Constants.MSG_SESSION_INVALID).build(); SimpleSynthesisMaterialBean synthesisMaterialBean = synthesisMaterialBO.saveFile(simpleSynthesisMaterialBean,httpRequest); List<String> errors = synthesisMaterialBean.getErrors(); return (errors == null || errors.size() == 0) ? Response.ok(synthesisMaterialBean).build() : Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errors).build(); } catch (Exception e){ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(CommonUtil.wrapErrorMessageInList("Error while saving the File" + e.getMessage())).build(); } } @POST @Path("/removeFile") @Produces ("application/json") public Response removeFile(@Context HttpServletRequest httpRequest, SimpleSynthesisMaterialBean simpleSynthesisMaterialBean) { try{ SynthesisMaterialBO synthesisMaterialBO = (SynthesisMaterialBO) SpringApplicationContext.getBean(httpRequest,"synthesisMaterialBO"); if (!SpringSecurityUtil.isUserLoggedIn()) return Response.status(Response.Status.UNAUTHORIZED) .entity(Constants.MSG_SESSION_INVALID).build(); SimpleSynthesisMaterialBean synthesisMaterialBean = synthesisMaterialBO.removeFile(simpleSynthesisMaterialBean,httpRequest); List<String> errors = synthesisMaterialBean.getErrors(); return (errors == null || errors.size() == 0) ? Response.ok(synthesisMaterialBean).build() : Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errors).build(); }catch (Exception e){ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(CommonUtil.wrapErrorMessageInList("Error while removing the File" + e.getMessage())).build(); } } @POST @Path("/submit") @Produces ("application/json") public Response submit(@Context HttpServletRequest httpRequest, SimpleSynthesisMaterialBean simpleSynthesisMaterialBean) { //TODO write return null; } @POST @Path("/delete") @Produces ("application/json") public Response delete(@Context HttpServletRequest httpRequest, SimpleSynthesisMaterialBean simpleSynthesisMaterialBean) { //TODO write return null; } @POST @Path("/viewDetails") @Produces ("application/json") public Response viewDetails(@Context HttpServletRequest httpRequest, SimpleSynthesisMaterialBean simpleSynthesisMaterialBean) { //TODO write return null; } }
51.414201
324
0.706871
0b0cc0481b6bf21e644c889064bf8eaadf47ddcb
339
package com.lambda.sprint; public abstract class Money { public int amount; //constructor public Money(int amount){ this.amount=amount; } public Money() { this.amount +=1; } //abstract method like in animals public abstract double getValue(); public abstract String getName(); }
17.842105
38
0.625369
faaef9be77cae3d7cc863fd1d159b0b5a167dd2a
1,421
package uk.gov.dwp.queue.triage.web.server.api.status; import uk.gov.dwp.queue.triage.core.client.status.FailedMessageStatusHistoryClient; import uk.gov.dwp.queue.triage.core.client.status.StatusHistoryResponse; import uk.gov.dwp.queue.triage.id.FailedMessageId; import uk.gov.dwp.queue.triage.web.server.w2ui.W2UIResponse; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import java.util.List; import java.util.stream.Collectors; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; @Path("api/failed-messages/status-history/{failedMessageId}") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) public class StatusHistoryResource { private final FailedMessageStatusHistoryClient failedMessageStatusHistoryClient; public StatusHistoryResource(FailedMessageStatusHistoryClient failedMessageStatusHistoryClient) { this.failedMessageStatusHistoryClient = failedMessageStatusHistoryClient; } @POST public W2UIResponse<StatusHistoryListItem> statusHistory(@PathParam("failedMessageId") FailedMessageId failedMessageId) { return W2UIResponse.success(failedMessageStatusHistoryClient.getStatusHistory(failedMessageId) .stream() .map(StatusHistoryListItem::new) .collect(Collectors.toList()) ); } }
36.435897
125
0.770584
e885e051f26dc735f50afeca908e5480290ab48e
256
package com.strandls.user.es.utils; import com.google.inject.AbstractModule; import com.google.inject.Scopes; public class EsUtilModule extends AbstractModule { @Override protected void configure() { bind(EsUtility.class).in(Scopes.SINGLETON); } }
19.692308
50
0.78125
6f1226dd10ae9ed797dc0cdfaa7e0240dd74dc41
2,802
/* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cd.go.authorization.google.models; import cd.go.authorization.google.GoogleApiClient; import cd.go.authorization.google.annotation.ProfileField; import cd.go.authorization.google.utils.Util; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import java.util.List; import java.util.Map; import static cd.go.authorization.google.utils.Util.GSON; public class GoogleConfiguration { private static final String GOOGLE_API_URL = "https://www.googleapis.com"; @Expose @SerializedName("ClientId") @ProfileField(key = "ClientId", required = true, secure = true) private String clientId; @Expose @SerializedName("ClientSecret") @ProfileField(key = "ClientSecret", required = true, secure = true) private String clientSecret; @Expose @SerializedName("AllowedDomains") @ProfileField(key = "AllowedDomains", required = false, secure = false) private String allowedDomains; private GoogleApiClient googleApiClient; public GoogleConfiguration() { } public GoogleConfiguration(String allowedDomains, String clientId, String clientSecret) { this.allowedDomains = allowedDomains; this.clientId = clientId; this.clientSecret = clientSecret; } public List<String> allowedDomains() { return Util.splitIntoLinesAndTrimSpaces(allowedDomains); } public String clientId() { return clientId; } public String clientSecret() { return clientSecret; } public String googleApiUrl() { return GOOGLE_API_URL; } public String toJSON() { return GSON.toJson(this); } public static GoogleConfiguration fromJSON(String json) { return GSON.fromJson(json, GoogleConfiguration.class); } public Map<String, String> toProperties() { return GSON.fromJson(toJSON(), new TypeToken<Map<String, String>>() { }.getType()); } public GoogleApiClient googleApiClient() { if (googleApiClient == null) { googleApiClient = new GoogleApiClient(this); } return googleApiClient; } }
28.886598
93
0.70414
48416c3d67e5b331118d6f86e93e1a5aac918da5
1,446
/* feito por: * José Miguel Pinho Paiva * Universidade de Aveiro */ import java.util.*; import static java.lang.Math.*; public class P12 { public static void main(String[] args) { // variáveis int num, secret, tentativas; char resposta; boolean ng = false; Scanner k = new Scanner(System.in); System.out.println("Jogo do adivinha o número (agora entre 0 e 100)"); System.out.println("-----------------------------------------------"); do { // obtém número secreto secret = (int) (random() * 100.0 + 1); tentativas = 0; // jogo do { System.out.print("\nColoque um número: "); num = k.nextInt(); System.out.println(); if (num > secret) { System.out.printf("O número %d é maior do que o número escolhido.\nTenta outra vez.\n", num); } else if (num < secret) { System.out.printf("O número %d é menor do que o número escolhido.\nTenta outra vez.\n", num); } ++tentativas; } while(num != secret); // menu de reiniciar o jogo System.out.printf("Parabéns, ao fim de %d tentativas conseguiste acertar no número.\n", tentativas); System.out.print("Novo jogo (s/n)? "); resposta = k.next().charAt(0); if (resposta == 's') { ng = true; } else if (resposta == 'n') { ng = false; } else { System.out.print("Resposta não aceitável.\nNovo jogo (s/n)? "); resposta = k.next().charAt(0); } } while (ng); } }
25.821429
103
0.57953
1af644fea314111e6bc627fe22d8af415a6850f9
758
package com.github.jeasyrest.io.handlers; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; public class OutputStreamHandler extends BinaryStreamHandler { @Override public void init(Object sourceObject, Object... sourceParams) throws IOException { super.init(sourceObject, sourceParams); outputStream = (OutputStream) sourceObject; } @Override public Reader getReader() throws IOException { throw new UnsupportedOperationException(); } @Override public Writer getWriter() throws IOException { return new OutputStreamWriter(outputStream, getCharset()); } private OutputStream outputStream; }
25.266667
86
0.734828
3d4c7e5b874c613bba69643e54a01c7887a37548
1,683
package com.vilderlee.design.commandchain; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 类说明: * * <pre> * Modify Information: * Author Date Description * ============ ============= ============================ * VilderLee 2019/7/26 Create this file * </pre> */ @Documented @Inherited @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface RiskCommand { /** * 风控名称 * * @return */ String RiskName(); /** * 风控等级 */ RiskLevelEnum RiskLevel() default RiskLevelEnum.LEVEL_HIGH; /** * 风控优先级 */ int RiskPriority() default 1; enum RiskLevelEnum { LEVEL_HIGH(1, "高等级"), LEVEL_LOW(2, "低等级"); private int value; private String desc; RiskLevelEnum(int value, String desc) { this.value = value; this.desc = desc; } public static RiskLevelEnum getInstance(int value){ for (RiskLevelEnum em : RiskLevelEnum.values()) { if (em.getValue() == value) { return em; } } return null; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } } }
20.777778
63
0.539513
e33d75098eb7b4fc61ed78f85c51c008fa3edb98
1,225
package bt.console.input; import java.util.function.Consumer; /** * Represents an argument that can consume an additional value. * * @author &#8904 */ public class ValueArgument extends Argument<ValueArgument> { protected Consumer<String> action; protected String value; public ValueArgument(String alias, String... aliases) { super(alias, aliases); } /** * Sets the action that is executed if this argument was found during a {@link ArgumentParser#parse(String[]) parse * operation}. The consumed String is the argument value. * * @param action * @return */ public ValueArgument onExecute(Consumer<String> action) { this.action = action; return this; } protected void execute(String value) { this.value = value; this.executed = true; if (this.action != null) { this.action.accept(value); } } /** * @return the value */ public String getValue() { return this.value; } /** * @see Argument#reset() */ @Override protected void reset() { this.executed = false; this.value = null; } }
20.081967
119
0.585306
4fbc9e0af7a845d1f2bb4e9d3730207bb1696bd2
2,763
package cn.felord.wepay.ali.sdk.api.domain; import java.util.Date; import cn.felord.wepay.ali.sdk.api.AlipayObject; import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField; /** * 医院报告明细 * * @author auto create * @version $Id: $Id */ public class MedicalHospitalReportList extends AlipayObject { private static final long serialVersionUID = 3372644547611153544L; /** * 报告产出日期 格式为yyyy-MM-dd HH:mm:ss。 */ @ApiField("report_date") private Date reportDate; /** * 报告说明 */ @ApiField("report_desc") private String reportDesc; /** * 报告详情连接 */ @ApiField("report_link") private String reportLink; /** * 报告名称 */ @ApiField("report_name") private String reportName; /** * 报告类型: CHECK_REPORT 检查报告 EXAM_REPORT检验报告 */ @ApiField("report_type") private String reportType; /** * <p>Getter for the field <code>reportDate</code>.</p> * * @return a {@link java.util.Date} object. */ public Date getReportDate() { return this.reportDate; } /** * <p>Setter for the field <code>reportDate</code>.</p> * * @param reportDate a {@link java.util.Date} object. */ public void setReportDate(Date reportDate) { this.reportDate = reportDate; } /** * <p>Getter for the field <code>reportDesc</code>.</p> * * @return a {@link java.lang.String} object. */ public String getReportDesc() { return this.reportDesc; } /** * <p>Setter for the field <code>reportDesc</code>.</p> * * @param reportDesc a {@link java.lang.String} object. */ public void setReportDesc(String reportDesc) { this.reportDesc = reportDesc; } /** * <p>Getter for the field <code>reportLink</code>.</p> * * @return a {@link java.lang.String} object. */ public String getReportLink() { return this.reportLink; } /** * <p>Setter for the field <code>reportLink</code>.</p> * * @param reportLink a {@link java.lang.String} object. */ public void setReportLink(String reportLink) { this.reportLink = reportLink; } /** * <p>Getter for the field <code>reportName</code>.</p> * * @return a {@link java.lang.String} object. */ public String getReportName() { return this.reportName; } /** * <p>Setter for the field <code>reportName</code>.</p> * * @param reportName a {@link java.lang.String} object. */ public void setReportName(String reportName) { this.reportName = reportName; } /** * <p>Getter for the field <code>reportType</code>.</p> * * @return a {@link java.lang.String} object. */ public String getReportType() { return this.reportType; } /** * <p>Setter for the field <code>reportType</code>.</p> * * @param reportType a {@link java.lang.String} object. */ public void setReportType(String reportType) { this.reportType = reportType; } }
20.316176
67
0.661238
a70fbcc86bf9074304b840a742c83483bffd2de7
478
package com.didi.carmate.dreambox.wrapper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.Map; public interface Monitor { Monitor empty = new Monitor() { @Override public void report(@NonNull String type, @Nullable Map<String, String> params) { } }; /** * 用于上报内部的关键信息,可用于数据监控,(主要用于运行时异常,参数不合法之类问题) */ void report(@NonNull String type, @Nullable Map<String, String> params); }
19.12
88
0.67364
995076eef6f20d82beca43c6a04a07dbd7c8f325
64,209
/******************************************************************************* * Copyright (c) 2004, 2008 Composent, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Composent, Inc. - initial API and implementation * Jacek Pospychala <jacek.pospychala@pl.ibm.com> - bug 192762, 197329, 190851 * Abner Ballardo <modlost@modlost.net> - bug 192756, 199336, 200630 * Jakub Jurkiewicz <jakub.jurkiewicz@pl.ibm.com> - bug 197332 * Hiroyuki Inaba <Hiroyuki <hiroyuki.inaba@gmail.com> - bug 222253 ******************************************************************************/ package org.eclipse.ecf.presence.ui.chatroom; import java.net.URI; import java.net.URISyntaxException; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.ecf.core.IContainerListener; import org.eclipse.ecf.core.events.*; import org.eclipse.ecf.core.identity.*; import org.eclipse.ecf.core.security.ConnectContextFactory; import org.eclipse.ecf.core.user.IUser; import org.eclipse.ecf.core.util.ECFException; import org.eclipse.ecf.internal.presence.ui.*; import org.eclipse.ecf.internal.presence.ui.preferences.PreferenceConstants; import org.eclipse.ecf.internal.ui.actions.SelectProviderAction; import org.eclipse.ecf.presence.*; import org.eclipse.ecf.presence.chatroom.*; import org.eclipse.ecf.presence.im.IChatID; import org.eclipse.ecf.presence.im.IChatMessage; import org.eclipse.ecf.presence.ui.MessagesView; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.*; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.*; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.*; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import org.eclipse.ui.*; import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.progress.IWorkbenchSiteProgressService; public class ChatRoomManagerView extends ViewPart implements IChatRoomInvitationListener { public ChatRoomManagerView() { } //$NON-NLS-1$ private static final String ATSIGN = "@"; //$NON-NLS-1$ public static final String VIEW_ID = "org.eclipse.ecf.presence.ui.chatroom.ChatRoomManagerView"; //$NON-NLS-1$ public static final String PARTICIPANTS_MENU_ID = "org.eclipse.ecf.presence.ui.chatroom.participantsView"; private static final int RATIO_READ_WRITE_PANE = 85; private static final int RATIO_PRESENCE_PANE = 15; protected static final int DEFAULT_INPUT_HEIGHT = 25; protected static final int DEFAULT_INPUT_SEPARATOR = 5; private CTabFolder rootTabFolder = null; private ChatRoomTab rootChannelTab = null; private IChatRoomViewCloseListener rootCloseListener = null; private IChatRoomMessageSender rootMessageSender = null; /** * UI independent renderer, that is aware of displaying any special fragments * of message, like formatting, graphical attachments, emotional content, etc. */ private IMessageRenderer messageRenderer = null; Action outputClear = null; Action outputCopy = null; Action outputPaste = null; Action outputSelectAll = null; boolean rootDisposed = false; private boolean rootEnabled = false; private Hashtable chatRooms = new Hashtable(); private IChatRoomCommandListener commandListener = null; private IChatRoomContainer container = null; private String localUserName = Messages.ChatRoomManagerView_DEFAULT_USER; private String hostName = Messages.ChatRoomManagerView_DEFAULT_HOST; private CTabItem infoTab; private boolean fClearInfoTab = true; class ChatRoomTab { private SashForm fullChat; private CTabItem tabItem; private Composite rightComposite; private StyledText subjectText; private StyledText outputText; private Text inputText; private Label participantsNumberLabel; private TableViewer participantsTable; private Action tabSelectAll; private Action tabCopy; private Action tabClear; private Action tabPaste; private boolean withParticipants; ChatRoomTab(CTabFolder parent, String name) { this(true, parent, name, null); } ChatRoomTab(boolean withParticipantsList, CTabFolder parent, String name, KeyListener keyListener) { withParticipants = withParticipantsList; tabItem = new CTabItem(parent, SWT.NULL); tabItem.setText(name); if (withParticipants) { fullChat = new SashForm(parent, SWT.HORIZONTAL); fullChat.setLayout(new FillLayout()); Composite memberComp = new Composite(fullChat, SWT.NONE); GridLayout layout = new GridLayout(1, true); layout.marginWidth = 0; layout.marginHeight = 0; memberComp.setLayout(layout); participantsNumberLabel = new Label(memberComp, SWT.BORDER | SWT.READ_ONLY); participantsNumberLabel.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false)); participantsNumberLabel.setAlignment(SWT.CENTER); participantsTable = new TableViewer(memberComp, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI); participantsTable.setSorter(new ViewerSorter()); participantsTable.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); participantsTable.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); String user = ((ChatRoomParticipant) selection.getFirstElement()).getName(); if (!ChatRoomManagerView.this.localUserName.equals(user)) { try { MessagesView messagesView = getMessagesView(); messagesView.selectTab(container.getPrivateMessageSender(), null, createStringID(localUserName), createStringID(user), user); getSite().getPage().activate(messagesView); } catch (PartInitException e) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.ChatRoomManagerView_EXCEPTION_MESSAGE_VIEW_INITIALIZATION, user), e)); } } } }); rightComposite = new Composite(fullChat, SWT.NONE); layout = new GridLayout(1, true); layout.marginHeight = 0; layout.marginWidth = 0; rightComposite.setLayout(layout); subjectText = createStyledTextWidget(rightComposite, SWT.SINGLE | SWT.BORDER); subjectText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); /* * The sendSubjectChange method in Smack 2.2.1 does not seem to be working correctly, so this whole block * can be temporily removed. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=223560 subjectText.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { if (evt.character == SWT.CR || evt.character == SWT.KEYPAD_CR) { ChatRoom chatroom = (ChatRoom) chatRooms.get(tabItem.getText()); if (chatroom != null) { IChatRoomAdminSender chatRoomAdminSender = chatroom.chatRoomContainer.getChatRoomAdminSender(); try { if (chatRoomAdminSender != null) { chatRoomAdminSender.sendSubjectChange(subjectText.getText()); } } catch (ECFException e) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, "sendSubjectChange", e));disconnected(); //$NON-NLS-1$ } } } } }); */ subjectText.setEditable(false); subjectText.setEnabled(false); } else { rightComposite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(1, true); layout.marginHeight = 0; layout.marginWidth = 0; rightComposite.setLayout(layout); } outputText = createStyledTextWidget(rightComposite, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI | SWT.READ_ONLY); outputText.setEditable(false); outputText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); inputText = new Text(rightComposite, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false); GC gc = new GC(inputText); gc.setFont(inputText.getFont()); FontMetrics fontMetrics = gc.getFontMetrics(); gc.dispose(); gd.heightHint = fontMetrics.getHeight() * 2; inputText.setLayoutData(gd); if (keyListener != null) inputText.addKeyListener(keyListener); if (withParticipants) { fullChat.setWeights(new int[] { RATIO_PRESENCE_PANE, RATIO_READ_WRITE_PANE }); tabItem.setControl(fullChat); } else tabItem.setControl(rightComposite); parent.setSelection(tabItem); makeActions(); hookContextMenu(); if (withParticipants) { hookParticipantsContextMenu(); } StyledText st = getOutputText(); if (st != null) { ScrollBar vsb = st.getVerticalBar(); if (vsb != null) { vsb.addSelectionListener(scrollSelectionListener); vsb.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { StyledText ot = getOutputText(); if (ot != null) { ScrollBar sb = ot.getVerticalBar(); if (sb != null) sb.removeSelectionListener(scrollSelectionListener); } } }); } } } private SelectionListener scrollSelectionListener = new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { if (!isLastOutputInvisible(getOutputText())) { makeTabItemNormal(); } } }; protected void makeTabItemBold() { changeTabItem(true); } protected void makeTabItemNormal() { changeTabItem(false); } protected void changeTabItem(boolean bold) { CTabItem item = tabItem; Font oldFont = item.getFont(); FontData[] fd = oldFont.getFontData(); item.setFont(new Font(oldFont.getDevice(), fd[0].getName(), fd[0].getHeight(), (bold) ? SWT.BOLD : SWT.NORMAL)); } private StyledText createStyledTextWidget(Composite parent, int styles) { SourceViewer result = null; try { result = new SourceViewer(parent, null, null, true, styles); } catch (NoClassDefFoundError e) { Activator.getDefault().getLog().log(new Status(IStatus.WARNING, Activator.PLUGIN_ID, IStatus.WARNING, Messages.ChatRoomManagerView_WARNING_HYPERLINKING_NOT_AVAILABLE, e)); return new StyledText(parent, styles); } result.configure(new ChatRoomViewerConfiguration(EditorsUI.getPreferenceStore(), container, ChatRoomManagerView.this)); result.setDocument(new Document()); return result.getTextWidget(); } protected void outputClear() { if (MessageDialog.openConfirm(null, Messages.ChatRoomManagerView_CONFIRM_CLEAR_TEXT_OUTPUT_TITLE, Messages.ChatRoomManagerView_CONFIRM_CLEAR_TEXT_OUTPUT_MESSAGE)) { //$NON-NLS-1$ outputText.setText(//$NON-NLS-1$ ""); } } protected void outputCopy() { String t = outputText.getSelectionText(); if (t == null || t.length() == 0) { outputText.selectAll(); } outputText.copy(); outputText.setSelection(outputText.getText().length()); } private void fillContextMenu(IMenuManager manager) { manager.add(tabCopy); manager.add(tabPaste); manager.add(tabClear); manager.add(new Separator()); manager.add(tabSelectAll); manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } private void hookContextMenu() { MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { fillContextMenu(manager); } }); Menu menu = menuMgr.createContextMenu(outputText); outputText.setMenu(menu); ISelectionProvider selectionProvider = new ISelectionProvider() { public void addSelectionChangedListener(ISelectionChangedListener listener) { // do nothing } public ISelection getSelection() { ISelection selection = new TextSelection(outputText.getSelectionRange().x, outputText.getSelectionRange().y); return selection; } public void removeSelectionChangedListener(ISelectionChangedListener listener) { // do nothing } public void setSelection(ISelection selection) { if (selection instanceof ITextSelection) { ITextSelection textSelection = (ITextSelection) selection; outputText.setSelection(textSelection.getOffset(), textSelection.getOffset() + textSelection.getLength()); } } }; getSite().registerContextMenu(menuMgr, selectionProvider); } private void hookParticipantsContextMenu() { MenuManager menuMgr = new MenuManager(); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } }); menuMgr.setRemoveAllWhenShown(true); Control control = participantsTable.getControl(); Menu menu = menuMgr.createContextMenu(control); control.setMenu(menu); getSite().registerContextMenu(PARTICIPANTS_MENU_ID, menuMgr, participantsTable); } private void makeActions() { tabSelectAll = new Action() { public void run() { outputText.selectAll(); } }; tabSelectAll.setText(Messages.ChatRoomManagerView_SELECT_ALL_TEXT); tabSelectAll.setToolTipText(Messages.ChatRoomManagerView_SELECT_ALL_TOOLTIP); tabSelectAll.setAccelerator(SWT.CTRL | 'A'); tabCopy = new Action() { public void run() { outputCopy(); } }; tabCopy.setText(Messages.ChatRoomManagerView_COPY_TEXT); tabCopy.setToolTipText(Messages.ChatRoomManagerView_COPY_TOOLTIP); tabCopy.setAccelerator(SWT.CTRL | 'C'); tabCopy.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_COPY)); tabClear = new Action() { public void run() { outputClear(); } }; tabClear.setText(Messages.ChatRoomManagerView_CLEAR_TEXT); tabClear.setToolTipText(Messages.ChatRoomManagerView_CLEAR_TOOLTIP); tabPaste = new Action() { public void run() { getInputText().paste(); } }; tabPaste.setText(Messages.ChatRoomManagerView_PASTE_TEXT); tabPaste.setToolTipText(Messages.ChatRoomManagerView_PASTE_TOOLTIP); tabPaste.setAccelerator(SWT.CTRL | 'V'); tabPaste.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_PASTE)); } protected Text getInputText() { return inputText; } protected void setKeyListener(KeyListener listener) { if (listener != null) inputText.addKeyListener(listener); } protected Label getParticipantsLabel() { return participantsNumberLabel; } protected TableViewer getParticipantsViewer() { return participantsTable; } /** * @return the <tt>StyledText</tt> widget that is displaying the output of the chatroom */ public StyledText getOutputText() { return outputText; } public void setSubject(String subject) { subjectText.setText(subject); } } public void createPartControl(Composite parent) { Composite rootComposite = new Composite(parent, SWT.NONE); rootComposite.setLayout(new FillLayout()); boolean useTraditionalTabFolder = PlatformUI.getPreferenceStore().getBoolean(IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS); rootTabFolder = new CTabFolder(rootComposite, SWT.NORMAL | SWT.CLOSE); rootTabFolder.setUnselectedCloseVisible(false); rootTabFolder.setSimple(useTraditionalTabFolder); //$NON-NLS-1$ populateInfoTab(getInfoTabControl(SWT.NONE, "Info", true)); PlatformUI.getPreferenceStore().addPropertyChangeListener(new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS) && !rootTabFolder.isDisposed()) { rootTabFolder.setSimple(((Boolean) event.getNewValue()).booleanValue()); rootTabFolder.redraw(); } } }); rootTabFolder.addCTabFolder2Listener(new CTabFolder2Adapter() { public void close(CTabFolderEvent event) { event.doit = closeTabItem((CTabItem) event.item); } }); } /** * This enables IM providers to provide additional information about the provider by asking the creation of a separate information tab. This information is displayed in a separate info tab. * * @param style with additional information about the provider * @param title * @param clearInfoTab set to true if the tab must be cleared when population of the view begins. * @return the Composite to draw on * @since 2.2 */ public Composite getInfoTabControl(int style, String title, boolean clearInfoTab) { // dispose old tab if (infoTab != null) infoTab.dispose(); CTabItem tab = new CTabItem(rootTabFolder, style); tab.setText(title); // assign new tab this.infoTab = tab; this.fClearInfoTab = clearInfoTab; Composite parent = new Composite(rootTabFolder, SWT.NONE); parent.setLayout(new FillLayout()); tab.setControl(parent); rootTabFolder.setSelection(tab); return parent; } /** * Creates a tab with view information. This view does nothing when it is opened manually. This tab is used to provide that information. */ private void populateInfoTab(Composite parent) { Link link = new Link(parent, SWT.NONE); //$NON-NLS-1$ link.setText("\n This view is not intended to be opened as a standalone view. Please select one of the <a>IM Providers</a> to open a populated view."); link.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { SelectProviderAction action = new SelectProviderAction(); action.init(ChatRoomManagerView.this.getSite().getWorkbenchWindow()); action.run(null); } }); } private boolean closeTabItem(CTabItem tabItem) { ChatRoom chatRoom = findChatRoomForTabItem(tabItem); if (chatRoom == null) { return true; } if (MessageDialog.openQuestion(getSite().getShell(), Messages.ChatRoomManagerView_CLOSE_CHAT_ROOM_TITLE, NLS.bind(Messages.ChatRoomManagerView_CLOSE_CHAT_ROOM_MESSAGE, tabItem.getText()))) { chatRoom.chatRoomDisconnect(); return true; } return false; } public IChatRoomContainer getRootChatRoomContainer() { return container; } /** * @return a list of IChatRoomContainer for each open channel * or an empty array if there are no channels open. * @since 2.1 */ public IChatRoomContainer[] getChatRoomContainers() { List containers = new ArrayList(chatRooms.size()); for (Iterator i = chatRooms.values().iterator(); i.hasNext(); ) { ChatRoom cr = (ChatRoom) i.next(); if (cr.chatRoomContainer != null) { containers.add(cr.chatRoomContainer); } } return (IChatRoomContainer[]) containers.toArray(new IChatRoomContainer[containers.size()]); } /** * @return chat room container of currently selected tab or null if none found. */ public IChatRoomContainer getActiveChatRoomContainer() { CTabItem selection = rootTabFolder.getSelection(); if (selection != null) { ChatRoom chatRoom = findChatRoomForTabItem(selection); if (chatRoom != null) { return chatRoom.chatRoomContainer; } } return null; } private ChatRoom findChatRoomForTabItem(CTabItem tabItem) { for (Iterator i = chatRooms.values().iterator(); i.hasNext(); ) { ChatRoom cr = (ChatRoom) i.next(); if (tabItem == cr.chatRoomTab.tabItem) return cr; } return null; } private Text getRootTextInput() { if (rootChannelTab == null) return null; return rootChannelTab.getInputText(); } private StyledText getRootTextOutput() { if (rootChannelTab == null) return null; return rootChannelTab.getOutputText(); } public void initializeWithoutManager(String username, String hostname, final IChatRoomCommandListener commandListener1, final IChatRoomViewCloseListener closeListener) { initializeWithManager(username, hostname, null, commandListener1, closeListener); } public void initializeWithManager(String localUserName1, String hostName1, final IChatRoomContainer rootChatRoomContainer, final IChatRoomCommandListener commandListener1, final IChatRoomViewCloseListener closeListener) { // We get populated, remove the info tab if requested if (infoTab != null && fClearInfoTab && !(infoTab.isDisposed())) { infoTab.getControl().dispose(); infoTab.dispose(); infoTab = null; } ChatRoomManagerView.this.localUserName = (localUserName1 == null) ? Messages.ChatRoomManagerView_DEFAULT_USER : localUserName1; ChatRoomManagerView.this.hostName = (hostName1 == null) ? Messages.ChatRoomManagerView_DEFAULT_HOST : hostName1; ChatRoomManagerView.this.rootCloseListener = closeListener; ChatRoomManagerView.this.commandListener = commandListener1; String viewTitle = localUserName1 + ATSIGN + hostName1; ChatRoomManagerView.this.setPartName(NLS.bind(Messages.ChatRoomManagerView_VIEW_TITLE, viewTitle)); ChatRoomManagerView.this.setTitleToolTip(Messages.ChatRoomManagerView_VIEW_TITLE_HOST_PREFIX + ChatRoomManagerView.this.hostName); if (rootChatRoomContainer != null) { ChatRoomManagerView.this.container = rootChatRoomContainer; ChatRoomManagerView.this.rootMessageSender = rootChatRoomContainer.getChatRoomMessageSender(); rootChannelTab = new ChatRoomTab(false, rootTabFolder, ChatRoomManagerView.this.hostName, new KeyListener() { public void keyPressed(KeyEvent evt) { handleKeyPressed(evt); } public void keyReleased(KeyEvent evt) { // do nothing } }); makeActions(); hookContextMenu(); if (rootChatRoomContainer.getConnectedID() == null) { StyledText outputText = getRootTextOutput(); if (!outputText.isDisposed()) outputText.setText(new SimpleDateFormat(Messages.ChatRoomManagerView_CONNECT_DATE_TIME_FORMAT).format(new Date()) + NLS.bind(Messages.ChatRoomManagerView_CONNECT_MESSAGE, viewTitle)); } } setEnabled(false); } public void setEnabled(boolean enabled) { this.rootEnabled = enabled; Text inputText = getRootTextInput(); if (inputText != null && !inputText.isDisposed()) inputText.setEnabled(enabled); } public boolean isEnabled() { return rootEnabled; } protected void clearInput() { Text textInput = getRootTextInput(); if (textInput != null) //$NON-NLS-1$ textInput.setText(""); } public void sendMessageLine(String line) { try { if (rootMessageSender != null) rootMessageSender.sendMessage(line); } catch (ECFException e) { removeLocalUser(); } } public void disconnected() { Display.getDefault().asyncExec(new Runnable() { public void run() { if (rootDisposed) return; setEnabled(false); setPartName(NLS.bind(Messages.ChatRoomManagerView_VIEW_DISABLED_NAME, getPartName())); } }); } protected CTabItem getTabItem(String targetName) { CTabItem[] items = rootTabFolder.getItems(); for (int i = 0; i < items.length; i++) { if (items[i].getText().equals(targetName)) { return items[i]; } } return null; } protected void doJoinRoom(final IChatRoomInfo roomInfo, final String password) { final ID targetRoomID = roomInfo.getRoomID(); final String targetRoomName = targetRoomID.getName(); // first, check to see if we already have it open. If so just activate ChatRoom room = (ChatRoom) chatRooms.get(targetRoomName); if (room != null && room.isConnected()) { room.setSelected(); return; } // Then we create a new chatRoomContainer from the roomInfo try { final IChatRoomContainer chatRoomContainer = roomInfo.createChatRoomContainer(); // Setup new user interface (new tab) final ChatRoom chatroom = new ChatRoom(chatRoomContainer, new ChatRoomTab(rootTabFolder, targetRoomName)); // setup message listener chatRoomContainer.addMessageListener(new IIMMessageListener() { public void handleMessageEvent(IIMMessageEvent messageEvent) { if (messageEvent instanceof IChatRoomMessageEvent) { IChatRoomMessage m = ((IChatRoomMessageEvent) messageEvent).getChatRoomMessage(); chatroom.handleMessage(m.getFromID(), m.getMessage()); } } }); // setup participant listener chatRoomContainer.addChatRoomParticipantListener(new IChatRoomParticipantListener() { public void handlePresenceUpdated(ID fromID, IPresence presence) { chatroom.handlePresence(fromID, presence); } public void handleArrived(IUser participant) { // do nothing } public void handleUpdated(IUser updatedParticipant) { // do nothing } public void handleDeparted(IUser participant) { // do nothing } }); chatRoomContainer.addListener(new IContainerListener() { public void handleEvent(IContainerEvent evt) { if (evt instanceof IContainerDisconnectedEvent || evt instanceof IContainerEjectedEvent) { chatroom.disconnected(); } } }); // Now connect/join Display.getDefault().asyncExec(new Runnable() { public void run() { try { chatRoomContainer.connect(targetRoomID, ConnectContextFactory.createPasswordConnectContext(password)); chatRooms.put(targetRoomName, chatroom); } catch (Exception e) { MessageDialog.openError(getSite().getShell(), "Connect Error", NLS.bind("Could not connect to {0}.\n\nError is {1}.", targetRoomName, e.getLocalizedMessage())); } } }); } catch (Exception e) { MessageDialog.openError(getSite().getShell(), "Container Create Error", NLS.bind("Could not create chatRoomContainer for {0}.\n\nError is {1}.", targetRoomName, e.getLocalizedMessage())); } } class ChatRoom implements IChatRoomInvitationListener, KeyListener { private IChatRoomContainer chatRoomContainer; private ChatRoomTab chatRoomTab; private IChatRoomMessageSender chatRoomMessageSender; private IUser localUser; private Label chatRoomParticipantsLabel; private TableViewer chatRoomParticipantViewer = null; /** * A list of available nicknames for nickname completion via the 'tab' * key. */ private ArrayList options; /** * Denotes the number of options that should be available for the user * to cycle through when pressing the 'tab' key to perform nickname * completion. The default value is set to 5. */ private int maximumCyclingOptions = 5; /** * The length of a nickname's prefix that has already been typed in by * the user. This is used to remove the beginning part of the available * nickname choices. */ private int prefixLength; /** * The index of the next nickname to select from {@link #options}. */ private int choice = 0; /** * The length of the user's nickname that remains resulting from * subtracting the nickname's length from the prefix that the user has * keyed in already. */ private int nickRemainder; /** * The caret position when the user first started * cycling through nickname completion options. */ private int caret; /** * The character to enter after the user's nickname has been * autocompleted. The default value is a colon (':'). */ private char nickCompletionSuffix = ':'; /** * Indicates whether the user is currently cycling over the list of * nicknames for nickname completion. */ private boolean isCycling = false; /** * Check to see whether the user is currently starting the line of text * with a nickname at the beginning of the message. This determines * whether {@link #nickCompletionSuffix} should be inserted when * performing autocompletion. If the user is not at the beginning of the * message, it is likely that the user is typing another user's name to * reference that person and not to direct the message to said person, * as such, the <code>nickCompletionSuffix</code> does not need to be * appended. */ private boolean isAtStart = false; private CTabItem itemSelected = null; private Text getInputText() { return chatRoomTab.getInputText(); } private StyledText getOutputText() { return chatRoomTab.getOutputText(); } ChatRoom(IChatRoomContainer container, ChatRoomTab tabItem) { Assert.isNotNull(container); Assert.isNotNull(tabItem); this.chatRoomContainer = container; this.chatRoomMessageSender = container.getChatRoomMessageSender(); this.chatRoomTab = tabItem; options = new ArrayList(); this.chatRoomTab.setKeyListener(this); this.chatRoomParticipantsLabel = tabItem.getParticipantsLabel(); this.chatRoomParticipantViewer = tabItem.getParticipantsViewer(); chatRoomContainer.addChatRoomAdminListener(new IChatRoomAdminListener() { public void handleSubjectChange(ID from, final String newSubject) { if (!chatRoomTab.getInputText().isDisposed()) { chatRoomTab.getInputText().getDisplay().asyncExec(new Runnable() { public void run() { chatRoomTab.setSubject(newSubject); } }); } } }); rootTabFolder.setUnselectedCloseVisible(true); rootTabFolder.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { itemSelected = (CTabItem) e.item; if (itemSelected == chatRoomTab.tabItem) makeTabItemNormal(); if (rootChannelTab != null && itemSelected == rootChannelTab.tabItem) rootChannelTab.makeTabItemNormal(); } }); StyledText st = getOutputText(); if (st != null) { ScrollBar vsb = st.getVerticalBar(); if (vsb != null) { vsb.addSelectionListener(scrollSelectionListener); vsb.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { StyledText ot = getOutputText(); if (ot != null) { ScrollBar vb = ot.getVerticalBar(); if (vb != null) vb.removeSelectionListener(scrollSelectionListener); } } }); } } } private SelectionListener scrollSelectionListener = new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { if (!isLastOutputInvisible(getOutputText())) { makeTabItemNormal(); } } }; protected void makeTabItemBold() { changeTabItem(true); } protected void makeTabItemNormal() { changeTabItem(false); } protected void changeTabItem(boolean bold) { CTabItem item = chatRoomTab.tabItem; Font oldFont = item.getFont(); FontData[] fd = oldFont.getFontData(); item.setFont(new Font(oldFont.getDevice(), fd[0].getName(), fd[0].getHeight(), (bold) ? SWT.BOLD : SWT.NORMAL)); } public void handleMessage(final ID fromID, final String messageBody) { Display.getDefault().asyncExec(new Runnable() { public void run() { if (rootDisposed) return; appendText(chatRoomTab, getOutputText(), new ChatLine(messageBody, new ChatRoomParticipant(fromID))); } }); } public void handleInvitationReceived(ID roomID, ID from, String subject, String body) { // XXX TODO show UI for invitation } public void keyPressed(KeyEvent e) { handleKeyPressed(e); } public void keyReleased(KeyEvent e) { handleKeyReleased(e); } protected void handleKeyPressed(KeyEvent evt) { Text inputText = getInputText(); if (evt.character == SWT.CR) { if (inputText.getText().trim().length() > 0) handleTextInput(inputText.getText()); clearInput(); makeTabItemNormal(); if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.PREFERENCES_SCROLLONINPUT)) scrollToEnd(getOutputText()); evt.doit = false; isCycling = false; } else if (evt.character == SWT.TAB) { // don't propogate the event upwards and insert a tab character evt.doit = false; int pos = inputText.getCaretPosition(); // if the user is at the beginning of the line, do nothing if (pos == 0) return; String text = inputText.getText(); // available nicknames if (isCycling) { // if everything's been cycled over, start over at zero if (choice == options.size()) { choice = 0; } //$NON-NLS-1$ //$NON-NLS-2$ String append = ((String) options.get(choice++)) + (isAtStart ? nickCompletionSuffix + " " : " "); // remove the previous completion proposal and insert the new one inputText.setText(text.substring(0, caret - prefixLength) + append + text.substring(caret + nickRemainder)); // subtract the prefix so we remember where we were originally nickRemainder = append.length() - prefixLength; // set the caret position to be the place where the nickname // completion ended inputText.setSelection(caret + nickRemainder); } else { // the user is not cycling, so we need to identify what the // user has typed based on the current caret position int count = pos - 1; // the beginning of the message has been reached while (count > -1 && !Character.isWhitespace(text.charAt(count))) { count--; } count++; // remove all previous options options.clear(); // get the prefix that the user typed as a lowercase string String prefix = text.substring(count, pos).toLowerCase(); isAtStart = count == 0; // if what's found was actually whitespace, do nothing if (//$NON-NLS-1$ prefix.trim().equals(//$NON-NLS-1$ "")) { return; } // get all of the users in this room and store them if they // start with the prefix that the user has typed TableItem[] participants = chatRoomParticipantViewer.getTable().getItems(); for (int i = 0; i < participants.length; i++) { String name = participants[i].getText(); // do a lowercase comparison because we should display options that differ in casing if (name.toLowerCase().startsWith(prefix)) { options.add(name); } } // simply return if no matches have been found if (options.isEmpty()) return; prefixLength = prefix.length(); if (options.size() == 1) { String nickname = (String) options.get(0); // since only one nickname is available, we'll select // the prefix that has been entered and then replace it // with the nickname option inputText.setSelection(pos - prefixLength, pos); //$NON-NLS-1$ //$NON-NLS-2$ inputText.insert(nickname + (isAtStart ? nickCompletionSuffix + " " : " ")); } else if (options.size() <= maximumCyclingOptions) { // note that the user is currently cycling through // options and also store the current caret position isCycling = true; caret = pos; choice = 0; // insert the nickname after removing the prefix //$NON-NLS-1$ //$NON-NLS-2$ String nickname = options.get(choice++) + (isAtStart ? nickCompletionSuffix + " " : " "); // select the prefix of the proposal inputText.setSelection(pos - prefixLength, pos); // and then replace it with a proposal inputText.insert(nickname); // store the length of this truncated nickname so that // it can be removed when the user is cycling nickRemainder = nickname.length() - prefixLength; } else { // as there are too many choices for the user to pick // from, simply display all of the available ones on the // chat window so that the user can get a visual // indicator of what's available and narrow down the // choices by typing a few more additional characters StringBuffer choices = new StringBuffer(); synchronized (choices) { for (int i = 0; i < options.size(); i++) { choices.append(options.get(i)).append(' '); } choices.delete(choices.length() - 1, choices.length()); } appendText(chatRoomTab, getOutputText(), new ChatLine(choices.toString())); } } } else { // remove the cycling marking for any other key pressed isCycling = false; } } protected void handleKeyReleased(KeyEvent evt) { if (evt.character == SWT.TAB) { // don't move to the next widget or try to add tabs evt.doit = false; } } protected void handleTextInput(String text) { if (chatRoomMessageSender == null) { MessageDialog.openError(getViewSite().getShell(), Messages.ChatRoomManagerView_NOT_CONNECTED_TITLE, Messages.ChatRoomManagerView_NOT_CONNECTED_MESSAGE); return; } String output = processForCommand(chatRoomContainer, text); if (output != null) sendMessageLine(output); } protected void chatRoomDisconnect() { if (chatRoomContainer != null) chatRoomContainer.disconnect(); } protected void clearInput() { //$NON-NLS-1$ getInputText().setText(""); } protected void sendMessageLine(String line) { try { chatRoomMessageSender.sendMessage(line); } catch (ECFException e) { disconnected(); } } public void handlePresence(final ID fromID, final IPresence presence) { Display.getDefault().asyncExec(new Runnable() { public void run() { if (rootDisposed) return; boolean isAdd = presence.getType().equals(IPresence.Type.AVAILABLE); ChatRoomParticipant p = new ChatRoomParticipant(fromID); if (isAdd) { if (localUser == null) localUser = p; addParticipant(p); } else removeParticipant(p); } }); } public void disconnected() { Display.getDefault().asyncExec(new Runnable() { public void run() { if (rootDisposed) return; Text inputText = getInputText(); if (!inputText.isDisposed()) inputText.setEnabled(false); } }); } protected boolean isConnected() { Text inputText = getInputText(); return !inputText.isDisposed() && inputText.isEnabled(); } protected void setSelected() { rootTabFolder.setSelection(chatRoomTab.tabItem); } protected void addParticipant(IUser p) { if (p != null) { ID id = p.getID(); if (id != null) { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); if (store.getBoolean(PreferenceConstants.CHATROOM_SHOW_USER_PRESENCE)) appendText(chatRoomTab, getOutputText(), new ChatLine(NLS.bind(Messages.ChatRoomManagerView_ENTERED_MESSAGE, getUsernameFromID(id)), null)); chatRoomParticipantViewer.add(p); chatRoomParticipantsLabel.setText(NLS.bind(Messages.ChatRoomManagerView_USERS_IN_CHAT_ROOM, String.valueOf(chatRoomContainer.getChatRoomParticipants().length))); } } } protected boolean isLocalUser(ID id) { if (localUser == null) return false; else if (localUser.getID().equals(id)) return true; else return false; } protected void removeLocalUser() { // It's us that's gone away... so we're outta here String title = getPartName(); setPartName(NLS.bind(Messages.ChatRoomManagerView_VIEW_DISABLED_NAME, title)); removeAllParticipants(); disconnect(); setEnabled(false); } protected void removeParticipant(IUser p) { if (p != null) { ID id = p.getID(); if (id != null) { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); if (store.getBoolean(PreferenceConstants.CHATROOM_SHOW_USER_PRESENCE)) appendText(chatRoomTab, getOutputText(), new ChatLine(NLS.bind(Messages.ChatRoomManagerView_LEFT_MESSAGE, getUsernameFromID(id)), null)); chatRoomParticipantViewer.remove(p); chatRoomParticipantsLabel.setText(NLS.bind(Messages.ChatRoomManagerView_USERS_IN_CHAT_ROOM, String.valueOf(chatRoomContainer.getChatRoomParticipants().length))); } } } protected void removeAllParticipants() { Table t = chatRoomParticipantViewer.getTable(); for (int i = 0; i < t.getItemCount(); i++) { Object o = chatRoomParticipantViewer.getElementAt(i); if (o != null) chatRoomParticipantViewer.remove(o); } chatRoomParticipantsLabel.setText(NLS.bind(Messages.ChatRoomManagerView_USERS_IN_CHAT_ROOM, String.valueOf(chatRoomContainer.getChatRoomParticipants().length))); } } protected void handleTextInput(String text) { if (rootMessageSender == null) { MessageDialog.openError(getViewSite().getShell(), Messages.ChatRoomManagerView_NOT_CONNECTED_TITLE, Messages.ChatRoomManagerView_NOT_CONNECTED_MESSAGE); } else { String output = processForCommand(null, text); if (output != null) sendMessageLine(output); } } protected String processForCommand(IChatRoomContainer chatRoomContainer, String text) { IChatRoomCommandListener l = commandListener; if (l != null) return l.handleCommand(chatRoomContainer, text); return text; } protected void handleEnter() { Text inputText = getRootTextInput(); if (inputText.getText().trim().length() > 0) handleTextInput(inputText.getText()); clearInput(); scrollToEnd(getRootTextOutput()); if (rootChannelTab != null) rootChannelTab.makeTabItemNormal(); } protected void handleKeyPressed(KeyEvent evt) { if (evt.character == SWT.CR) { handleEnter(); evt.doit = false; } } public void setFocus() { Text text = getRootTextInput(); if (text != null) text.setFocus(); } public void joinRoom(final IChatRoomInfo info, final String password) { Display.getDefault().syncExec(new Runnable() { public void run() { if (rootDisposed) return; doJoinRoom(info, password); } }); } public void dispose() { disconnect(); rootDisposed = true; super.dispose(); } protected String getMessageString(ID fromID, String text) { return NLS.bind(Messages.ChatRoomManagerView_MESSAGE, fromID.getName(), text); } private ID createStringID(String str) { try { return IDFactory.getDefault().createStringID(str); } catch (IDCreateException e) { } return null; } private MessagesView getMessagesView() throws PartInitException { IWorkbenchPage page = getSite().getPage(); MessagesView messageView = (MessagesView) page.findView(MessagesView.VIEW_ID); if (messageView == null) { messageView = (MessagesView) page.showView(MessagesView.VIEW_ID, null, IWorkbenchPage.VIEW_CREATE); } return messageView; } /** * A delegate method to handle chat messages. * @param message the chat message that has been received * @since 1.1 */ public void handleChatMessage(final IChatMessage message) { Display.getDefault().asyncExec(new Runnable() { public void run() { try { ID targetID = createStringID(localUserName); MessagesView messageView = getMessagesView(); IWorkbenchSiteProgressService service = (IWorkbenchSiteProgressService) messageView.getSite().getAdapter(IWorkbenchSiteProgressService.class); if (container.getPrivateMessageSender() != null) { messageView.openTab(container.getPrivateMessageSender(), null, targetID, message.getFromID(), new ChatRoomParticipant(targetID).getNickname()); messageView.showMessage(message); service.warnOfContentChange(); } } catch (Exception e) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.ChatRoomManagerView_EXCEPTION_MESSAGE_VIEW_INITIALIZATION + message.getFromID(), e)); } } }); } public void handleMessage(final ID fromID, final String messageBody) { Display.getDefault().asyncExec(new Runnable() { public void run() { if (rootDisposed) return; if (rootChannelTab != null) { appendText(rootChannelTab, getRootTextOutput(), new ChatLine(messageBody, new ChatRoomParticipant(fromID))); rootChannelTab.makeTabItemBold(); } } }); } /** * @return String username for given <code>targetID</code> */ public static String getUsernameFromID(ID targetID) { IChatID chatID = (IChatID) targetID.getAdapter(IChatID.class); if (chatID != null) return chatID.getUsername(); try { URI uri = new URI(targetID.getName()); String user = uri.getUserInfo(); return user == null ? targetID.getName() : user; } catch (URISyntaxException e) { String userAtHost = targetID.getName(); int atIndex = userAtHost.lastIndexOf(ATSIGN); if (atIndex != -1) userAtHost = userAtHost.substring(0, atIndex); return userAtHost; } } /** * @return String hostname for given <code>targetID</code> */ public static String getHostnameFromID(ID targetID) { IChatID chatID = (IChatID) targetID.getAdapter(IChatID.class); if (chatID != null) return chatID.getHostname(); try { URI uri = new URI(targetID.getName()); String host = uri.getHost(); return host == null ? targetID.getName() : host; } catch (URISyntaxException e) { String userAtHost = targetID.getName(); int atIndex = userAtHost.lastIndexOf(ATSIGN); if (atIndex != -1) userAtHost = userAtHost.substring(atIndex + 1); return userAtHost; } } class ChatRoomParticipant implements IUser, IActionFilter { private static final long serialVersionUID = 2008114088656711572L; ID id; public ChatRoomParticipant(ID id) { this.id = id; } public ID getID() { return id; } public String getName() { return toString(); } public boolean equals(Object other) { if (!(other instanceof ChatRoomParticipant)) return false; ChatRoomParticipant o = (ChatRoomParticipant) other; if (id.equals(o.id)) return true; return false; } public int hashCode() { return id.hashCode(); } public String toString() { return getUsernameFromID(id); } public Map getProperties() { return null; } public Object getAdapter(Class adapter) { return null; } /* * (non-Javadoc) * * @see org.eclipse.ecf.core.user.IUser#getNickname() */ public String getNickname() { return getName(); } public boolean testAttribute(Object target, String name, String value) { if (//$NON-NLS-1$ name.equals("scheme")) { IChatRoomContainer c = ChatRoomManagerView.this.container; String scheme = c.getConnectedID().getNamespace().getScheme(); return scheme.equalsIgnoreCase(value); } return false; } } public void disconnect() { if (rootCloseListener != null) { rootCloseListener.chatRoomViewClosing(); } // disconnect from each chat room container for (Iterator i = chatRooms.values().iterator(); i.hasNext(); ) { ChatRoom chatRoom = (ChatRoom) i.next(); IChatRoomContainer c = chatRoom.chatRoomContainer; if (c != null) c.disconnect(); } rootMessageSender = null; rootCloseListener = null; chatRooms.clear(); } protected void removeLocalUser() { // It's us that's gone away... so we're outta here String title = getPartName(); setPartName(NLS.bind(Messages.ChatRoomManagerView_VIEW_DISABLED_NAME, title)); disconnect(); setEnabled(false); } public void handleInvitationReceived(ID roomID, ID from, String subject, String body) { // XXX TODO } private boolean isLastOutputInvisible(StyledText chatText) { Point locAtEnd = chatText.getLocationAtOffset(chatText.getText().length()); Rectangle bounds = chatText.getBounds(); return (locAtEnd.y > bounds.height + 5); } private void scrollToEnd(StyledText chatText) { chatText.setSelection(chatText.getText().length()); } protected void appendText(ChatRoomTab chatRoomTab, StyledText st, ChatLine text) { if (st == null || text == null) { return; } boolean isAtEndBeforeAppend = !isLastOutputInvisible(st); String originator = null; if (text.getOriginator() != null) { originator = text.getOriginator().getNickname(); } if (messageRenderer == null) messageRenderer = new MessageRenderer(); String output = messageRenderer.render(text.getText(), originator, localUserName); StyleRange[] ranges = messageRenderer.getStyleRanges(); if (output == null) { return; } int startRange = st.getText().length(); if (!text.isNoCRLF()) { //$NON-NLS-1$ output += "\n"; } st.append(output); if (ranges != null) { // set all ranges to start as message line starts for (int i = 0; i < ranges.length; i++) { ranges[i].start += startRange; } st.replaceStyleRanges(startRange, output.length(), ranges); } if (isAtEndBeforeAppend) scrollToEnd(st); if (isCurrentlyActive(chatRoomTab)) chatRoomTab.makeTabItemNormal(); else chatRoomTab.makeTabItemBold(); } protected void outputClear() { if (MessageDialog.openConfirm(null, Messages.ChatRoomManagerView_CLEAR_CONFIRM_TITLE, Messages.ChatRoomManagerView_CLEAR_CONFIRM_MESSAGE)) { //$NON-NLS-1$ getRootTextOutput().setText(""); } } protected void outputCopy() { StyledText outputText = getRootTextOutput(); String t = outputText.getSelectionText(); if (t == null || t.length() == 0) { outputText.selectAll(); } outputText.copy(); outputText.setSelection(outputText.getText().length()); } protected void outputSelectAll() { getRootTextOutput().selectAll(); } protected void makeActions() { outputSelectAll = new Action() { public void run() { outputSelectAll(); } }; outputSelectAll.setText(Messages.ChatRoomManagerView_SELECT_ALL_TEXT); outputSelectAll.setToolTipText(Messages.ChatRoomManagerView_SELECT_ALL_TOOLTIP); outputSelectAll.setAccelerator(SWT.CTRL | 'A'); outputCopy = new Action() { public void run() { outputCopy(); } }; outputCopy.setText(Messages.ChatRoomManagerView_COPY_TEXT); outputCopy.setToolTipText(Messages.ChatRoomManagerView_COPY_TOOLTIP); outputCopy.setAccelerator(SWT.CTRL | 'C'); outputCopy.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_COPY)); outputClear = new Action() { public void run() { outputClear(); } }; outputClear.setText(Messages.ChatRoomManagerView_CLEAR_TEXT); outputClear.setToolTipText(Messages.ChatRoomManagerView_CLEAR_TOOLTIP); outputPaste = new Action() { public void run() { getRootTextInput().paste(); } }; outputPaste.setText(Messages.ChatRoomManagerView_PASTE_TEXT); outputPaste.setToolTipText(Messages.ChatRoomManagerView_PASTE_TOOLTIP); outputPaste.setAccelerator(SWT.CTRL | 'V'); outputPaste.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_PASTE)); } private void fillContextMenu(IMenuManager manager) { manager.add(outputCopy); manager.add(outputPaste); manager.add(outputClear); manager.add(new Separator()); manager.add(outputSelectAll); manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } private void hookContextMenu() { MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { fillContextMenu(manager); } }); StyledText outputText = getRootTextOutput(); Menu menu = menuMgr.createContextMenu(outputText); outputText.setMenu(menu); ISelectionProvider selectionProvider = new ISelectionProvider() { public void addSelectionChangedListener(ISelectionChangedListener listener) { // do nothing } public ISelection getSelection() { StyledText ot = getRootTextOutput(); ISelection selection = new TextSelection(ot.getSelectionRange().x, ot.getSelectionRange().y); return selection; } public void removeSelectionChangedListener(ISelectionChangedListener listener) { // do nothing } public void setSelection(ISelection selection) { if (selection instanceof ITextSelection) { ITextSelection textSelection = (ITextSelection) selection; StyledText ot = getRootTextOutput(); ot.setSelection(textSelection.getOffset(), textSelection.getOffset() + textSelection.getLength()); } } }; getSite().registerContextMenu(menuMgr, selectionProvider); } public void setMessageRenderer(IMessageRenderer defaultMessageRenderer) { this.messageRenderer = defaultMessageRenderer; } private boolean isCurrentlyActive(ChatRoomTab chatRoomTab) { int selected = rootTabFolder.getSelectionIndex(); if (selected != -1) { CTabItem item = rootTabFolder.getItem(selected); if (item == chatRoomTab.tabItem) return true; } return false; } }
39.980697
225
0.586148
08b49424b6c324e8d889f840f8802fe2431b1f6a
2,062
/* * Copyright 2015 Laukviks Bedrifter. * * 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 no.laukvik.csv.query; import no.laukvik.csv.columns.Column; import no.laukvik.csv.columns.DateColumn; import java.util.Arrays; import java.util.Date; import java.util.List; /** * Compares a StringColumn to have the specified value. */ public final class MillisecondMatcher implements ValueMatcher<Date> { /** * The value to compare. */ private final List<Integer> values; /** * The column to compare. */ private final DateColumn column; /** * Compares the date against one or more values. * * @param dateColumn the column * @param value the value */ public MillisecondMatcher(final DateColumn dateColumn, final Integer... value) { this(dateColumn, Arrays.asList(value)); } /** * Compares the date against one or more values. * * @param dateColumn the column * @param values the values */ public MillisecondMatcher(final DateColumn dateColumn, final List<Integer> values) { super(); this.column = dateColumn; this.values = values; } @Override public Column getColumn() { return column; } /** * Returns true when the value matchesRow. * * @param value the value * @return true when the row matchesRow */ @Override public boolean matches(final Date value) { return values.contains(DateColumn.getMilliseconds(value)); } }
26.101266
88
0.664888
4d74e827ea891d8b04402f66804b27f960b72a22
1,749
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.parallax.server.blocklyprop.db.dao; import com.parallax.server.blocklyprop.db.generated.tables.ProjectSharing; import com.parallax.server.blocklyprop.db.generated.tables.records.ProjectSharingRecord; import java.util.List; /** * * @author Michel */ public interface ProjectSharingDao { /** * Retrieve a project * @param idProject * @param accessKey * @return */ ProjectSharingRecord getProject(Long idProject, String accessKey); /** * Share an existing project * @param idProject * @param shareKey * @return */ ProjectSharingRecord shareProject(Long idProject, String shareKey); /** * Disable the shared link to a project * @param idProject * @return */ int revokeSharing(Long idProject); /** * Get a project sharing record * @param idProject * @return */ List<ProjectSharingRecord> getSharingInfo(Long idProject); // Set the active flag in an existing shared project record /** * Enable the project sharing link * * @param idProject * @return */ ProjectSharingRecord activateProject(Long idProject); // Remove a project sharing link record /** * Delete a project sharing record * * @param idProject * @return */ boolean deleteProjectSharingRecord(Long idProject); /** * Is the project sharing feature enabled for a project * @param idProject * @return */ boolean isProjectSharingActive(Long idProject); }
22.139241
88
0.657519
22edcac336c3fdbf7caeab5b441433ef0095a58c
5,202
package jburg.util; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jburg.ProductionTable; import jburg.TransitionTableLoader; import jburg.frontend.XMLGrammar; /** * GenerateHostBURM is a convenience entry point * that uses command-line switches to load a * production table, and to dump that table using * the specified template group. */ public class GenerateHostBURM { public static void main(String[] args) throws Exception { String outputFileName = null; String grammarFileName = null; String templateGroup = null; String burmClassName = null; String visitorClassName = null; String nodeClassName = null; String nodeTypeClassAlias = null; String verboseTrigger = null; Map<String,String> attributes = new HashMap<String,String>(); String nonterminalClassName = null; String nodeTypeClassName = null; List<String> includes = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-classname")) { burmClassName = args[++i]; } else if (args[i].equals("-grammar")) { grammarFileName = args[++i]; } else if (args[i].equalsIgnoreCase("-include")) { includes.add(args[++i]); } else if (args[i].equalsIgnoreCase("-nonterminalClass")) { nonterminalClassName = args[++i]; } else if (args[i].equalsIgnoreCase("-nodeClass")) { nodeClassName = args[++i]; } else if (args[i].equalsIgnoreCase("-nodeTypeClass")) { nodeTypeClassName = args[++i]; } else if (args[i].equalsIgnoreCase("-nodeTypeClassAlias")) { nodeTypeClassAlias = args[++i]; } else if (args[i].equals("-output")) { outputFileName = args[++i]; } else if (args[i].equalsIgnoreCase("-resultType")) { attributes.put("result.type", args[++i]); } else if (args[i].equals("-visitor")) { visitorClassName = args[++i]; } else if (args[i].equals("-templateGroup")) { templateGroup = args[++i]; } else if (args[i].equals("-visitor")) { visitorClassName = args[++i]; } else if (args[i].equals("-verbose")) { verboseTrigger = args[++i]; } else { throw new IllegalArgumentException("unrecognized argument " + args[i]); } } if (outputFileName == null) { throw new IllegalArgumentException("-output must be specified."); } else if (grammarFileName == null) { throw new IllegalArgumentException("-grammar must be specified."); } else if (templateGroup == null) { throw new IllegalArgumentException("-templateGroup must be specified."); } else if (burmClassName == null) { throw new IllegalArgumentException("-classname must be specified."); } else if (visitorClassName == null) { throw new IllegalArgumentException("-visitor must be specified."); } else if (nonterminalClassName == null) { throw new IllegalArgumentException("-nonterminalClass must be specified."); } else if (nodeClassName == null) { throw new IllegalArgumentException("-nodeClass must be specified."); } else if (nodeTypeClassName == null) { throw new IllegalArgumentException("-nodeTypeClass must be specified."); } XMLGrammar<String,String> grammarBuilder = new XMLGrammar<String,String>(nonterminalClassName, nodeTypeClassName); grammarBuilder.setVerboseTrigger(verboseTrigger); ProductionTable<String, String> productions = grammarBuilder.build(convertToFileURL(grammarFileName)); attributes.put("class.name", burmClassName); attributes.put("visitor.class", visitorClassName); attributes.put("node.class", nodeClassName); attributes.put("nonterminal.class", nonterminalClassName); attributes.put("grammar.name", grammarFileName); Map<String,Object> defaults = new HashMap<String, Object>(); defaults.put("includes",includes); if (nodeTypeClassAlias == null) { attributes.put("nodeType.class", nodeTypeClassName); } else { attributes.put("nodeType.class", nodeTypeClassAlias); } attributes.put("nodeClass", nodeClassName); productions.dump(outputFileName, templateGroup, attributes, defaults, grammarBuilder.getSemantics()); } public static String convertToFileURL(String filename) { String path = new File(filename).getAbsolutePath(); if (File.separatorChar != '/') { path = path.replace(File.separatorChar, '/'); } if (!path.startsWith("/")) { path = "/" + path; } return "file:" + path; } }
38.820896
123
0.589389
c7054b0ca19f047271be286bbf2141c44c5c56d6
376
package com.alipay.api.response; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.eco.cityservice.openevent.app.modify response. * * @author auto create * @since 1.0, 2022-04-20 15:46:39 */ public class AlipayEcoCityserviceOpeneventAppModifyResponse extends AlipayResponse { private static final long serialVersionUID = 1295549973128528157L; }
17.904762
84
0.763298
e591398bc67729e740848568d21137bb84cea1fb
3,330
import java.util.ArrayList; import java.util.List; import java.util.Stack; class ONTEditor { private Stack<UndoableCommand> undostack, redostack; private List<UndoableCommand> commandbatch; //not init'd in constructor yet private boolean joinedcommandmode; ProgramData programdata; ONTEditor(ProgramData programdata) { this.programdata = programdata; undostack = new Stack<UndoableCommand>(); redostack = new Stack<UndoableCommand>(); } /** * given book, chapter, and verse indices, return line number in the ONT * file. */ int verseToLine(int bookidx, int chapidx, int verseidx) { int bookstartidx = 0; if (UserData.filetype == ONTFiler.Filetype.nt) bookstartidx = 39; int versessum = 0; for (int i = bookstartidx; i <= bookidx; i++) for (int j = 0; j < Verse.BIBLE[i].length; j++) if (i == bookidx && j == chapidx) { versessum += verseidx + 1; break; } else versessum += Verse.BIBLE[i][j]; return versessum; } /** * mode for multiple undoes at a time to be possible. */ void turnOnBatchMode() { joinedcommandmode = true; commandbatch = new ArrayList<UndoableCommand>(); } void turnOffBatchMode() { joinedcommandmode = false; undostack.push(new CompositeCommand(commandbatch)); } void remove(Word word) { pushOntoUndoStack(new RemoveWordCommand(word.verse, UserData.wordidx)); } void add(Word word) { pushOntoUndoStack(new AddWordCommand(word.verse, UserData.wordidx, word)); } void set(Word oldword, Word newword) { // //cancel if all fields are same // boolean changed = false; // try // { // for (Field field : Word.class.getDeclaredFields()) // if (field.get(oldword).equals(field.get(newword))) // { // changed = true; // System.out.println(field.get(oldword) + " " + field.get(newword)); // break; // } // } // catch (IllegalArgumentException | IllegalAccessException e) // { // e.printStackTrace(); // } // if (changed) pushOntoUndoStack(new ChangeWordCommand(oldword, newword)); } /** * pushes command onto undoable stack. * also marks verse as changed and clears redostack. * @param command */ void pushOntoUndoStack(UndoableCommand command) { if (joinedcommandmode) commandbatch.add(command); else undostack.push(command); UserData.changedverses.put(verseToLine(command.bookidx, command.chapidx, command.verseidx), UserData.verses[command.bookidx][command.chapidx][command.verseidx]); redostack.clear(); } /** * use stack to undo. */ void undo() { if (!undostack.empty()) { UndoableCommand command = undostack.pop(); command.undo(); redostack.push(command); //jump to commanded area. UserData.bookidx = command.bookidx; UserData.chapidx = command.chapidx; UserData.verseidx = command.verseidx; UserData.wordidx = command.wordidx; } } /** * use stack to redo. */ void redo() { if (!redostack.empty()) { UndoableCommand command = redostack.pop(); command.redo(); undostack.push(command); //jump to commanded area. UserData.bookidx = command.bookidx; UserData.chapidx = command.chapidx; UserData.verseidx = command.verseidx; UserData.wordidx = command.wordidx; } } void cut() { } void copy() { } void paste() { } }
21.346154
77
0.666967
436520f23f409182742421430cabc22ce3c36c74
2,848
package com.github.shaneyu.playground.lib.registration.registries; import com.github.shaneyu.playground.common.block.interfaces.IHasDescription; import com.github.shaneyu.playground.common.item.BlockItemTooltip; import com.github.shaneyu.playground.lib.provider.IBlockProvider; import com.github.shaneyu.playground.lib.registration.DoubleWrappedDeferredRegister; import net.minecraft.block.AbstractBlock; import net.minecraft.block.Block; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraftforge.registries.ForgeRegistries; import java.util.ArrayList; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import static com.github.shaneyu.playground.common.registration.PlaygroundBlocks.BLOCKS; public class BlockDeferredRegister extends DoubleWrappedDeferredRegister<Block, Item> { private final List<IBlockProvider> allBlocks = new ArrayList<>(); private final Supplier<Item.Properties> defaultItemProperties; public BlockDeferredRegister(String modId, Supplier<Item.Properties> defaultItemProperties) { super(modId, ForgeRegistries.BLOCKS, ForgeRegistries.ITEMS); this.defaultItemProperties = defaultItemProperties; } public <BLOCK extends Block, ITEM extends BlockItem> BlockRegistryObject<BLOCK, ITEM> register( String name, Supplier<? extends BLOCK> blockSupplier, Function<BLOCK, ITEM> itemCreator) { BlockRegistryObject<BLOCK, ITEM> registeredBlock = register(name, blockSupplier, itemCreator, BlockRegistryObject::new); allBlocks.add(registeredBlock); return registeredBlock; } public BlockRegistryObject<Block, BlockItem> register(String name, AbstractBlock.Properties properties) { return registerDefaultProperties(name, () -> new Block(properties), BlockItem::new); } public <BLOCK extends Block> BlockRegistryObject<BLOCK, BlockItem> register(String name, Supplier<? extends BLOCK> blockSupplier) { return registerDefaultProperties(name, blockSupplier, BlockItem::new); } public <BLOCK extends Block, ITEM extends BlockItem> BlockRegistryObject<BLOCK, ITEM> registerDefaultProperties( String name, Supplier<? extends BLOCK> blockSupplier, BiFunction<BLOCK, Item.Properties, ITEM> itemCreator) { return register(name, blockSupplier, block -> itemCreator.apply(block, defaultItemProperties.get())); } public <BLOCK extends Block & IHasDescription> BlockRegistryObject<BLOCK, BlockItemTooltip<BLOCK>> registerBlock( String name, Supplier<? extends BLOCK> blockSupplier) { return BLOCKS.registerDefaultProperties(name, blockSupplier, BlockItemTooltip::new); } public List<IBlockProvider> getAllBlocks() { return allBlocks; } }
45.206349
135
0.774579
3f3137711af4f3172767be658b33d8f191a642d8
196
package transgenic.lauterbrunnen.lateral.example.cassandra.proto; /** * Created by stumeikle on 16/07/20. */ public class PricePerServingOption { double price; String servingOption; }
17.818182
65
0.744898
aa4e17587ec97d6cca0aa064ae6964502c0fbf2e
832
package com.leven.dto; /** * @Author: LevenLiu * @Description: * @Date: Create 0:55 2018/8/20 * @Modified By: */ public class Author { private String username; private String name; private String email; public Author(String username, String name, String email) { this.username = username; this.name = name; this.email = email; } public Author() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
17.333333
63
0.582933
10d34827af748c27e6b1568c84b6320febb6342b
1,545
/** Copyright (c) 2014 BlackBerry Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blackberry.logdriver.mapreduce.boom; import java.io.IOException; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import com.blackberry.logdriver.boom.LogLineData; public class BoomIndividualInputFormat extends FileInputFormat<LogLineData, Text> { @Override protected boolean isSplitable(JobContext context, Path filename) { return true; } @Override public RecordReader<LogLineData, Text> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException { return new BoomIndividualRecordReader((FileSplit) split, context); } }
33.586957
77
0.775405
40e30a1d179bd17fc413ea38d44135d65cff04a6
3,429
package com.bewitchment.common.block; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.EnumPushReaction; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.Random; @SuppressWarnings({"deprecation", "NullableProblems"}) public class BlockCandle extends BlockCandleBase { private static final AxisAlignedBB BOX = new AxisAlignedBB(0.38, 0, 0.38, 0.62, 0.5, 0.62); public BlockCandle(String name) { super(name, Material.CLOTH, SoundType.CLOTH, 1, 1, "", 0); Blocks.FIRE.setFireInfo(this, 0, 0); } @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) { return BOX; } @Override public void updateTick(World world, BlockPos pos, IBlockState state, Random rand) { if (!world.getBlockState(pos.down()).getBlock().canPlaceTorchOnTop(world.getBlockState(pos.down()), world, pos)) world.destroyBlock(pos, true); } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) { if (state.getValue(LIT)) world.spawnParticle(EnumParticleTypes.FLAME, pos.getX() + 0.5, pos.getY() + 0.7, pos.getZ() + 0.5, 0, 0, 0); } @Override public void neighborChanged(IBlockState state, World world, BlockPos to, Block block, BlockPos from) { world.scheduleUpdate(to, this, 0); } @Override public boolean canPlaceBlockAt(World world, BlockPos pos) { return world.getBlockState(pos.down()).getBlock().canPlaceTorchOnTop(world.getBlockState(pos.down()), world, pos); } @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing face, float hitX, float hitY, float hitZ) { if (state.getValue(LIT)) { world.setBlockState(pos, getDefaultState().withProperty(LIT, false)); world.playSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.BLOCK_FIRE_EXTINGUISH, SoundCategory.BLOCKS, 0.5f, 2.6f + (world.rand.nextFloat() - world.rand.nextFloat()) * 0.8f, false); return true; } else { ItemStack stack = player.getHeldItem(hand); if (stack.getItem() == Items.FLINT_AND_STEEL) { stack.damageItem(1, player); world.setBlockState(pos, getDefaultState().withProperty(LIT, true)); world.playSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.ITEM_FLINTANDSTEEL_USE, SoundCategory.BLOCKS, 1, world.rand.nextFloat() * 0.4f + 0.8f, false); return true; } } return super.onBlockActivated(world, pos, state, player, hand, face, hitX, hitY, hitZ); } @Override public EnumPushReaction getPushReaction(IBlockState state) { return EnumPushReaction.DESTROY; } @Override public int getLightValue(IBlockState state) { return state.getValue(LIT) ? 9 : 0; } }
38.52809
190
0.757655
0d33d65c4fd1f1573ce8537b179000e5419b06e7
2,238
/* * Copyright 2016 The gRPC 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.grpc.internal; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.grpc.CallOptions; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; import io.grpc.internal.Channelz.SocketStats; import io.grpc.internal.ClientStreamListener.RpcProgress; import java.util.concurrent.Executor; /** * A client transport that creates streams that will immediately fail when started. */ class FailingClientTransport implements ClientTransport { @VisibleForTesting final Status error; private final RpcProgress rpcProgress; FailingClientTransport(Status error, RpcProgress rpcProgress) { Preconditions.checkArgument(!error.isOk(), "error must not be OK"); this.error = error; this.rpcProgress = rpcProgress; } @Override public ClientStream newStream( MethodDescriptor<?, ?> method, Metadata headers, CallOptions callOptions) { return new FailingClientStream(error, rpcProgress); } @Override public void ping(final PingCallback callback, Executor executor) { executor.execute(new Runnable() { @Override public void run() { callback.onFailure(error.asException()); } }); } @Override public ListenableFuture<SocketStats> getStats() { SettableFuture<SocketStats> ret = SettableFuture.create(); ret.set(null); return ret; } @Override public LogId getLogId() { throw new UnsupportedOperationException("Not a real transport"); } }
31.083333
83
0.747542
ee3d2af7ff9b3e785510258f96817dd755b38c48
7,641
package io.vividcode.happytakeaway.restaurant.service; import io.quarkus.panache.common.Sort; import io.vividcode.happytakeaway.common.base.PageRequest; import io.vividcode.happytakeaway.common.base.PagedResult; import io.vividcode.happytakeaway.restaurant.api.CreateRestaurantRequest; import io.vividcode.happytakeaway.restaurant.api.DeleteRestaurantRequest; import io.vividcode.happytakeaway.restaurant.api.GetRestaurantRequest; import io.vividcode.happytakeaway.restaurant.api.SetActiveMenuRequest; import io.vividcode.happytakeaway.restaurant.api.SetActiveMenuResponse; import io.vividcode.happytakeaway.restaurant.api.UpdateRestaurantRequest; import io.vividcode.happytakeaway.restaurant.api.UpdateRestaurantResponse; import io.vividcode.happytakeaway.restaurant.api.v1.Address; import io.vividcode.happytakeaway.restaurant.api.v1.MenuItem; import io.vividcode.happytakeaway.restaurant.api.v1.Restaurant; import io.vividcode.happytakeaway.restaurant.api.v1.RestaurantWithMenuItems; import io.vividcode.happytakeaway.restaurant.api.v1.RestaurantWithMenuItems.RestaurantWithMenuItemsBuilder; import io.vividcode.happytakeaway.restaurant.entity.RestaurantEntity; import io.vividcode.happytakeaway.restaurant.entity.RestaurantEntity.RestaurantEntityBuilder; import io.vividcode.happytakeaway.restaurant.repository.MenuRepository; import io.vividcode.happytakeaway.restaurant.repository.RestaurantRepository; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.transaction.Transactional; @ApplicationScoped public class RestaurantService { @Inject RestaurantRepository restaurantRepository; @Inject MenuRepository menuRepository; @Inject MenuItemService menuItemService; @Inject OwnerIdProvider ownerIdProvider; @Transactional public String createRestaurant(CreateRestaurantRequest request) { RestaurantEntityBuilder builder = RestaurantEntity.builder() .ownerId(this.ownerIdProvider.get()) .name(request.getName()) .description(request.getDescription()) .phoneNumber(request.getPhoneNumber()); if (request.getAddress() != null) { builder .addressCode(request.getAddress().getCode()) .addressLine(request.getAddress().getAddressLine()) .addressLng(request.getAddress().getLng()) .addressLat(request.getAddress().getLat()); } RestaurantEntity entity = builder.build(); this.restaurantRepository.persist(entity); return entity.getId(); } public RestaurantWithMenuItems getRestaurant(GetRestaurantRequest request) { return this.restaurantRepository .findByOwnerIdAndId(this.ownerIdProvider.get(), request.getId()) .map( restaurant -> { RestaurantWithMenuItemsBuilder builder = RestaurantWithMenuItems.builder() .id(restaurant.getId()) .name(restaurant.getName()) .description(restaurant.getDescription()) .address(ServiceHelper.buildAddress(restaurant)); if (restaurant.getActiveMenu() != null && request.getNumberOfMenuItems() > 0) { builder.menuItems( this.menuItemService.findMenuItems( restaurant.getActiveMenu().getId(), PageRequest.of(0, request.getNumberOfMenuItems()))); } return builder.build(); }) .orElseThrow(() -> ServiceHelper.restaurantNotFound(request.getId())); } @Transactional public List<Restaurant> listAllRestaurants(PageRequest pageRequest) { return this.restaurantRepository .findAll() .page(pageRequest.getPage(), pageRequest.getSize()) .list() .stream() .map(ServiceHelper::buildRestaurant) .collect(Collectors.toList()); } @Transactional public PagedResult<Restaurant> listRestaurants(PageRequest pageRequest) { long count = this.restaurantRepository.count(); List<RestaurantEntity> entities = this.restaurantRepository .findAll(Sort.by("name")) .page(pageRequest.getPage(), pageRequest.getSize()) .list(); List<Restaurant> results = ServiceHelper.transform(entities, ServiceHelper::buildRestaurant); return PagedResult.fromData(results, pageRequest, count); } @Transactional public PagedResult<MenuItem> getMenuItems(String restaurantId, PageRequest pageRequest) { return this.restaurantRepository .findByOwnerIdAndId(this.ownerIdProvider.get(), restaurantId) .map( restaurant -> Optional.ofNullable(restaurant.getActiveMenu()) .map(menu -> this.menuItemService.findMenuItems(menu.getId(), pageRequest)) .orElse(PagedResult.empty())) .orElseThrow(() -> ServiceHelper.restaurantNotFound(restaurantId)); } @Transactional public UpdateRestaurantResponse updateRestaurant(UpdateRestaurantRequest request) { return this.restaurantRepository .findByOwnerIdAndId(this.ownerIdProvider.get(), request.getId()) .map( restaurant -> { if (request.getName() != null) { restaurant.setName(request.getName()); } if (request.getDescription() != null) { restaurant.setDescription(request.getDescription()); } Address address = request.getAddress(); if (address != null) { restaurant.setAddressCode(address.getCode()); restaurant.setAddressLine(address.getAddressLine()); restaurant.setAddressLng(address.getLng()); restaurant.setAddressLat(address.getLat()); } this.restaurantRepository.persist(restaurant); return UpdateRestaurantResponse.builder() .id(restaurant.getId()) .name(restaurant.getName()) .description(restaurant.getDescription()) .address( Address.builder() .code(restaurant.getAddressCode()) .addressLine(restaurant.getAddressLine()) .lng(restaurant.getAddressLng()) .lat(restaurant.getAddressLat()) .build()) .build(); }) .orElseThrow(() -> ServiceHelper.restaurantNotFound(request.getId())); } @Transactional public boolean deleteRestaurant(DeleteRestaurantRequest request) { return this.restaurantRepository.deleteByOwnerIdAndId( this.ownerIdProvider.get(), request.getId()); } @Transactional public SetActiveMenuResponse setActiveMenu(SetActiveMenuRequest request) { this.restaurantRepository .findByOwnerIdAndId(this.ownerIdProvider.get(), request.getRestaurantId()) .map( restaurant -> { restaurant.setActiveMenu( this.menuRepository .findById(request.getRestaurantId(), request.getMenuId()) .orElseThrow(() -> ServiceHelper.menuNotFound(request.getMenuId()))); return restaurant; }) .orElseThrow(() -> ServiceHelper.restaurantNotFound(request.getRestaurantId())); return SetActiveMenuResponse.builder() .restaurantId(request.getRestaurantId()) .menuId(request.getMenuId()) .build(); } }
42.926966
107
0.672425
7788ea754d785ed6b78bb5971a91d341fe8dfb0f
827
import java.util.Iterator; import java.util.HashMap; import java.util.Map; public class InstrumentSpec { private Map properties; public InstrumentSpec(Map properties) { if (properties == null) { this.properties = new HashMap(); } else { this.properties = new HashMap(properties); } } public Object getProperty(String propertyName) { return properties.get(propertyName); } public Map getProperties() { return properties; } public boolean matches(InstrumentSpec otherSpec) { for (Iterator i = otherSpec.getProperties().keySet().iterator(); i.hasNext(); ) { String propertyName = (String)i.next(); if (!properties.get(propertyName).equals( otherSpec.getProperty(propertyName))) { return false; } } return true; } }
22.351351
69
0.652963
39c5e2c76f5953a0f5991b5dfa094ecdd08a1775
1,588
package com.bolo1.tweet_app.holder; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bolo1.tweet_app.R; import com.bolo1.tweet_app.media.IjkVideoView; import butterknife.ButterKnife; import butterknife.InjectView; /** * Created by 菠萝 on 2018/7/18. */ public class HomeHolder extends RecyclerView.ViewHolder { @InjectView(R.id.tv_home_recommend) public TextView tv_home_recommend; @InjectView(R.id.tv_home_round) public TextView tv_home_round; @InjectView(R.id.iv_search_home) public ImageView iv_search_home; @InjectView(R.id.iv_home_author) public ImageView iv_home_author; @InjectView(R.id.iv_home_add) public ImageView iv_home_add; @InjectView(R.id.tv_home_like) public TextView tv_home_like; @InjectView(R.id.tv_home_comment) public TextView tv_home_comment; @InjectView(R.id.tv_home_share) public TextView tv_home_share; @InjectView(R.id.tv_home_author_name) public TextView tv_home_author_name; @InjectView(R.id.tv_home_title) public TextView tv_home_title; @InjectView(R.id.tv_home_music_name) public TextView tv_home_music_name; @InjectView(R.id.iv_home_music) public ImageView iv_home_music; @InjectView(R.id.ll_home_main) public LinearLayout ll_home_main; @InjectView(R.id.ijk_home) public IjkVideoView ijk_home; public HomeHolder(View itemView) { super(itemView); ButterKnife.inject(this,itemView); } }
29.962264
57
0.761965
a372c48422bd53c2bb176f17db22696be978000d
3,743
/* * Copyright (c) 2014, Erik Wienhold * All rights reserved. * * Licensed under the BSD 3-Clause License. */ package vsr.cobalt.planner.extenders.providers; import java.util.HashSet; import java.util.Set; import vsr.cobalt.models.Action; import vsr.cobalt.models.Property; import vsr.cobalt.models.PropositionSet; import vsr.cobalt.models.Widget; import vsr.cobalt.planner.Repository; import vsr.cobalt.utils.OrderedPowerSetIterator; /** * A provider for precursor actions, which composes actions when possible to create precursor actions not explicitly * provided by the repository. The provided precursor actions are minimal, i.e. they satisfy only the minimal set of * requirements of a requested action. * * @author Erik Wienhold */ public class ComposingMinimalPrecursorActionProvider implements PrecursorActionProvider { private final Repository repository; /** * @param repository a repository to provide actions */ public ComposingMinimalPrecursorActionProvider(final Repository repository) { this.repository = repository; } @Override public Set<Action> getPrecursorActionsFor(final Action action) { return createPrecursors(action, selectPartialPrecursors(action, getWidgetActions(action.getWidget()))); } private Set<Action> getWidgetActions(final Widget widget) { return repository.getWidgetActions(widget); } /** * Select actions which are partial precursors for a requested action from all widget actions and maintenance * actions. * * @param action a requested action * @param actions a set of actions from the same widget * * @return a set of partial precursors */ private static Set<Action> selectPartialPrecursors(final Action action, final Set<Action> actions) { final Set<Action> partials = new HashSet<>(); for (final Action a : actions) { if (a.isPartialPrecursorOf(action)) { partials.add(a); } } // create maintenance actions for all properties required cleared for (final Property p : action.getPreConditions().getClearedProperties()) { partials.add(createMaintenanceAction(action.getWidget(), p)); } return partials; } /** * Create a maintenance action for a cleared property. * * @param widget a widget * @param property a property * * @return a maintenance action */ private static Action createMaintenanceAction(final Widget widget, final Property property) { return Action.create(widget, PropositionSet.cleared(property)); } /** * Create precursor actions from a set of partial precursors. * * @param action an action requiring a precursor * @param partials a set of partial precursors * * @return a set of precursor actions */ private static Set<Action> createPrecursors(final Action action, final Set<Action> partials) { final Set<Action> precursors = new HashSet<>(); // iterate over all combinations of partial precursors final OrderedPowerSetIterator<Action> it = new OrderedPowerSetIterator<>(partials); while (it.hasNext()) { final Set<Action> combination = it.next(); if (Action.isComposable(combination)) { final Action ca = Action.compose(combination); if (!ca.isMaintenance() && ca.isPrecursorOf(action)) { precursors.add(ca); // supersets of a sufficient combination can be skipped because they would not satisfy anything not already // satisfied it.excludeSuperSetsOf(combination); } } else { // any superset will not be composable either, therefore we can skip those combinations it.excludeSuperSetsOf(combination); } } return precursors; } }
31.720339
117
0.710393
e55c1373307ccbf21c80b0c278747f9ccddaefea
3,029
package sguest.villagelife.util; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import net.minecraft.block.Block; import net.minecraft.util.Direction; import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.shapes.VoxelShapes; import net.minecraftforge.client.model.generators.BlockModelBuilder; import net.minecraftforge.client.model.generators.ModelBuilder; public class CubeUtil { public static ModelBuilder<BlockModelBuilder>.ElementBuilder modelElement(BlockModelBuilder builder, Cube cube) { return builder.element().from(cube.getX1(), cube.getY1(), cube.getZ1()).to(cube.getX2(), cube.getY2(), cube.getZ2()); } public static VoxelShape getVoxel(Cube cube) { return Block.makeCuboidShape(cube.getX1(), cube.getY1(), cube.getZ1(), cube.getX2(), cube.getY2(), cube.getZ2()); } public static List<VoxelShape> getVoxels(Cube ... cubes) { return Stream.of(cubes).map(CubeUtil::getVoxel).collect(Collectors.toList()); } public static Cube rotate(Cube cube) { return new Cube(16 - cube.getZ1(), cube.getY1(), cube.getX1(), 16 - cube.getZ2(), cube.getY2(), cube.getX2()); } public static Cube[] rotate(Cube ... cubes) { return Stream.of(cubes).map(CubeUtil::rotate).toArray(Cube[]::new); } public static Map<Direction, VoxelShape> getHorizontalShapes(Cube ... cubes) { Map<Direction, VoxelShape> shapes = new HashMap<>(); shapes.put(Direction.NORTH, friendlyOr(getVoxels(cubes))); cubes = rotate(cubes); shapes.put(Direction.EAST, friendlyOr(getVoxels(cubes))); cubes = rotate(cubes); shapes.put(Direction.SOUTH, friendlyOr(getVoxels(cubes))); cubes = rotate(cubes); shapes.put(Direction.WEST, friendlyOr(getVoxels(cubes))); return shapes; } private static VoxelShape friendlyOr(List<VoxelShape> shapes) { VoxelShape first = shapes.remove(0); return VoxelShapes.or(first, shapes.stream().toArray(VoxelShape[]::new)); } public static class Cube { private final float x1; private final float x2; private final float y1; private final float y2; private final float z1; private final float z2; public Cube(float x1, float y1, float z1, float x2, float y2, float z2) { this.x1 = x1; this.y1 = y1; this.z1 = z1; this.x2 = x2; this.y2 = y2; this.z2 = z2; } public float getX1() { return this.x1; } public float getY1() { return this.y1; } public float getZ1() { return this.z1; } public float getX2() { return this.x2; } public float getY2() { return this.y2; } public float getZ2() { return this.z2; } } }
31.226804
125
0.623968
87b01403a64613bc27934f5a4920b9c1f2f99be0
1,519
package org.webpieces.httpclient.api; import java.net.InetSocketAddress; import org.webpieces.util.futures.XFuture; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.webpieces.data.api.BufferPool; import org.webpieces.data.api.TwoPools; import org.webpieces.http2client.api.Http2Client; import org.webpieces.http2client.api.Http2Socket; import org.webpieces.httpclient.Http2CloseListener; import org.webpieces.httpclient.api.mocks.MockChannel; import org.webpieces.httpclient.api.mocks.MockChannelMgr; import org.webpieces.httpclientx.api.Http2to11ClientFactory; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; public class TestConnecting { private MockChannelMgr mockChannelMgr = new MockChannelMgr(); private MockChannel mockChannel = new MockChannel(); private Http2Client httpClient; @Before public void setup() { BufferPool pool = new TwoPools("pl", new SimpleMeterRegistry()); httpClient = Http2to11ClientFactory.createHttpClient("myClient2", mockChannelMgr, new SimpleMeterRegistry(), pool); } @Test public void testConnecting() { mockChannelMgr.addTCPChannelToReturn(mockChannel); Http2Socket socket = httpClient.createHttpSocket(new Http2CloseListener()); XFuture<Void> future1 = new XFuture<Void>(); mockChannel.setConnectFuture(future1); XFuture<Void> future = socket.connect(new InetSocketAddress(8080)); Assert.assertFalse(future.isDone()); future1.complete(null); Assert.assertTrue(future.isDone()); } }
30.38
117
0.798552
921af5cefbc2526b2080ec1a934f78d86a686113
3,076
package io.hawt.maven; import java.util.List; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; @Mojo(name = "camel", defaultPhase = LifecyclePhase.PROCESS_TEST_CLASSES, requiresDependencyResolution = ResolutionScope.RUNTIME) @Execute(phase = LifecyclePhase.PROCESS_TEST_CLASSES) public class CamelMojo extends RunMojo { @Parameter(property = "hawtio.applicationContextUri") private String applicationContextUri; @Parameter(property = "hawtio.fileApplicationContextUri") private String fileApplicationContextUri; protected Artifact camelCoreArtifact; @Override protected void addCustomArguments(List<String> args) throws Exception { if (applicationContextUri != null) { args.add("-ac"); args.add(applicationContextUri); } else if (fileApplicationContextUri != null) { args.add("-fa"); args.add(fileApplicationContextUri); } if (mainClass != null) { getLog().info("Using custom " + mainClass + " to initiate Camel"); } else { // use spring by default getLog().info("Using org.apache.camel.spring.Main to initiate Camel"); mainClass = "org.apache.camel.spring.Main"; } } protected Artifact getCamelCoreArtifact(Set<Artifact> artifacts) throws MojoExecutionException { for (Artifact artifact : artifacts) { if (artifact.getGroupId().equals("org.apache.camel") && artifact.getArtifactId().equals("camel-core")) { return artifact; } } return null; } @Override protected void resolvedArtifacts(Set<Artifact> artifacts) throws Exception { // make sure we have camel-core camelCoreArtifact = getCamelCoreArtifact(artifacts); if (camelCoreArtifact == null) { throw new IllegalAccessError("Cannot resolve camel-core dependency from the Maven pom.xml file"); } super.resolvedArtifacts(artifacts); } @Override protected boolean filterUnwantedArtifacts(Artifact artifact) { // filter out unwanted OSGi related JARs as some projects like ActiveMQ includes these dependencies // and you should use the camel-blueprint goal for running as OSGi if (artifact.getGroupId().equals("org.apache.aries.blueprint")) { return true; } else if (artifact.getGroupId().startsWith("org.ops4j")) { return true; } else if (artifact.getGroupId().equals("org.osgi")) { return true; } else if (artifact.getGroupId().equals("org.apache.felix")) { return true; } return super.filterUnwantedArtifacts(artifact); } }
37.512195
129
0.676528
7bdd69567588b9cd48c8737c15068c2e521bf4e1
5,091
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.dialer.searchfragment.common; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.style.StyleSpan; /** Utility class for handling bolding queries contained in string. */ public class QueryBoldingUtil { /** * Compares a name and query and returns a {@link CharSequence} with bolded characters. * * <p>Some example: * * <ul> * <li>"query" would bold "John [query] Smith" * <li>"222" would bold "[AAA] Mom" * <li>"222" would bold "[A]llen [A]lex [A]aron" * </ul> * * @param query containing any characters * @param name of a contact/string that query will compare to * @return name with query bolded if query can be found in the name. */ public static CharSequence getNameWithQueryBolded(@Nullable String query, @NonNull String name) { if (TextUtils.isEmpty(query)) { return name; } int index = -1; int numberOfBoldedCharacters = 0; if (QueryFilteringUtil.nameMatchesT9Query(query, name)) { // Bold the characters that match the t9 query String t9 = QueryFilteringUtil.getT9Representation(name); index = QueryFilteringUtil.indexOfQueryNonDigitsIgnored(query, t9); if (index == -1) { return getNameWithInitialsBolded(query, name); } numberOfBoldedCharacters = query.length(); for (int i = 0; i < query.length(); i++) { char c = query.charAt(i); if (!Character.isDigit(c)) { numberOfBoldedCharacters--; } } for (int i = 0; i < index + numberOfBoldedCharacters; i++) { if (!Character.isLetterOrDigit(name.charAt(i))) { if (i < index) { index++; } else { numberOfBoldedCharacters++; } } } } if (index == -1) { // Bold the query as an exact match in the name index = name.toLowerCase().indexOf(query); numberOfBoldedCharacters = query.length(); } return index == -1 ? name : getBoldedString(name, index, numberOfBoldedCharacters); } private static CharSequence getNameWithInitialsBolded(String query, String name) { SpannableString boldedInitials = new SpannableString(name); name = name.toLowerCase(); int initialsBolded = 0; int nameIndex = -1; while (++nameIndex < name.length() && initialsBolded < query.length()) { if ((nameIndex == 0 || name.charAt(nameIndex - 1) == ' ') && QueryFilteringUtil.getDigit(name.charAt(nameIndex)) == query.charAt(initialsBolded)) { boldedInitials.setSpan( new StyleSpan(Typeface.BOLD), nameIndex, nameIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE); initialsBolded++; } } return boldedInitials; } /** * Compares a number and a query and returns a {@link CharSequence} with bolded characters. * * <ul> * <li>"123" would bold "(650)34[1-23]24" * <li>"123" would bold "+1([123])111-2222 * </ul> * * @param query containing only numbers and phone number related characters "(", ")", "-", "+" * @param number phone number of a contact that the query will compare to. * @return number with query bolded if query can be found in the number. */ public static CharSequence getNumberWithQueryBolded( @Nullable String query, @NonNull String number) { if (TextUtils.isEmpty(query) || !QueryFilteringUtil.numberMatchesNumberQuery(query, number)) { return number; } int index = QueryFilteringUtil.indexOfQueryNonDigitsIgnored(query, number); int boldedCharacters = query.length(); for (char c : query.toCharArray()) { if (!Character.isDigit(c)) { boldedCharacters--; } } for (int i = 0; i < index + boldedCharacters; i++) { if (!Character.isDigit(number.charAt(i))) { if (i <= index) { index++; } else { boldedCharacters++; } } } return getBoldedString(number, index, boldedCharacters); } private static SpannableString getBoldedString(String s, int index, int numBolded) { SpannableString span = new SpannableString(s); span.setSpan( new StyleSpan(Typeface.BOLD), index, index + numBolded, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); return span; } }
32.845161
99
0.65056
65a795fd9246d48ed04e9b28bab7b0346b0dd69a
1,399
/* * Copyright 2020 Anne Bernhart, Anja Hansen, Tobias Klumpp, Fabian Palitza, * Florian Patzer, Friedrich Volz, Sandra Wolf * SPDX-License-Identifier: Apache-2.0 */ package edu.kit.informatik.tolowiz.controller.interpretation; import java.io.FileNotFoundException; import java.util.List; import edu.kit.informatik.tolowiz.model.ontology.Ontology; /** * This is the Interface to allow interpretation of ontology files. Ontologies * must be submitted in rdf format. The file will then be analyzed to create an * ontology object from it. * * @author Anne Bernhart * */ public interface InterpreterInterface { /** * Builds a new ontology from a rdf file. * * @return returns the newly built ontology. * @throws FileNotFoundException if the given file can not be found * @throws OntologyFileException if the given filepath doesn't refer to a valid * ontology file. */ public Ontology buildOntology() throws FileNotFoundException, OntologyFileException; /** * returns all Error messages of Problems that have occured while reading and * processing the ontology given when constructing. The Messages describe what * went wrong and how this will influence the presentation of the ontology. * * @return the List of all Error messages. */ public List<String> getErrorMessages(); }
33.309524
88
0.713367
0379466838344f16fb75b00665c1824db16bb7d7
3,675
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.models.extensions.OpenShiftChangeRequest; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.http.IHttpRequest; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The interface for the Open Shift Change Request Request. */ public interface IOpenShiftChangeRequestRequest extends IHttpRequest { /** * Gets the OpenShiftChangeRequest from the service * * @param callback the callback to be called after success or failure */ void get(final ICallback<OpenShiftChangeRequest> callback); /** * Gets the OpenShiftChangeRequest from the service * * @return the OpenShiftChangeRequest from the request * @throws ClientException this exception occurs if the request was unable to complete for any reason */ OpenShiftChangeRequest get() throws ClientException; /** * Delete this item from the service * * @param callback the callback when the deletion action has completed */ void delete(final ICallback<OpenShiftChangeRequest> callback); /** * Delete this item from the service * * @throws ClientException if there was an exception during the delete operation */ void delete() throws ClientException; /** * Patches this OpenShiftChangeRequest with a source * * @param sourceOpenShiftChangeRequest the source object with updates * @param callback the callback to be called after success or failure */ void patch(final OpenShiftChangeRequest sourceOpenShiftChangeRequest, final ICallback<OpenShiftChangeRequest> callback); /** * Patches this OpenShiftChangeRequest with a source * * @param sourceOpenShiftChangeRequest the source object with updates * @return the updated OpenShiftChangeRequest * @throws ClientException this exception occurs if the request was unable to complete for any reason */ OpenShiftChangeRequest patch(final OpenShiftChangeRequest sourceOpenShiftChangeRequest) throws ClientException; /** * Posts a OpenShiftChangeRequest with a new object * * @param newOpenShiftChangeRequest the new object to create * @param callback the callback to be called after success or failure */ void post(final OpenShiftChangeRequest newOpenShiftChangeRequest, final ICallback<OpenShiftChangeRequest> callback); /** * Posts a OpenShiftChangeRequest with a new object * * @param newOpenShiftChangeRequest the new object to create * @return the created OpenShiftChangeRequest * @throws ClientException this exception occurs if the request was unable to complete for any reason */ OpenShiftChangeRequest post(final OpenShiftChangeRequest newOpenShiftChangeRequest) throws ClientException; /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ IOpenShiftChangeRequestRequest select(final String value); /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ IOpenShiftChangeRequestRequest expand(final String value); }
36.75
152
0.699048
10cd578cf72ee5018556a79b9c40719fc7d5b08f
154
package com.buschmais.xo.neo4j.test.relation.typed.composite; import com.buschmais.xo.neo4j.api.annotation.Label; @Label("F1)") public interface F1 { }
19.25
61
0.772727
73e5b3adbe8dc671efe7f228b41bb39d75872347
1,613
/* * Copyright (C) 2018-2022 FusionSoft * * 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 ru.fusionsoft.database.snapshot; import org.cactoos.Bytes; import org.cactoos.Input; import org.cactoos.Text; import org.cactoos.bytes.Sha256DigestOf; import org.cactoos.io.InputOf; import org.cactoos.text.HexOf; import org.cactoos.text.TextEnvelope; /** * The type of Text that is a hash of {@link AstronomicalTime}. * @since 0.1 */ public class HashTextOf extends TextEnvelope { /** * Instantiates a new Hash text of time. * @param input The Input to be used. */ private HashTextOf(final Input input) { super( new HexOf(new Sha256DigestOf(input)) ); } /** * Instantiates a new Hash text of time. * @param text The Text to be hashed. */ public HashTextOf(final Text text) { this(new InputOf(text)); } /** * Instantiates a new Hash text of time. * @param time The Text to be hashed. */ public HashTextOf(final AstronomicalTime time) { this(new InputOf((Bytes) time)); } }
27.338983
85
0.680099
926dbad680926bfa656b3b4dd2b41c83267e2b70
1,236
package dev.emi.nourish.mixin; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import dev.emi.nourish.effects.NourishStatusEffectInstance; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.nbt.CompoundTag; @Mixin(StatusEffectInstance.class) public class StatusEffectInstanceMixin { @Inject(at = @At("RETURN"), method = "typelessToTag") private void typelessToTag(CompoundTag tag, CallbackInfo info) { if ((Object) this instanceof NourishStatusEffectInstance) { tag.putBoolean("Nourish", true); } } @Inject(at = @At("RETURN"), method = "fromTag", cancellable = true) private static void fromTag(CompoundTag tag, CallbackInfoReturnable<StatusEffectInstance> info) { if (tag.contains("Nourish") && tag.getBoolean("Nourish")) { StatusEffectInstance old = info.getReturnValue(); NourishStatusEffectInstance inst = new NourishStatusEffectInstance(old.getEffectType(), old.getDuration(), old.getAmplifier()); info.setReturnValue(inst); } } }
39.870968
130
0.788026
66d8a3a04b9155b59401c5245733c717f790cdf7
6,600
/* Copyright 2012 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.hraven.etl; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; /** * Pathfilter that allows only files that are named correctly and are modified * within a certain time range. * */ public class JobFileModifiedRangeSubstringPathFilter extends JobFilePathFilter { /** * The minimum modification time of a file to be accepted in milliseconds * since January 1, 1970 UTC (excluding). */ private final long minModificationTimeMillis; /** * The maximum modification time of a file to be accepted in milliseconds * since January 1, 1970 UTC (including). */ private final long maxModificationTimeMillis; /** * The configuration of this processing job (not the files we are processing). */ private final Configuration myConf; private String[] pathExclusionFilter; private String[] pathInclusionFilter; private static Log LOG = LogFactory.getLog(JobFileModifiedRangeSubstringPathFilter.class); /** * Constructs a filter that accepts only JobFiles with lastModification time * in the specified range. * * @param myConf * used to be able to go from a path to a FileStatus. * @param minModificationTimeMillis * The minimum modification time of a file to be accepted in * milliseconds since January 1, 1970 UTC (excluding). * @param maxModificationTimeMillis The * maximum modification time of a file to be accepted in milliseconds * since January 1, 1970 UTC (including). */ public JobFileModifiedRangeSubstringPathFilter(Configuration myConf, long minModificationTimeMillis, long maxModificationTimeMillis) { this(myConf, minModificationTimeMillis, maxModificationTimeMillis, null, null); } /** * Constructs a filter that accepts only JobFiles with lastModification time * as least the specified minumum. * * @param myConf * used to be able to go from a path to a FileStatus. * @param minModificationTimeMillis * The minimum modification time of a file to be accepted in * milliseconds since January 1, 1970 UTC (excluding). */ public JobFileModifiedRangeSubstringPathFilter(Configuration myConf, long minModificationTimeMillis) { this(myConf, minModificationTimeMillis, Long.MAX_VALUE); } /** * Constructs a filter that accepts only JobFiles with lastModification time * as least the specified minumum. Also accepts a simple substring to exclude. * * @param myConf * used to be able to go from a path to a FileStatus. * @param minModificationTimeMillis * The minimum modification time of a file to be accepted in * milliseconds since January 1, 1970 UTC (excluding). * @param maxModificationTimeMillis The * maximum modification time of a file to be accepted in milliseconds * since January 1, 1970 UTC (including). * @param pathExclusionFilter * files with this substring path will be excluded */ public JobFileModifiedRangeSubstringPathFilter(Configuration myConf, long minModificationTimeMillis, long maxModificationTimeMillis, String[] pathExclusionFilter, String[] pathInclusionFilter) { this.myConf = myConf; this.minModificationTimeMillis = minModificationTimeMillis; this.maxModificationTimeMillis = maxModificationTimeMillis; this.pathExclusionFilter = pathExclusionFilter; this.pathInclusionFilter = pathInclusionFilter; } /* * (non-Javadoc) * * @see * com.twitter.hraven.etl.JobFilePathFilter#accept(org.apache * .hadoop.fs.Path) */ @Override public boolean accept(Path path) { if (!super.accept(path)) { return false; } JobFile jobFile = new JobFile(path.getName()); if (jobFile.isJobConfFile() || jobFile.isJobHistoryFile()) { if (jobFile.isJobHistoryFile()) { if (!includesPathSubstrings(path) || !excludesPathSubstrings(path)) { return false; } } try { FileSystem fs = path.getFileSystem(myConf); FileStatus fileStatus = fs.getFileStatus(path); long fileModificationTimeMillis = fileStatus.getModificationTime(); return accept(fileModificationTimeMillis); } catch (IOException e) { throw new ImportException("Cannot determine file modification time of " + path.getName(), e); } } else { // Reject anything that does not match a job conf filename. LOG.info(" Not a valid job conf / job history file " + path.getName()); return false; } } private boolean excludesPathSubstrings(Path path) { if (pathExclusionFilter == null) return true; for (String s: pathExclusionFilter) { if (path.toString().indexOf(s) != -1) return false; } return true; } private boolean includesPathSubstrings(Path path) { if (pathInclusionFilter == null) return true; for (String s: pathInclusionFilter) { if (path.toString().indexOf(s) != -1) return true; } return false; } /** * @param fileModificationTimeMillis * in milliseconds since January 1, 1970 UTC * @return whether a file with such modification time is to be accepted. */ public boolean accept(long fileModificationTimeMillis) { return ((minModificationTimeMillis < fileModificationTimeMillis) && (fileModificationTimeMillis <= maxModificationTimeMillis)); } /** * @return the minModificationTimeMillis used in for this filter. */ public long getMinModificationTimeMillis() { return minModificationTimeMillis; } /** * @return the maxModificationTimeMillis used for this filter */ public long getMaxModificationTimeMillis() { return maxModificationTimeMillis; } }
33.502538
134
0.706061
a4963f9a1a01ac928293d287b58313f737c23d47
959
package com.qd; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class GreetingClient { public static void main(String[] args){ String serverName = args[0]; int port = Integer.parseInt(args[1]); try{ System.out.println("connecting to "+serverName+"on port "+ port); Socket client = new Socket(serverName,port); System.out.println("Just connected to "+client.getRemoteSocketAddress()); OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); out.writeUTF("Hello from "+ client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server say:"+ in.readUTF()); client.close(); }catch(IOException e){ e.printStackTrace(); } } }
31.966667
76
0.74244
ef8cbfaffa28d5b4d48656251acd0aa8311d0e74
644
package co.com.wwb.game.db; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity(name="Ciudad") @Table(name="CIUDAD") public class Ciudad { @Id private String codigo; private String nombre; /** * @return the codigo */ public String getCodigo() { return codigo; } /** * @param codigo the codigo to set */ public void setCodigo(String codigo) { this.codigo = codigo; } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; } }
14.311111
39
0.664596
0d4f99929dee1c8c9082b56a52e3dd7463e7b259
12,838
/* * Copyright 2000-2010 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 org.jetbrains.android.compiler; import com.android.SdkConstants; import com.android.sdklib.IAndroidTarget; import com.intellij.facet.FacetManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.*; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.roots.CompilerModuleExtension; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.android.compiler.tools.AndroidDxWrapper; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.android.facet.AndroidRootUtil; import org.jetbrains.android.maven.AndroidMavenProvider; import org.jetbrains.android.maven.AndroidMavenUtil; import org.jetbrains.android.sdk.AndroidPlatform; import org.jetbrains.android.util.AndroidBuildCommonUtils; import org.jetbrains.android.util.AndroidBundle; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.*; /** * Android Dex compiler. */ public class AndroidDexCompiler implements ClassPostProcessingCompiler { @Override @NotNull public ProcessingItem[] getProcessingItems(@NotNull CompileContext context) { return ApplicationManager.getApplication().runReadAction(new PrepareAction(context)); } @Override public ProcessingItem[] process(@NotNull CompileContext context, @NotNull ProcessingItem[] items) { if (!AndroidCompileUtil.isFullBuild(context)) { return ProcessingItem.EMPTY_ARRAY; } if (items.length > 0) { context.getProgressIndicator().setText("Generating " + AndroidBuildCommonUtils.CLASSES_FILE_NAME + "..."); return new ProcessAction(context, items).compute(); } return ProcessingItem.EMPTY_ARRAY; } @Override @NotNull public String getDescription() { return FileUtil.getNameWithoutExtension(SdkConstants.FN_DX); } @Override public boolean validateConfiguration(CompileScope scope) { return true; } @Override public ValidityState createValidityState(DataInput in) throws IOException { return new MyValidityState(in); } public static VirtualFile getOutputDirectoryForDex(@NotNull Module module) { if (AndroidMavenUtil.isMavenizedModule(module)) { AndroidMavenProvider mavenProvider = AndroidMavenUtil.getMavenProvider(); if (mavenProvider != null) { String buildDirPath = mavenProvider.getBuildDirectory(module); if (buildDirPath != null) { VirtualFile buildDir = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(buildDirPath)); if (buildDir != null) { return buildDir; } } } } return CompilerModuleExtension.getInstance(module).getCompilerOutputPath(); } static void addModuleOutputDir(Collection<VirtualFile> files, VirtualFile dir) { // only include files inside packages for (VirtualFile child : dir.getChildren()) { if (child.isDirectory()) { files.add(child); } } } private static final class PrepareAction implements Computable<ProcessingItem[]> { private final CompileContext myContext; public PrepareAction(CompileContext context) { myContext = context; } @Override public ProcessingItem[] compute() { final AndroidDexCompilerConfiguration dexConfig = AndroidDexCompilerConfiguration.getInstance(myContext.getProject()); Module[] modules = ModuleManager.getInstance(myContext.getProject()).getModules(); List<ProcessingItem> items = new ArrayList<ProcessingItem>(); for (Module module : modules) { AndroidFacet facet = FacetManager.getInstance(module).getFacetByType(AndroidFacet.ID); if (facet != null && facet.getConfiguration().isAppProject()) { final VirtualFile dexOutputDir = getOutputDirectoryForDex(module); Collection<VirtualFile> files; final boolean shouldRunProguard = AndroidCompileUtil.getProguardConfigFilePathIfShouldRun(facet, myContext) != null; if (shouldRunProguard) { final VirtualFile obfuscatedSourcesJar = dexOutputDir.findChild(AndroidBuildCommonUtils.PROGUARD_OUTPUT_JAR_NAME); if (obfuscatedSourcesJar == null) { myContext.addMessage(CompilerMessageCategory.INFORMATION, "Dex won't be launched for module " + module.getName() + " because file " + AndroidBuildCommonUtils.PROGUARD_OUTPUT_JAR_NAME + " doesn't exist", null, -1, -1, null, Collections.singleton(module.getName())); continue; } files = Collections.singleton(obfuscatedSourcesJar); } else { CompilerModuleExtension extension = CompilerModuleExtension.getInstance(module); VirtualFile outputDir = extension.getCompilerOutputPath(); if (outputDir == null) { myContext.addMessage(CompilerMessageCategory.INFORMATION, "Dex won't be launched for module " + module.getName() + " because it doesn't contain compiled files", null, -1, -1, null, Collections.singleton(module.getName())); continue; } files = new HashSet<VirtualFile>(); addModuleOutputDir(files, outputDir); files.addAll(AndroidRootUtil.getExternalLibraries(module)); for (VirtualFile file : AndroidRootUtil.getDependentModules(module, outputDir)) { if (file.isDirectory()) { addModuleOutputDir(files, file); } else { files.add(file); } } if (facet.getProperties().PACK_TEST_CODE) { VirtualFile outputDirForTests = extension.getCompilerOutputPathForTests(); if (outputDirForTests != null) { addModuleOutputDir(files, outputDirForTests); } } } final AndroidPlatform platform = AndroidPlatform.getInstance(module); if (platform == null) { myContext.addMessage(CompilerMessageCategory.ERROR, AndroidBundle.message("android.compilation.error.specify.platform", module.getName()), null, -1, -1, null, Collections.singleton(module.getName())); continue; } StringBuilder options = new StringBuilder(dexConfig.VM_OPTIONS); //JpsAndroidModuleProperties state = configuration.getState(); //if (state != null ) { // if (state.ENABLE_MULTI_DEX) { // options.append(" --multi-dex"); // } // if (!StringUtil.isEmpty(state.MAIN_DEX_LIST)) { // options.append(" --main-dex-list ").append(state.MAIN_DEX_LIST); // } // if (state.MINIMAL_MAIN_DEX) { // options.append(" --minimal-main-dex"); // } //} items.add(new DexItem(module, dexOutputDir, platform.getTarget(), files, options.toString(), dexConfig.MAX_HEAP_SIZE, dexConfig.OPTIMIZE)); } } return items.toArray(ProcessingItem.EMPTY_ARRAY); } } private final static class ProcessAction implements Computable<ProcessingItem[]> { private final CompileContext myContext; private final ProcessingItem[] myItems; public ProcessAction(CompileContext context, ProcessingItem[] items) { myContext = context; myItems = items; } @Override public ProcessingItem[] compute() { List<ProcessingItem> results = new ArrayList<ProcessingItem>(myItems.length); for (ProcessingItem item : myItems) { if (item instanceof DexItem) { DexItem dexItem = (DexItem)item; if (!AndroidCompileUtil.isModuleAffected(myContext, dexItem.myModule)) { continue; } String outputDirPath = FileUtil.toSystemDependentName(dexItem.myClassDir.getPath()); String[] files = new String[dexItem.myFiles.size()]; int i = 0; for (VirtualFile file : dexItem.myFiles) { files[i++] = FileUtil.toSystemDependentName(file.getPath()); } Map<CompilerMessageCategory, List<String>> messages = AndroidCompileUtil.toCompilerMessageCategoryKeys(AndroidDxWrapper.execute( dexItem.myModule, dexItem.myAndroidTarget, outputDirPath, files, dexItem.myAdditionalVmParams, dexItem.myMaxHeapSize, dexItem.myOptimize)); addMessages(messages, dexItem.myModule); if (messages.get(CompilerMessageCategory.ERROR).isEmpty()) { results.add(dexItem); } } } return results.toArray(ProcessingItem.EMPTY_ARRAY); } private void addMessages(Map<CompilerMessageCategory, List<String>> messages, Module module) { for (CompilerMessageCategory category : messages.keySet()) { List<String> messageList = messages.get(category); for (String message : messageList) { myContext.addMessage(category, '[' + module.getName() + "] " + message, null, -1, -1, null, Collections.singleton(module.getName())); } } } } private final static class DexItem implements ProcessingItem { final Module myModule; final VirtualFile myClassDir; final IAndroidTarget myAndroidTarget; final Collection<VirtualFile> myFiles; final String myAdditionalVmParams; final int myMaxHeapSize; final boolean myOptimize; public DexItem(@NotNull Module module, @NotNull VirtualFile classDir, @NotNull IAndroidTarget target, Collection<VirtualFile> files, @NotNull String additionalVmParams, int maxHeapSize, boolean optimize) { myModule = module; myClassDir = classDir; myAndroidTarget = target; myFiles = files; myAdditionalVmParams = additionalVmParams; myMaxHeapSize = maxHeapSize; myOptimize = optimize; } @Override @NotNull public VirtualFile getFile() { return myClassDir; } @Override @Nullable public ValidityState getValidityState() { return new MyValidityState(myFiles, myAdditionalVmParams, myMaxHeapSize, myOptimize); } } private static class MyValidityState extends ClassesAndJarsValidityState { private final String myAdditionalVmParams; private final int myMaxHeapSize; private final boolean myOptimize; public MyValidityState(@NotNull Collection<VirtualFile> files, @NotNull String additionalVmParams, int maxHeapSize, boolean optimize) { super(files); myAdditionalVmParams = additionalVmParams; myMaxHeapSize = maxHeapSize; myOptimize = optimize; } public MyValidityState(@NotNull DataInput in) throws IOException { super(in); myAdditionalVmParams = in.readUTF(); myMaxHeapSize = in.readInt(); myOptimize = in.readBoolean(); } @Override public void save(DataOutput out) throws IOException { super.save(out); out.writeUTF(myAdditionalVmParams); out.writeInt(myMaxHeapSize); out.writeBoolean(myOptimize); } @Override public boolean equalsTo(ValidityState otherState) { if (!super.equalsTo(otherState)) { return false; } if (!(otherState instanceof MyValidityState)) { return false; } final MyValidityState state = (MyValidityState)otherState; return state.myAdditionalVmParams.equals(myAdditionalVmParams) && state.myMaxHeapSize == myMaxHeapSize && state.myOptimize == myOptimize; } } }
37.648094
181
0.66163
ee017d7d41f46ceab652dc8a14ecb8a60bcbfaf6
953
package cn.robby.rpc.log_append; import cn.robby.common.util.codec.BooleanCodec; import cn.robby.common.value_obj.Term; import cn.robby.rpc.AbstractRpcCodec; import io.netty.buffer.ByteBuf; import lombok.Getter; import lombok.Setter; @Getter @Setter public class LogAppendResponse extends AbstractRpcCodec { // term当前任期,对于领导人而言 它会更新自己的任期 // 如果跟随者所含有的条目和 prevLogIndex 以及 prevLogTerm 匹配上了,则为 true private boolean success; @Override protected void subSerialize(ByteBuf buffer) { buffer.writeBytes(BooleanCodec.Serialize(success)); } @Override public LogAppendResponse deserialize(ByteBuf byteBuf) { LogAppendResponse appendResp = new LogAppendResponse(); appendResp.setTerm(new Term(byteBuf.readInt())); appendResp.setSuccess(BooleanCodec.deserialize(byteBuf.readInt())); return appendResp; } @Override protected int getType() { return logAppendResp; } }
27.228571
75
0.732424
a537052411f8b27b42bd7bafd4cd3c2b05aa9d4b
294
package io.nuls.api.db; import io.nuls.api.model.po.db.ChainConfigInfo; import io.nuls.api.model.po.db.ChainInfo; /** * */ public interface DBTableService { void initCache(); void addDefaultChainCache(); void addChainCache(ChainInfo chainInfo, ChainConfigInfo configInfo); }
17.294118
72
0.734694
275e7a74c90477a2def358c552ac5cd984478535
3,365
package org.hmsystem.server.config.secret; import org.hmsystem.server.utils.MyPasswordEncoder; import org.hmsystem.server.pojo.Usertable; import org.hmsystem.server.service.IUsertableService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private IUsertableService usertableService; @Autowired private RestAuthorizationEntryPoint restAuthorizationEntryPoint; @Autowired private RestfulAccessDeniedHandler restfulAccessDeniedHandler; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder()); } @Override public void configure(WebSecurity web) throws Exception { //端口放行 web.ignoring().antMatchers( "/login", "/logout", "/css/**", "/js/**", "/index.html", "/favicon.ico", "/doc.html", "/webjars/**", "/swagger-resources/**", "/v2/api-docs/**", "/captcha", "/register", "/userInfo" ); } @Override protected void configure(HttpSecurity http) throws Exception { //使用jwt不需要csrf http.csrf() .disable() //基于token,不需要session .sessionManagement() .and() .authorizeRequests() //除了上面的,所有请求都需要认证 .anyRequest() .authenticated() .and() .headers() .cacheControl(); //添加jwt登录授权过滤器 http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class); //添加自定义未授权和为登录结果返回 http.exceptionHandling() .accessDeniedHandler(restfulAccessDeniedHandler) .authenticationEntryPoint(restAuthorizationEntryPoint); } @Override @Bean public UserDetailsService userDetailsService() { return username -> { Usertable user = usertableService.getUserByUserName(username); if (null != user) { return user; } return null; }; } @Bean public PasswordEncoder passwordEncoder() { return new MyPasswordEncoder(); } @Bean public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() { return new JwtAuthenticationTokenFilter(); } }
33.316832
107
0.654086
9d06c069ea1448626066c9fa7875335c392dc817
210
package com.oral.service; import com.oral.bean.Operationtype; import com.baomidou.mybatisplus.extension.service.IService; /** * */ public interface OperationtypeService extends IService<Operationtype> { }
17.5
71
0.790476
ae5e18b96b3fe80b9668310cd0a9240518c4fc82
779
package com.user.validator; import com.user.validator.commons.AbstractValidator; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import lombok.experimental.FieldDefaults; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; // Lombok @FieldDefaults(level = AccessLevel.PRIVATE) @Getter @Setter public class AddressValidator extends AbstractValidator { @NotNull(message = "") @NotEmpty String alias; @NotNull(message = "") @NotEmpty String name; String building; // Building, floor... @NotNull(message = "") @NotEmpty String street; // Street, house number, box number @NotNull(message = "") @NotEmpty String postcode; // Postcode and name of municipality }
21.054054
57
0.726573
c1cf740a0d1d8bf4879d4e0d599e1e0b32092127
1,014
package cgeo.geocaching.settings; import cgeo.geocaching.connector.ec.ECConnector; import cgeo.geocaching.connector.ec.ECLogin; import cgeo.geocaching.enumerations.StatusCode; import org.apache.commons.lang3.tuple.ImmutablePair; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; public class CheckECCredentialsPreference extends AbstractCheckCredentialsPreference { public CheckECCredentialsPreference(Context context, AttributeSet attrs) { super(context, attrs); } public CheckECCredentialsPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected ImmutablePair<String, String> getCredentials() { return Settings.getCredentials(ECConnector.getInstance()); } @Override protected ImmutablePair<StatusCode, Drawable> login() { return new ImmutablePair<StatusCode, Drawable>(ECLogin.getInstance().login(), null); } }
30.727273
92
0.767258
fbe4f29c9512c69b573db409cf0faa8425f87bee
122
package com.ggbwallet.app.ui.widget; public interface OnImportPrivateKeyListener { void onPrivateKey(String key); }
17.428571
45
0.786885
5b013fb4d9311f1d365b00a09338b7b592623878
7,159
package mchorse.chameleon.geckolib; import mchorse.chameleon.ClientProxy; import mchorse.mclib.utils.Interpolations; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.EnumFacing; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import software.bernie.geckolib3.core.builder.Animation; import software.bernie.geckolib3.core.easing.EasingManager; import software.bernie.geckolib3.core.keyframe.BoneAnimation; import software.bernie.geckolib3.core.keyframe.KeyFrame; import software.bernie.geckolib3.core.keyframe.VectorKeyFrameList; import software.bernie.geckolib3.core.snapshot.BoneSnapshot; import software.bernie.geckolib3.geo.render.built.GeoBone; import software.bernie.geckolib3.geo.render.built.GeoModel; import software.bernie.shadowed.eliotlash.mclib.math.IValue; import javax.vecmath.Vector3d; import java.util.List; @SideOnly(Side.CLIENT) public class ChameleonAnimator { public static void resetPose(GeoModel model) { for (GeoBone bone : model.topLevelBones) { resetBone(bone); } } private static void resetBone(GeoBone bone) { BoneSnapshot initial = bone.getInitialSnapshot(); bone.setPositionX(initial.positionOffsetX); bone.setPositionY(initial.positionOffsetY); bone.setPositionZ(initial.positionOffsetZ); bone.setRotationX(initial.rotationValueX); bone.setRotationY(initial.rotationValueY); bone.setRotationZ(initial.rotationValueZ); bone.setScaleX(initial.scaleValueX); bone.setScaleY(initial.scaleValueY); bone.setScaleZ(initial.scaleValueZ); for (GeoBone childBone : bone.childBones) { resetBone(childBone); } } public static void animate(EntityLivingBase target, GeoModel model, Animation animation, float frame, float blend, boolean skipInitial) { MolangHelper.setMolangVariables(ClientProxy.parser, target, frame); for (GeoBone bone : model.topLevelBones) { animateBone(bone, animation, frame, blend, skipInitial); } } private static void animateBone(GeoBone bone, Animation animation, float frame, float blend, boolean skipInitial) { boolean applied = false; for (BoneAnimation boneAnimation : animation.boneAnimations) { if (boneAnimation.boneName.equals(bone.name)) { applyBoneAnimation(bone, boneAnimation, frame, blend); applied = true; break; } } if (!applied && !skipInitial) { BoneSnapshot initial = bone.getInitialSnapshot(); bone.setPositionX(Interpolations.lerp(bone.getPositionX(), initial.positionOffsetX, blend)); bone.setPositionY(Interpolations.lerp(bone.getPositionY(), initial.positionOffsetY, blend)); bone.setPositionZ(Interpolations.lerp(bone.getPositionZ(), initial.positionOffsetZ, blend)); bone.setRotationX(Interpolations.lerp(bone.getRotationX(), initial.rotationValueX, blend)); bone.setRotationY(Interpolations.lerp(bone.getRotationY(), initial.rotationValueY, blend)); bone.setRotationZ(Interpolations.lerp(bone.getRotationZ(), initial.rotationValueZ, blend)); bone.setScaleX(Interpolations.lerp(bone.getScaleX(), initial.scaleValueX, blend)); bone.setScaleY(Interpolations.lerp(bone.getScaleY(), initial.scaleValueY, blend)); bone.setScaleZ(Interpolations.lerp(bone.getScaleZ(), initial.scaleValueZ, blend)); } for (GeoBone childBone : bone.childBones) { animateBone(childBone, animation, frame, blend, skipInitial); } } private static void applyBoneAnimation(GeoBone geoBone, BoneAnimation boneAnimation, float frame, float blend) { Vector3d pos = interpolateList(boneAnimation.positionKeyFrames, frame, MolangHelper.Component.POSITION); Vector3d rot = interpolateList(boneAnimation.rotationKeyFrames, frame, MolangHelper.Component.ROTATION); Vector3d scale = interpolateList(boneAnimation.scaleKeyFrames, frame, MolangHelper.Component.SCALE); BoneSnapshot initial = geoBone.getInitialSnapshot(); geoBone.setPositionX(Interpolations.lerp(geoBone.getPositionX(), (float) pos.x + initial.positionOffsetX, blend)); geoBone.setPositionY(Interpolations.lerp(geoBone.getPositionY(), (float) pos.y + initial.positionOffsetY, blend)); geoBone.setPositionZ(Interpolations.lerp(geoBone.getPositionZ(), (float) pos.z + initial.positionOffsetZ, blend)); geoBone.setRotationX(Interpolations.lerp(geoBone.getRotationX(), (float) (rot.x / 180 * Math.PI) + initial.rotationValueX, blend)); geoBone.setRotationY(Interpolations.lerp(geoBone.getRotationY(), (float) (rot.y / 180 * Math.PI) + initial.rotationValueY, blend)); geoBone.setRotationZ(Interpolations.lerp(geoBone.getRotationZ(), (float) (rot.z / 180 * Math.PI) + initial.rotationValueZ, blend)); geoBone.setScaleX(Interpolations.lerp(geoBone.getScaleX(), (float) scale.x + initial.scaleValueX, blend)); geoBone.setScaleY(Interpolations.lerp(geoBone.getScaleY(), (float) scale.y + initial.scaleValueY, blend)); geoBone.setScaleZ(Interpolations.lerp(geoBone.getScaleZ(), (float) scale.z + initial.scaleValueZ, blend)); } private static Vector3d interpolateList(VectorKeyFrameList<KeyFrame<IValue>> keyframes, float frame, MolangHelper.Component component) { Vector3d vector = new Vector3d(); vector.x = interpolate(keyframes.xKeyFrames, frame, component, EnumFacing.Axis.X); vector.y = interpolate(keyframes.yKeyFrames, frame, component, EnumFacing.Axis.Y); vector.z = interpolate(keyframes.zKeyFrames, frame, component, EnumFacing.Axis.Z); return vector; } private static double interpolate(List<KeyFrame<IValue>> keyframes, float frame, MolangHelper.Component component, EnumFacing.Axis axis) { if (keyframes.isEmpty()) { return 0; } KeyFrame<IValue> first = keyframes.get(0); if (frame < first.getLength()) { return MolangHelper.getValue(first.getStartValue(), component, axis); } double duration = 0; KeyFrame<IValue> previous = null; for (KeyFrame<IValue> kf : keyframes) { if (frame >= duration && frame < duration + kf.getLength()) { double factor = EasingManager.ease((frame - duration) / kf.getLength().floatValue(), kf.easingType, kf.easingArgs); double start = MolangHelper.getValue(kf.getStartValue(), component, axis); double destination = MolangHelper.getValue(kf.getEndValue(), component, axis); return Interpolations.lerp(start, destination, factor); } duration += kf.getLength(); previous = kf; } return MolangHelper.getValue(previous.getEndValue(), component, axis); } }
42.111765
140
0.691158
388a83b5fd0606ac3771d3f574d3de1916c2e9c6
4,648
/* *Copyright (c) 2005-2010, 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.carbon.esb.mediator.test.iterate; import org.apache.axis2.AxisFault; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.esb.integration.common.utils.ESBIntegrationTest; import org.wso2.esb.integration.common.utils.ESBTestConstant; import static org.testng.Assert.assertEquals; /** * This class will test iterator mediator when invalid name space is set for both fields 'attachPath' * and 'iterate expression' */ public class InvalidNamespaceTestCase extends ESBIntegrationTest { @BeforeClass(alwaysRun = true) public void uploadSynapseConfig() throws Exception { super.init(); } /** * This test sets invalid name space specified for 'AttachPath' field and mediate the messages and verify * error handling by sending stock quote requests. Error in attaching the splitted elements,Unable to get * the attach path specified by the expression */ @Test(groups = { "wso2.esb" }, description = "Testing invalid namespace for 'attachPath' field") public void testInvalidNameSpaceForAttachPath() throws Exception { try { axis2Client.sendMultipleQuoteRequest( getProxyServiceURLHttp("iterateWithInvalidNameSpaceForAttachPathTestProxy"), null, "WSO2", 5); Assert.fail( "This Request must throw AxisFault"); // This will execute when the exception is not thrown as expected } catch (AxisFault message) { assertEquals(message.getReason(), ESBTestConstant.READ_TIME_OUT, "Iterator mediator worked even with an invalid name space for 'attachPath' field."); } } /** * This test sets invalid name space specified for 'AttachPath' field and mediate the message and verify error * handling by sending stock quote requests. Evaluation of the XPath expression will not throw exceptions, but * it will time out */ @Test(groups = { "wso2.esb" }, description = "Testing invalid namespace for 'iterate expression' field") public void testInvalidNameSpaceForIterateExpression() throws Exception { try { axis2Client.sendMultipleQuoteRequest( getProxyServiceURLHttp("iterateWithInvalidNameSpaceForExpressionTestProxy"), null, "WSO2", 5); Assert.fail( "This Request must throw AxisFault"); // This will execute when the exception is not thrown as expected } catch (AxisFault message) { assertEquals(message.getReason(), ESBTestConstant.READ_TIME_OUT, "Iterator mediator worked even with an invalid name space for 'iterate expression' field."); } } /** * This test define a valid iterate expression which does NOT match with the original message and do mediation * to see error handling.No exceptions will be thrown but request will time out. */ @Test(groups = { "wso2.esb" }, description = "Testing valid expression which mismatch the original message in 'iterate expression' field") public void testValidIterateExpressionMismatchOriginalMessage() throws Exception { try { axis2Client.sendMultipleQuoteRequest( getProxyServiceURLHttp("iterateWithValidIterateExpressionMismatchToOriginalMessageTestProxy"), null, "WSO2", 10); Assert.fail( "This Request must throw AxisFault"); // This will execute when the exception is not thrown as expected } catch (AxisFault message) { assertEquals(message.getReason(), ESBTestConstant.READ_TIME_OUT, "Iterator mediator worked with a valid iterate expression which mismatches the original message."); } } @AfterClass(groups = "wso2.esb") public void close() throws Exception { super.cleanup(); } }
44.692308
133
0.696213
d2f5d0dea7ba7ba98f106b43f90d3a0e9d8df506
75
package com.github.lindenb.jvarkit.chart; public class ChartExporter { }
12.5
41
0.786667
ab40e95b86ec467d2c0553122810b6d21125bc68
3,069
package org.spellwind; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.spellwind.model.World; import org.spellwind.net.MudPipelineFactory; import org.spellwind.persist.PersistenceManager; import org.spellwind.task.TaskQueue; /** * The core class of the MUD server. * @author Graham Edgecombe */ public final class Server { /** * The logger instance. */ private static final Logger logger = Logger.getLogger(Server.class.getName()); /** * The entry point of the server. This method will simply create a new * <code>Server</code> object, call the {@link #start()} method and log any * exceptions that occur. * @param args The command-line arguments. */ public static void main(String[] args) { try { logger.info("Loading configuration..."); ServerConfiguration configuration = PersistenceManager.getManager().loadConfiguration(); Server server = new Server(configuration); server.start(); } catch(Throwable t) { logger.log(Level.SEVERE, "Error starting server.", t); } } /** * The server configuration. */ private final ServerConfiguration configuration; /** * The <code>ServerBootstrap</code> object. */ private final ServerBootstrap bootstrap = new ServerBootstrap(); /** * Creates the server, initialising Netty and the game world. * @param port The configuration. */ public Server(ServerConfiguration configuration) { logger.info("Starting Spellwind..."); this.configuration = configuration; initNetty(); initWorld(); } /** * Initialises Netty by: * <ul> * <li>Creating the thread pools.</li> * <li>Creating the channel factory.</li> * <li>Creating the pipeline factory.</li> * </ul> */ private void initNetty() { logger.info("Bootstrapping Netty..."); ExecutorService bossExecutor = Executors.newCachedThreadPool(); ExecutorService workerExecutor = Executors.newCachedThreadPool(); bootstrap.setFactory(new NioServerSocketChannelFactory(bossExecutor, workerExecutor)); bootstrap.setPipelineFactory(new MudPipelineFactory()); } /** * Initialises the game world. */ private void initWorld() { logger.info("Creating game world..."); World.getWorld().init(); } /** * Starts the server and continues processing <code>Task</code>s until the * server is shut down. */ public void start() { logger.info("Binding to port: " + configuration.getPort() + "..."); bootstrap.bind(new InetSocketAddress(configuration.getPort())); logger.info("Ready for connections."); processTasks(); } /** * Processes <code>Task</code>s in the <code>TaskQueue</code> until the * server is shut down. */ private void processTasks() { while(TaskQueue.isRunning()) { boolean interrupted = TaskQueue.processNextTask(); if(interrupted) { continue; } } } }
26.921053
91
0.714565
0199ffdd3481f54bd7153fa2c68014bcae0c6d19
2,450
package io.snyk.gradle.plugin; import org.gradle.api.GradleException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Runner { private Runner() { } public static Result runSnyk(String task) { return runCommand(Meta.getInstance().getBinary() + " " + task); } public static Result runCommand(String task) { try { Process process = Runtime.getRuntime().exec(task + " --integration-name=GRADLE_PLUGIN"); try ( BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())) ) { String line; StringBuilder content = new StringBuilder(); StringBuilder error = new StringBuilder(); boolean hasError = false; while ((line = stdInput.readLine()) != null) { content.append("\n"); content.append(line); } while ((line = stdError.readLine()) != null) { if (!hasError) hasError = true; content.append("\n"); error.append(line); } process.waitFor(); int exitStatus = process.exitValue(); String result = content + (hasError ? "Error: " + error : ""); return new Result(result, exitStatus); } } catch (InterruptedException e) { throw new GradleException("Internal error", e); } catch (IOException e) { return new Result(e.getMessage(), 1); } } public static class Result { String output; int exitcode; public Result(String output, int exitcode) { this.output = output; this.exitcode = exitcode; } public String getOutput() { return output; } public int getExitcode() { return exitcode; } public boolean failed() { return exitcode != 0; } @Override public String toString() { return "Result{" + "output='" + output + '\'' + ", exitcode=" + exitcode + '}'; } } }
28.823529
110
0.514286
42922c350f6ddc09b065aeb8d614de1e92556791
1,474
package java.util.zip; import org.checkerframework.checker.javari.qual.*; interface ZipConstants { static long LOCSIG = 0x04034b50L; static long EXTSIG = 0x08074b50L; static long CENSIG = 0x02014b50L; static long ENDSIG = 0x06054b50L; static final int LOCHDR = 30; static final int EXTHDR = 16; static final int CENHDR = 46; static final int ENDHDR = 22; static final int LOCVER = 4; static final int LOCFLG = 6; static final int LOCHOW = 8; static final int LOCTIM = 10; static final int LOCCRC = 14; static final int LOCSIZ = 18; static final int LOCLEN = 22; static final int LOCNAM = 26; static final int LOCEXT = 28; static final int EXTCRC = 4; static final int EXTSIZ = 8; static final int EXTLEN = 12; static final int CENVEM = 4; static final int CENVER = 6; static final int CENFLG = 8; static final int CENHOW = 10; static final int CENTIM = 12; static final int CENCRC = 16; static final int CENSIZ = 20; static final int CENLEN = 24; static final int CENNAM = 28; static final int CENEXT = 30; static final int CENCOM = 32; static final int CENDSK = 34; static final int CENATT = 36; static final int CENATX = 38; static final int CENOFF = 42; static final int ENDSUB = 8; static final int ENDTOT = 10; static final int ENDSIZ = 12; static final int ENDOFF = 16; static final int ENDCOM = 20; }
28.901961
50
0.65943