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
4afc1d10c6a1b992c4db2b56047971c6a9f7297e
861
public class Solution { public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> map = new HashMap(); int n = strs.length; for (String s : strs) { char[] chars = s.toCharArray(); Arrays.sort(chars); String keyStr = String.valueOf(chars); if (!map.containsKey(keyStr)) map.put(keyStr, new ArrayList()); map.get(keyStr).add(s); } return new ArrayList<List<String>>(map.values()); } } // faster solution 2, using counting sort (below is in c++) string strSort(string& s) { int count[26] = {0}, n = s.length(); for (int i = 0; i < n; i++) count[s[i] - 'a']++; int p = 0; string t(n, 'a'); for (int j = 0; j < 26; j++) for (int i = 0; i < count[j]; i++) t[p++] += j; return t; }
30.75
75
0.509872
bb3e3d5a6cb7561b12532ed591732ce93a614d9b
2,583
package cn.jungmedia.android.ui.user.presenter; import cn.jungmedia.android.ui.user.bean.UserInfo; import cn.jungmedia.android.R; import cn.jungmedia.android.ui.user.presenter.UserContract.LoginPresenter; import com.leon.common.basebean.BaseRespose; import com.leon.common.baserx.RxSubscriber; /*** * * @Copyright 2018 * * @TODO * * @author niufei * * * @date 2018/3/17. 下午7:26 * * */ public class LoginPresenterImp extends LoginPresenter { @Override public void getVerifyCode(String phone) { mRxManage.add(mModel.getVerifyCode(phone).subscribe(new RxSubscriber<BaseRespose<String>>(mContext, false) { @Override public void onStart() { super.onStart(); mView.showLoading(mContext.getString(R.string.loading)); } @Override protected void _onNext(BaseRespose<String> data) { mView.returnVerifyCode(data); mView.stopLoading(); } @Override protected void _onError(String message) { mView.showErrorTip(message); } })); } @Override public void accountLogin(String phone, String pwd) { mRxManage.add(mModel.accountLogin(phone, pwd).subscribe(new RxSubscriber<BaseRespose<UserInfo>>(mContext, false) { @Override public void onStart() { super.onStart(); mView.showLoading(mContext.getString(R.string.loading)); } @Override protected void _onNext(BaseRespose<UserInfo> data) { mView.returnLoginResponse(data); mView.stopLoading(); } @Override protected void _onError(String message) { mView.showErrorTip(message); } })); } @Override public void mobileLogin(String phone, String code) { mRxManage.add(mModel.mobileLogin(phone, code).subscribe(new RxSubscriber<BaseRespose<UserInfo>>(mContext, false) { @Override public void onStart() { super.onStart(); mView.showLoading(mContext.getString(R.string.loading)); } @Override protected void _onNext(BaseRespose<UserInfo> data) { mView.returnLoginResponse(data); mView.stopLoading(); } @Override protected void _onError(String message) { mView.showErrorTip(message); } })); } }
28.7
122
0.577236
79fef2838fb7563a6b7e92cabad023e3ee4ef62a
217
package com.cisco.restAPI.repository; import com.cisco.restAPI.dataObjects.Task; import org.springframework.data.jpa.repository.JpaRepository; public interface TaskRepository extends JpaRepository<Task,Integer> { }
27.125
69
0.83871
c461b1356c76c2dab038e03dc133d131c46a46fd
3,081
package com.example.mybatis.demomybatis.algorithms; import lombok.extern.slf4j.Slf4j; /** * 归并排序是稳定的:时间复杂度nlogn * 相较于{@link MergeSort},不使用辅助数组 * @author jacksparrow414 * @date 2021/3/6 */ @Slf4j public class AdvancedMergeSort { /** * 不允许使用辅助数组,如何判断到了递归的终止条件处? * 只能根据现有条件来找思路。 * 现在只有一个数组,能找到可用的东西数组元素本身,数组的两个下标(数组的最大下标和最小下标) * * @see MergeSort#mergeNewArray(int[]) 方法中使用辅助数组可以清晰的知道原始数组被分成了什么样子? * 不让用辅助数组,不让用辅助数组......那可以和下面的方法采取一样的思考方法,可以通过标记位来标记成一个假的辅助数组 * 原始数组进来,必然要在中间被分,为什么?废话,归并算法的思想就是分成两路 * 既然在中间被分了,那么low->mid就可以视作arrayOne,mid+1->high就可以视作arrayTwo * 按照这个思路继续递归去分隔,那么接下来递归的应该是刚才被拆的第一个伪数组,low还是不变,那么此数组的最大长度也就到mid * 同理,第二个数组递归时,mid+1的位置视为第二个数组开始位 * * 就这样,一直递归递归下去,到最后,肯定不能判断nums.length==1的方式了,因为nums在这里就是原始数组,里面的元素根本没变过 * 随着两个low和high指针的不断靠近,最终会重合 */ public void mergeSort(int[] nums, int low, int high) { // 也就是上面所说的重合条件,也可以换成 low < high if (low < high) { // 这里为什么不使用( low + high ) /2 有可能出现数字越界,超过int最大值 int mid = low + (high-low) / 2; mergeSort(nums, low, mid); mergeSort(nums, mid+1, high); // 最终归并之前,需要传入三个标记位来判断两个伪数组的界限 doMerge(nums, low, mid, high); } } /** * 既然没有辅助数组,那么比较就不能再两个数组之间比较了.就需要在原始数组上比较 * 如何在原始数组上比较呢?一开始我也是没思路,既然没思路,莫不如造点数据 * 假设,经过递归,最后一次合并之前,此时的数组变为了{1,3,5,7,9}和{2,4,6,8} * 面对这样的数组怎么处理?要想实现和{@link MergeSort#doNewMerge(int[], int[])}一样的效果 * 那么就要确定这两个部分的开始、结束位置。而两个数组入参的情况的方法,直接分别从两个数组下标为0的位置开始即可 * * 但是在这里只有一个数组,如何把这两部分区分开?用标记位判断 * low到mid的位置就可以被视为第一个数组 * mid+1到high的位置可以被视为第二个数组 * * 根据这个想法,那么实现和{@link MergeSort#doNewMerge(int[], int[])}方法的思想,就简单了 * * 可以看到,大部分代码都是基本相同的 */ public void doMerge(int[] nums, int low, int mid, int high) { // 这里为什么要high-low,直接使用high不可以吗? // 不可以。因为这个方法是基于一个数组来的,根据MergeSort类的思想,要最终分成一个一个的元素, // 假设一开始第三个位置和第四个位置开始向上合并,那么此时的high是3,low是2,而这时新的数组其实只有两个元素, // 如果不把low前面的部分减掉的话,那就会多出来元素 int[] result = new int[high-low+1]; int resultStart = 0; // 相当于第一个数组的起始位 int lowStart = low; // 相当于第二个数组的起始位 int highStart = mid+1; while (lowStart <=mid && highStart<=high) { if (nums[lowStart] > nums[highStart]) { result[resultStart++] = nums[highStart++]; }else { result[resultStart++] = nums[lowStart++]; } } while (lowStart<=mid) { result[resultStart++] = nums[lowStart++]; } while (highStart<= high) { result[resultStart++] = nums[highStart++]; } // 因为始终要在原始数据上进行比较,所以在每次归并之后,要替换原始数组的内容 System.arraycopy(result, 0, nums, low, result.length); log.info("本次归并结果为{}", result); } public static void main(String[] args) { AdvancedMergeSort advancedMergeSort = new AdvancedMergeSort(); int[] nums = new int[]{9,1,5,8,3,7,4,6,2}; advancedMergeSort.mergeSort(nums, 0, nums.length-1); } }
33.857143
75
0.614411
30a97d4409c8c2c597e5a62170dee0e5200d6da9
1,425
package com.ivsom.ops.app.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import com.jess.arms.utils.LogUtils; /** * @author HanN on 2019/11/5 11:38 * @email: 1356548475@qq.com * @project mvparms * @description: bind服务学习使用 * @updateuser: * @updatedata: 2019/11/5 11:38 * @updateremark: * @version: 2.1.67 */ public class MyService extends Service { private static final String TAG = "MyService"; private MyLocalBinder myLocalBinder = new MyLocalBinder(); /** * bindservice 需要返回自定义的binder * 如果是启动服务可以为null * @param intent * @return */ @Nullable @Override public IBinder onBind(Intent intent) { return myLocalBinder; } public class MyLocalBinder extends Binder { /** * 方便客户端调用服务的公用方法 * @return */ public MyService getService() { return MyService.this; } /** * binder 里面的方法 */ public void start() { LogUtils.debugInfo(TAG,"LocalBinder_start"); } public void end() { LogUtils.debugInfo(TAG,"LocalBinder_end"); } } /** * 服务里面对外的方法 * @return */ public String myway(){ LogUtils.debugInfo(TAG, "myway:hello world"); return "hello world"; } }
21.590909
62
0.600702
f87c265303e67ca6e2ea6aa35730d40f39673751
501
/** * https://leetcode.com/problems/find-peak-element/ * https://leetcode.com/problems/find-peak-element/solution/ */ class Solution { public int findPeakElement(int[] nums) { return binarySearch(nums, 0, nums.length - 1); } private int binarySearch(int[] nums, int left, int right) { if (left == right) return left; int mid = left + (right - left) / 2; if (nums[mid] > nums[mid + 1]) return binarySearch(nums, left, mid); return binarySearch(nums, mid + 1, right); } }
31.3125
72
0.650699
0c1cc1598453670e5469012d6ad8a03815580dba
2,715
/* * This Java source file was generated by the Gradle 'init' task. */ package parameter.store.app; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import parameter.store.jpa.Parameter; import parameter.store.jpa.ParameterRepository; import javax.sql.DataSource; import java.util.List; @SpringBootApplication @EnableJpaRepositories(basePackageClasses = ParameterRepository.class) public class App { private static final Logger log = LoggerFactory.getLogger(App.class); @Bean public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.H2).build(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(true); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("parameter.store.jpa"); factory.setDataSource(dataSource()); return factory; } @Bean public CommandLineRunner demo(ParameterRepository repository) { return (args) -> { repository.save(new Parameter("test", "/app/parameter-1", "Hello")); repository.save(new Parameter("test", "/app/parameter-2", "World!")); log.info("Listing all params for /app"); List<Parameter> params = repository.findByEnvironmentAndNameStartingWith("test", "/app"); for (Parameter parameter : params) { log.info("{}", parameter); } log.info("Listing all params in environment: "); params = repository.findByEnvironment("test"); for (Parameter parameter : params) { log.info("{}", parameter); } }; } public static void main(String[] args) { SpringApplication.run(App.class); } }
36.2
102
0.724125
964c476e8e619029871acf21b656b92922ac452e
1,416
package org.echocat.kata.java.part1.service; import java.io.File; import java.io.IOException; import java.util.List; import org.echocat.kata.java.part1.pojo.Author; import org.echocat.kata.java.part1.pojo.Book; import org.echocat.kata.java.part1.pojo.Magazine; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import lombok.NonNull; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class CsvReaderService { private final CsvMapper csvMapper; public List<Author> readAuthorCsvFile( @NonNull final File authorCsvFile ) throws IOException { MappingIterator<Author> authorMappingIterator = csvMapper.readerWithTypedSchemaFor( Author.class ).readValues( authorCsvFile ); return authorMappingIterator.readAll(); } public List<Book> readBookCsvFile( @NonNull final File bookCsvFile ) throws IOException { MappingIterator<Book> bookMappingIterator = csvMapper.readerWithTypedSchemaFor( Book.class ).readValues( bookCsvFile ); return bookMappingIterator.readAll(); } public List<Magazine> readMagazineCsvFile( @NonNull final File magazineCsvFile ) throws IOException { MappingIterator<Magazine> magazineMappingIterator = csvMapper.readerWithTypedSchemaFor( Magazine.class ).readValues( magazineCsvFile ); return magazineMappingIterator.readAll(); } }
32.930233
143
0.781073
7e5db0cd7780a88cf6598287d883d37f672721b7
1,105
/* * 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 net.iatsoftware.iat.config; /** * * @author michael */ import org.springframework.core.annotation.Order; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.view.InternalResourceView; import org.springframework.web.servlet.view.UrlBasedViewResolver; @Configuration @Order(4) public class ResourceViewResolverConfigurer { @Bean public ViewResolver internalResourceViewResolver() { UrlBasedViewResolver resolver = new UrlBasedViewResolver(); resolver.setViewClass(InternalResourceView.class); resolver.setOrder(2); resolver.setViewNames(new String[]{ "*.html" }); resolver.setPrefix("/"); resolver.setCache(false); resolver.setContentType("text/html"); return resolver; } }
30.694444
79
0.743891
c533e0046e13beca36a231e90f795515becdb125
644
/* * jenkins-common * * Copyright (c) 2021 Synopsys, Inc. * * Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide. */ package com.synopsys.integration.stepworkflow; public abstract class AbstractSupplyingSubStep<R> implements SubStep<Object, R> { public abstract SubStepResponse<R> run(); @Override public SubStepResponse<R> run(final SubStepResponse previousResponse) { if (previousResponse.isSuccess()) { return run(); } else { return SubStepResponse.FAILURE(previousResponse); } } }
30.666667
142
0.698758
fc574b8dc78b46c512d80fca7ec47b10dc26f769
2,431
package ar.com.gorosite.tablas; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; public class Main { private static Random random = new Random(System.currentTimeMillis()); public static void main(String[] args) { int cuantas=0; long comienzo=0; int respuestasCorrectas=0; int respuestasIncorrectas=0; try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { cuantas = pideNumeroNatural("¿Cuantas cuentas?", br); int hastaQueNumero = pideNumeroNatural("¿Hasta qué número?", br); System.out.println("Ok... comenzamos...\n"); comienzo = System.currentTimeMillis(); for (int i=0; i<cuantas ; i++ ) { int x = numeroAleatorio(hastaQueNumero); int y = numeroAleatorio(10); int respuesta = pideNumeroNatural("¿Cuanto es ... "+x+" x "+y+" ?", br); if ( respuesta == x*y ) { respuestasCorrectas++; System.out.println("BIEN!"); } else { respuestasIncorrectas++; System.out.println("no :-("); } } long fin = System.currentTimeMillis(); long demoroSegundos = (fin-comienzo)/1000; System.out.println("Terminamos!!!\n"); System.out.println("Respuestas correctas:"+respuestasCorrectas); System.out.println("Respuestas incorrectas:"+respuestasIncorrectas); System.out.println("Tiempo total en segundos:"+demoroSegundos); System.out.println("Tiempo promedio por cuenta:"+demoroSegundos/cuantas); System.out.println("\n\n"); System.out.println("Presione ENTER para finalizar"); br.read(); } catch (IOException e) { e.printStackTrace(); } } private static int numeroAleatorio(int maximo) { if ( maximo < 2 ) { return 1; } return random.nextInt(maximo-1)+1; } private static int pideNumeroNatural(String pregunta, BufferedReader br) throws IOException { while ( true ) { System.out.println(pregunta); try { String linea = br.readLine(); Integer i = Integer.valueOf(linea); if ( i >= 1 ) { return i; } else { muestraMensajeError("Debe ingresar un número entero mayor o igual a uno."); } } catch (NumberFormatException e) { muestraMensajeError("Eso no es un número!"); } } } private static void muestraMensajeError(String s) { System.err.println(s); try { Thread.sleep(100); } catch (InterruptedException e1) { e1.printStackTrace(); } } }
23.375
94
0.672974
317d9fb36145fdfebdb08cd4d93d91a8c67982dc
375
package ca.blarg.tiles3.basicexample.entities.events; import com.badlogic.gdx.math.Vector3; import ca.blarg.gdx.entities.Entity; import ca.blarg.gdx.events.Event; public class MoveInDirectionEvent extends Event { public Entity entity; public final Vector3 direction = new Vector3(); @Override public void reset() { entity = null; direction.set(Vector3.Zero); } }
22.058824
53
0.768
3f49a724e2f3da16d60c04f548efa2d1659d61fd
227
package com.mi.http.resource; import java.io.Serializable; /** * Copyright (C) 2013, niuxiaowei Inc. All rights reserved. * * Created by niuxiaowei * on 18-1-27. */ public interface DataProtocol extends Serializable { }
17.461538
59
0.722467
c2044939d9e5a1088b145b6fc9fcf88594ac7a02
924
package org.walkframework.shiro.web.filter.authz; import java.io.IOException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter; /** * 拓展org.apache.shiro.web.filter.authz.RolesAuthorizationFilter * shiro默认只支持且,不支持或,现拓展以支持or * * @author shf675 */ public class WithORRolesAuthorizationFilter extends RolesAuthorizationFilter { public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException { Subject subject = getSubject(request, response); //查找存在或的配置,如有权限直接放行 boolean isAccessAllowed = OrAuthorizationHelper.orAccessAllowed(subject, (String[]) mappedValue); return isAccessAllowed ? isAccessAllowed : super.isAccessAllowed(request, response, mappedValue); } }
33
126
0.766234
62f3d4d48e2fe435999710291b8344038c0319d5
863
package mpinard.jbrains.tdd.poswo; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class DisplayTest { private static final Barcode BARCODE = new Barcode("12345"); @Test public void displayBeforeAnyBarcodeReceived() { final Display display = new Display(); assertThat(display.getText()).isEqualTo(""); } @Test public void productNotFound() { final Display display = new Display(); display.setProductNotFound(BARCODE); assertThat(display.getText()).isEqualTo(String.format("Product not found for barcode %s", BARCODE)); } @Test public void emptyBarcodeRead() { final Display display = new Display(); display.emptyBarcodeRead(); assertThat(display.getText()).isEqualTo("An empty barcode was read"); } }
25.382353
108
0.667439
29acc99e8b60af313f6a86a67624e29d12d7a710
3,066
package com.acod.play.app; import android.content.Context; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; /** * Created by andrew on 12/21/14. */ public class FileOperations { public static String getFileValue(String fileName, Context context) { try { StringBuffer outStringBuf = new StringBuffer(); String inputLine = ""; /* * We have to use the openFileInput()-method the ActivityContext * provides. Again for security reasons with openFileInput(...) */ FileInputStream fIn = context.openFileInput(fileName); InputStreamReader isr = new InputStreamReader(fIn); BufferedReader inBuff = new BufferedReader(isr); while ((inputLine = inBuff.readLine()) != null) { outStringBuf.append(inputLine); outStringBuf.append("\n"); } inBuff.close(); return outStringBuf.toString(); } catch (IOException e) { return null; } } public static boolean appendFileValue(String fileName, String value, Context context) { return writeToFile(fileName, value, context); } public static boolean setFileValue(String fileName, String value, Context context) { return writeToFile(fileName, value, context); } public static boolean writeToFile(String fileName, String value, Context context) { /* * We have to use the openFileOutput()-method the ActivityContext * provides, to protect your file from others and This is done for * security-reasons. We chose MODE_WORLD_READABLE, because we have * nothing to hide in our file */ File root = android.os.Environment.getExternalStorageDirectory(); // See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder File dir = new File(root.getAbsolutePath()); dir.mkdirs(); File file = new File(dir, fileName + ".xml"); try { FileOutputStream f = new FileOutputStream(file); PrintWriter pw = new PrintWriter(f); pw.println(value); pw.flush(); pw.close(); f.close(); } catch (FileNotFoundException e) { e.printStackTrace(); Log.i("Play", "******* File not found. Did you" + " add a WRITE_EXTERNAL_STORAGE permission to the manifest?"); } catch (IOException e) { e.printStackTrace(); } return true; } public static void deleteFile(String fileName, Context context) { context.deleteFile(fileName); } }
34.066667
89
0.589367
6683cd75c7bf34eb73a40232f5c0197e7aa92180
4,485
package javachr.rules; import javachr.constraints.Constraint; import javachr.exceptions.AlreadyDefinedException; import javachr.rules.body.Body; import javachr.rules.body.BodyStore; import javachr.rules.guard.Guard; import javachr.rules.head.Head; import java.util.List; /** * The type of rule that just adds new constraints and removes none. * Original syntax: * {@code Head => Guard | Body.} */ public class Propagation extends Rule { // Default definitions of body and guard private Guard guard = x -> true; // Guard that accepts evey constraints for the rule. private Body body = (x, y) -> { }; // Empty body for the rule. private boolean guardIsSet = false; private boolean bodyIsSet = false; public Propagation(int nrOfConstraints) { super(nrOfConstraints); } public Propagation(String name, int nrOfConstraints) { super(name, nrOfConstraints); } public Propagation(Class<?>... headTypes){super(headTypes);} public Propagation(String name, Class<?>... headTypes){super(name, headTypes);} public Propagation(Head... headDefinitions){ super(headDefinitions); } public Propagation(String name, Head... headDefinitions){ super(name, headDefinitions); } @Override public List<Constraint<?>> apply(Constraint<?>[] constraints) { if(constraints.length != headSize()) return null; BodyStore newConstraints = new BodyStore(); // All new constraints get added to this list by the body body.execute(constraints, newConstraints); // The old constraints are also added to the body store and the internal store of the body store is returned. newConstraints.addAll(constraints); return newConstraints.getAll(); } @Override public boolean accepts(Constraint<?>[] constraints) { if(constraints.length != headSize()) return false; // Assumes that the rule applicator checks if the constraints are valid. return guard.check(constraints); } /** * Used to define the guard of the rule by defining a lambda function. The lambda gets an array with constraints * (the head of the rule) and should return true if the constraints are accepted. * Example for the lambda: * {@code head -> head[0] > head[1]} * where head is an array with constraints. * @param guard lambda function defined according to {@link Guard}. * @return This object. (Used to chain function calls.) */ public Propagation guard(Guard guard){ if(guardIsSet) throw new AlreadyDefinedException("Guard is already defined for this rule!"); this.guard = guard; guardIsSet = true; return this; } /** * Used to define the body of the rule by defining a lambda function. The lambda gets an array with constraints * (the head of the rule) and an empty list were new arrays are added. The body uses the constraints to calculate * something and adds new constraints to the given list. * @param body lambda function defined according to {@link Body}. * @return This object. (Used to chain function calls.) */ public Propagation body(Body body){ if(bodyIsSet) throw new AlreadyDefinedException("Body is already defined for this rule!"); this.body = body; this.bodyIsSet = true; return this; } /** * The propagation history of a rule is saved if this method returns true. */ @Override public boolean saveHistory(){ return true; } /** * Used for negation-as-absence like in production rules. * * All the given constraint definitions are negated. That means the rule applicator makes sure that there are no * constraints like the defines ones in the constraint store. * * Attention: Negations ignore all variable bindings! Head of type ANY are ignored! * * @param negatedHead Negated constraints (Constraints that are not allowed to be in the constraint store) * @return This rule. Use this to chain method calls. */ public Propagation not(Head... negatedHead){ if (this.negatedHeadsDefined) throw new AlreadyDefinedException("Negated head constraints already defined!"); if (negatedHead.length > 0) { this.negatedHeadsDefined = true; this.negated = negatedHead; } return this; } }
33.721805
117
0.668004
ebad38b8a0368e93e337abf682507e6f8fc9dfdb
1,726
package wiki.tony.chat.logic.service; import com.google.protobuf.InvalidProtocolBufferException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import wiki.tony.chat.base.bean.Proto; import wiki.tony.chat.base.exception.ConnectionAuthException; import wiki.tony.chat.base.pb.Auth; import wiki.tony.chat.base.service.AuthService; import wiki.tony.chat.logic.config.CachingConfig; /** * 受权 * <p> * Created by Tony on 4/14/16. */ @Service("authService") public class AuthServiceImpl implements AuthService { private Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class); @Autowired private CacheManager cacheManager; @Override public String auth(int serverId, Proto proto) throws ConnectionAuthException { Auth.AuthReq req; try { req = Auth.AuthReq.parseFrom(proto.getBody()); } catch (InvalidProtocolBufferException e) { logger.error("invalid proto {} {}", proto, e.getMessage()); throw new ConnectionAuthException("invalid proto", e); } cacheManager.getCache(CachingConfig.ONLINE).put(req.getUid(), serverId); logger.debug("auth serverId={}, userId={}, token={}", serverId, req.getUid(), req.getToken()); return encodeKey(req.getUid()); } @Override public boolean quit(int serverId, String key) { logger.debug("client quit uid={}, key={}", serverId, key); return true; } private String encodeKey(int uid) { return uid + ""; } }
30.821429
102
0.70394
cc4be6221bc4d465e5738f8a21422f4f8f98fcd3
732
/* * @author Anna Balazinska (abalazinska@hotmail.com) */ package marek.client.table; import java.util.ArrayList; import java.util.List; import marek.client.model.LoginInfo; public class LoginDataSource { private final List<LoginInfo> loginL; private List<String> loginHeader; public LoginDataSource(List<LoginInfo> loginL) { loginHeader = new ArrayList<String>(); loginHeader.add("Nickname"); loginHeader.add("Email Address"); loginHeader.add("Password"); loginHeader.add("Code"); loginHeader.add("Remember me"); this.loginL = loginL; } public List<LoginInfo> getLoginInfo() { return loginL; } public List<String> getTableHeader() { return loginHeader; } }
20.914286
55
0.693989
0c6b759e2ccef963ae43a31376308ae0d9d7def0
2,091
package com.daya.logger.sample.fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TabHost; import com.daya.logger.sample.R; public class MainLoggerFragment extends Fragment { private static final String TAG = MainLoggerFragment.class.getSimpleName(); public MainLoggerFragment() { } public static MainLoggerFragment newInstance() { return new MainLoggerFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main_logger, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); TabHost loggerTab = view.findViewById(R.id.loggerTabHost); loggerTab.setup(); TabHost.TabSpec toastLoggerTabSpec = loggerTab.newTabSpec("toast_logger") .setContent(R.id.toast_logger_fragment) .setIndicator("TOAST"); loggerTab.addTab(toastLoggerTabSpec); TabHost.TabSpec instanceLoggerTabSpec = loggerTab.newTabSpec("instance_logger") .setContent(R.id.instance_logger_fragment) .setIndicator("Instance"); loggerTab.addTab(instanceLoggerTabSpec); TabHost.TabSpec crashLoggerTabSpec = loggerTab.newTabSpec("crash_logger") .setContent(R.id.crash_logger_fragment) .setIndicator("CRASH"); loggerTab.addTab(crashLoggerTabSpec); } @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onDetach() { super.onDetach(); } }
29.450704
87
0.692013
bd402420419b85f8dbff2f45e0f0e565888d96cc
17,883
/** * MIT License * * Copyright (c) 2018 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.buuz135.portality.tile; import com.buuz135.portality.block.ControllerBlock; import com.buuz135.portality.block.module.IPortalModule; import com.buuz135.portality.data.PortalDataManager; import com.buuz135.portality.data.PortalInformation; import com.buuz135.portality.data.PortalLinkData; import com.buuz135.portality.gui.ControllerScreen; import com.buuz135.portality.gui.PortalsScreen; import com.buuz135.portality.gui.RenameControllerScreen; import com.buuz135.portality.gui.button.PortalSettingButton; import com.buuz135.portality.gui.button.TextPortalButton; import com.buuz135.portality.handler.ChunkLoaderHandler; import com.buuz135.portality.handler.StructureHandler; import com.buuz135.portality.handler.TeleportHandler; import com.buuz135.portality.network.PortalNetworkMessage; import com.buuz135.portality.proxy.CommonProxy; import com.buuz135.portality.proxy.PortalityConfig; import com.buuz135.portality.proxy.PortalitySoundHandler; import com.buuz135.portality.proxy.client.TickeableSound; import com.buuz135.portality.util.BlockPosUtils; import com.hrznstudio.titanium.api.IFactory; import com.hrznstudio.titanium.block.tile.PoweredTile; import com.hrznstudio.titanium.client.screen.addon.StateButtonInfo; import com.hrznstudio.titanium.energy.NBTEnergyHandler; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ActionResultType; import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import net.minecraft.world.World; import net.minecraft.world.dimension.DimensionType; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import javax.annotation.Nonnull; import java.util.List; import java.util.UUID; public class ControllerTile extends PoweredTile<ControllerTile> { private static String NBT_FORMED = "Formed"; private static String NBT_LENGTH = "Length"; private static String NBT_WIDTH = "Width"; private static String NBT_HEIGHT = "Height"; private static String NBT_PORTAL = "Portal"; private static String NBT_LINK = "Link"; private static String NBT_DISPLAY = "Display"; private static String NBT_ONCE = "Once"; private boolean isFormed; private boolean onceCall; private boolean display; private PortalInformation information; private PortalLinkData linkData; @OnlyIn(Dist.CLIENT) private TickeableSound sound; private TeleportHandler teleportHandler; private StructureHandler structureHandler; public ControllerTile() { super(CommonProxy.BLOCK_CONTROLLER); this.isFormed = false; this.onceCall = false; this.display = true; this.teleportHandler = new TeleportHandler(this); this.structureHandler = new StructureHandler(this); this.addButton(new PortalSettingButton(-22, 12, () -> () -> { OpenGui.open(1, ControllerTile.this); }, new StateButtonInfo(0, PortalSettingButton.RENAME, "portality.display.change_name")) { @Override public int getState() { return 0; } }.setId(1)); this.addButton(new PortalSettingButton(-22, 12 + 22, () -> () -> { }, new StateButtonInfo(0, PortalSettingButton.PUBLIC, "portality.display.make_private"), new StateButtonInfo(1, PortalSettingButton.PRIVATE, "portality.display.make_public")) { @Override public int getState() { return information != null && information.isPrivate() ? 1 : 0; } }.setPredicate((playerEntity, compoundNBT) -> { if (information.getOwner().equals(playerEntity.getUniqueID())) togglePrivacy(); }).setId(2)); this.addButton(new PortalSettingButton(-22, 12 + 22 * 2, () -> () -> { }, new StateButtonInfo(0, PortalSettingButton.NAME_SHOWN, "portality.display.hide_name"), new StateButtonInfo(1, PortalSettingButton.NAME_HIDDEN, "portality.display.show_name")) { @Override public int getState() { return display ? 0 : 1; } }.setPredicate((playerEntity, compoundNBT) -> { if (information.getOwner().equals(playerEntity.getUniqueID())) setDisplayNameEnabled(!isDisplayNameEnabled()); }).setId(3)); this.addButton(new TextPortalButton(5, 90, 80, 16, "portality.display.call_portal") .setClientConsumer(() -> screen -> { OpenGui.open(2, ControllerTile.this); }) .setId(4) .setPredicate((playerEntity, compoundNBT) -> PortalNetworkMessage.sendInformationToPlayer((ServerPlayerEntity) playerEntity, isInterdimensional(), getPos(), BlockPosUtils.getMaxDistance(this.getLength()))) ); this.addButton(new TextPortalButton(90, 90, 80, 16, "portality.display.close_portal").setPredicate((playerEntity, compoundNBT) -> closeLink()).setId(5)); } @Override public void tick() { if (isActive()) { teleportHandler.tick(); if (linkData != null) { for (Entity entity : this.world.getEntitiesWithinAABB(Entity.class, getPortalArea())) { teleportHandler.addEntityToTeleport(entity, linkData); } } } if (!world.isRemote) { workModules(); } if (world.isRemote) { tickSound(); return; } if (isActive() && linkData != null) { this.getEnergyStorage().extractEnergy((linkData.isCaller() ? 2 : 1) * structureHandler.getLength() * PortalityConfig.POWER_PORTAL_TICK, false); if (this.getEnergyStorage().getEnergyStored() == 0 || !isFormed) { closeLink(); } } if (this.world.getGameTime() % 10 == 0) { if (structureHandler.shouldCheckForStructure()) { this.isFormed = structureHandler.checkArea(); if (this.isFormed) { structureHandler.setShouldCheckForStructure(false); } else { structureHandler.cancelFrameBlocks(); } } if (isFormed) { getPortalInfo(); if (linkData != null) { ChunkLoaderHandler.addPortalAsChunkloader(this); TileEntity tileEntity = this.world.getServer().getWorld(DimensionType.getById(linkData.getDimension())).getTileEntity(linkData.getPos()); if (!(tileEntity instanceof ControllerTile) || ((ControllerTile) tileEntity).getLinkData() == null || ((ControllerTile) tileEntity).getLinkData().getDimension() != this.world.getDimension().getType().getId() || !((ControllerTile) tileEntity).getLinkData().getPos().equals(this.pos)) { this.closeLink(); } } } markForUpdate(); } } @Nonnull @Override public ControllerTile getSelf() { return this; } @OnlyIn(Dist.CLIENT) private void tickSound() { if (isActive()) { if (sound == null) { Minecraft.getInstance().getSoundHandler().play(sound = new TickeableSound(this.world, this.pos, PortalitySoundHandler.PORTAL)); } else { sound.increase(); } } else if (sound != null) { if (sound.getPitch() > 0) { sound.decrease(); } else { sound.setDone(); sound = null; } } } @Override public CompoundNBT write(CompoundNBT compound) { compound = super.write(compound); compound.putBoolean(NBT_FORMED, isFormed); compound.putInt(NBT_LENGTH, structureHandler.getLength()); compound.putInt(NBT_WIDTH, structureHandler.getWidth()); compound.putInt(NBT_HEIGHT, structureHandler.getHeight()); compound.putBoolean(NBT_ONCE, onceCall); compound.putBoolean(NBT_DISPLAY, display); if (information != null) compound.put(NBT_PORTAL, information.writetoNBT()); if (linkData != null) compound.put(NBT_LINK, linkData.writeToNBT()); return compound; } @Override public void read(CompoundNBT compound) { isFormed = compound.getBoolean(NBT_FORMED); structureHandler.setLength(compound.getInt(NBT_LENGTH)); structureHandler.setWidth(compound.getInt(NBT_WIDTH)); structureHandler.setHeight(compound.getInt(NBT_HEIGHT)); if (compound.contains(NBT_PORTAL)) information = PortalInformation.readFromNBT(compound.getCompound(NBT_PORTAL)); if (compound.contains(NBT_LINK)) linkData = PortalLinkData.readFromNBT(compound.getCompound(NBT_LINK)); onceCall = compound.getBoolean(NBT_ONCE); display = compound.getBoolean(NBT_DISPLAY); super.read(compound); } public void breakController() { closeLink(); structureHandler.cancelFrameBlocks(); } private void workModules() { boolean interdimensional = false; for (BlockPos pos : structureHandler.getModules()) { Block block = this.world.getBlockState(pos).getBlock(); if (block instanceof IPortalModule) { if (((IPortalModule) block).allowsInterdimensionalTravel()) interdimensional = true; if (isActive()) ((IPortalModule) block).work(this, pos); } } PortalDataManager.setPortalInterdimensional(this.world, this.pos, interdimensional); } public AxisAlignedBB getPortalArea() { if (!(world.getBlockState(this.pos).getBlock() instanceof ControllerBlock)) return new AxisAlignedBB(0, 0, 0, 0, 0, 0); Direction facing = world.getBlockState(this.pos).get(ControllerBlock.FACING_HORIZONTAL); BlockPos corner1 = this.pos.offset(facing.rotateY(), structureHandler.getWidth()).offset(Direction.UP); BlockPos corner2 = this.pos.offset(facing.rotateYCCW(), structureHandler.getWidth()).offset(Direction.UP, structureHandler.getHeight() - 1).offset(facing.getOpposite(), structureHandler.getLength() - 1); return new AxisAlignedBB(corner1, corner2); } @Override public AxisAlignedBB getRenderBoundingBox() { return getPortalArea(); } private void getPortalInfo() { information = PortalDataManager.getInfoFromPos(this.world, this.pos); markForUpdate(); } public void togglePrivacy() { PortalDataManager.setPortalPrivacy(this.world, this.pos, !information.isPrivate()); getPortalInfo(); markForUpdate(); } public boolean isFormed() { return isFormed; } public boolean isPrivate() { return information != null && information.isPrivate(); } public UUID getOwner() { if (information != null) return information.getOwner(); return null; } public UUID getID() { if (information != null) return information.getId(); return null; } public String getPortalDisplayName() { if (information != null) return information.getName(); return ""; } public void setDisplayName(String name) { if (information != null) information.setName(name); } public boolean isInterdimensional() { return information != null && information.isInterdimensional(); } public ItemStack getDisplay() { if (information != null) return information.getDisplay(); return ItemStack.EMPTY; } public void linkTo(PortalLinkData data, PortalLinkData.PortalCallType type) { if (type == PortalLinkData.PortalCallType.FORCE) { closeLink(); } if (linkData != null) return; if (type == PortalLinkData.PortalCallType.SINGLE) onceCall = true; if (data.isCaller()) { World world = this.world.getServer().getWorld(DimensionType.getById(data.getDimension())); TileEntity entity = world.getTileEntity(data.getPos()); if (entity instanceof ControllerTile) { data.setName(((ControllerTile) entity).getPortalDisplayName()); ((ControllerTile) entity).linkTo(new PortalLinkData(this.world.getDimension().getType().getId(), this.pos, false, this.getPortalDisplayName()), type); int power = PortalityConfig.PORTAL_POWER_OPEN_INTERDIMENSIONAL; if (entity.getWorld().equals(this.world)) { power = (int) this.pos.distanceSq(new Vec3i(entity.getPos().getX(), entity.getPos().getZ(), entity.getPos().getY())) * structureHandler.getLength(); } this.getEnergyStorage().extractEnergy(power, false); } } PortalDataManager.setActiveStatus(this.world, this.pos, true); this.linkData = data; } public void closeLink() { if (linkData != null) { PortalDataManager.setActiveStatus(this.world, this.pos, false); World world = this.world.getServer().getWorld(DimensionType.getById(linkData.getDimension())); TileEntity entity = world.getTileEntity(linkData.getPos()); linkData = null; if (entity instanceof ControllerTile) { ((ControllerTile) entity).closeLink(); } } ChunkLoaderHandler.removePortalAsChunkloader(this); } public boolean isActive() { return information != null && information.isActive(); } public PortalLinkData getLinkData() { return linkData; } public boolean isDisplayNameEnabled() { return display; } public void setDisplayNameEnabled(ItemStack display) { PortalDataManager.setPortalDisplay(this.world, this.pos, display); getPortalInfo(); markForUpdate(); } public void setDisplayNameEnabled(boolean display) { this.display = display; markForUpdate(); } public List<BlockPos> getModules() { return structureHandler.getModules(); } public boolean teleportedEntity() { if (onceCall) { onceCall = false; closeLink(); return true; } return false; } public boolean isShouldCheckForStructure() { return structureHandler.shouldCheckForStructure(); } public void setShouldCheckForStructure(boolean shouldCheckForStructure) { structureHandler.setShouldCheckForStructure(shouldCheckForStructure); } public int getWidth() { return structureHandler.getWidth(); } public int getHeight() { return structureHandler.getHeight(); } public int getLength() { return structureHandler.getLength(); } public PortalInformation getInformation() { getPortalInfo(); return information; } @OnlyIn(Dist.CLIENT) @Override public ActionResultType onActivated(PlayerEntity playerIn, Hand hand, Direction facing, double hitX, double hitY, double hitZ) { if (super.onActivated(playerIn, hand, facing, hitX, hitY, hitZ) != ActionResultType.SUCCESS) { if (!world.isRemote()) { Minecraft.getInstance().deferTask(() -> { OpenGui.open(0, this); }); return ActionResultType.SUCCESS; } } return ActionResultType.PASS; } @Override protected IFactory<NBTEnergyHandler> getEnergyHandlerFactory() { return () -> new NBTEnergyHandler(this, PortalityConfig.MAX_PORTAL_POWER, PortalityConfig.MAX_PORTAL_POWER_IN, 0); } @OnlyIn(Dist.CLIENT) public static class OpenGui { public static void open(int id, ControllerTile controller) { switch (id) { case 0: Minecraft.getInstance().displayGuiScreen(new ControllerScreen(controller)); return; case 1: Minecraft.getInstance().displayGuiScreen(new RenameControllerScreen(controller)); return; case 2: Minecraft.getInstance().displayGuiScreen(new PortalsScreen(controller)); return; } } } }
39.476821
304
0.650394
d4380a9edded2dfde78fb8b8deb6b79f6710e2e3
980
package com.greenfield.SpEL.domain; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component @PropertySource({"classpath:domain.properties"}) public class Company { @Autowired Environment environment; @Value("#{environment['business.number']}") private long businessNumber; @Value("#{environment['business.name']}") private String name; public long getBusinessNumber() { return businessNumber; } public void setBusinessNumber(long businessNumber) { this.businessNumber = businessNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Company [businessNumber=" + businessNumber + ", name=" + name + "]"; } }
22.272727
78
0.757143
189cab11417f546d7597a899e043e0974e294e0c
64
package com.kaizenko.vendingmachine; public class Product { }
10.666667
36
0.78125
da18f62f10cd669f75c6e1c4ff36c62607119a08
659
package bernard.problem; public class NoOfBrief { static void minimumBribes(int[] q) { int count=0; for(int i=0; i< q.length-1 ;i++){ if(q[i+1]<q[i]){ int diff=q[i]-q[i+1]; if((q[i]- (i+1+2))>2){ System.out.println("Too chaotic"); return; } count = count +1; //swap both value int t= q[i+1]; q[i+1]=q[i]; q[i]=t; //initialize scanning to 1st position i=0; } } System.out.println(count); } }
23.535714
54
0.37481
ddb2ff07a63611772c56bfcf6284e175fd74a9eb
877
package com.kymjs.arty.module.base; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; /** * Created by ZhangTao on 12/26/16. */ public abstract class BaseFragment extends Fragment { protected View mRootView; @LayoutRes public abstract int inflateLayout(); @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mRootView = View.inflate(getActivity(), inflateLayout(), null); super.onCreateView(inflater, container, savedInstanceState); ButterKnife.bind(this, mRootView); return mRootView; } }
26.575758
123
0.751425
94099ebd866e2aba97dcc238245dbe053d251075
1,993
/* * Copyright (c) 2019. http://devonline.academy * * 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.revenat.javamm.interpreter.component.impl.calculator; import com.revenat.javamm.code.component.ExpressionContext; import com.revenat.javamm.code.fragment.Expression; import com.revenat.javamm.code.fragment.operator.UnaryOperator; import com.revenat.javamm.interpreter.component.UnaryExpressionCalculator; import com.revenat.javamm.interpreter.component.impl.error.JavammLineRuntimeError; import static com.revenat.javamm.code.util.TypeUtils.getType; /** * @author Vitaliy Dragun */ public abstract class AbstractUnaryExpressionCalculator implements UnaryExpressionCalculator { private final UnaryOperator operator; protected AbstractUnaryExpressionCalculator(final UnaryOperator operator) { this.operator = operator; } @Override public Object calculate(final ExpressionContext expressionContext, final Expression expression) { final Object value = expression.getValue(expressionContext); return calculate(value); } protected abstract Object calculate(Object value); @Override public UnaryOperator getOperator() { return operator; } protected final JavammLineRuntimeError createNotSupportedTypesError(final Object value) { return new JavammLineRuntimeError("Operator '%s' is not supported for type: %s", operator.getCode(), getType(value)); } }
34.964912
101
0.755143
202a0fe475dd063ad485a5486194cda8821b882a
1,182
package com.ezextended.registry; import net.minecraft.block.Block; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import com.ezextended.ref.RefStrings; /** Interface to help with block registration */ public interface IRegistryBlock extends IRegistryBase { /** Gets the block's item class to use when registering */ public default Class<? extends ItemBlock> getItemClass() { return ItemBlock.class; } /** Gets additional arguments to pass through to the ItemBlock constructor */ public default Object[] getItemClassArgs() { return new Object[0]; } @Override public default String getShorthandName() { return ((Block)this).getUnlocalizedName().substring(5); } @SideOnly(Side.CLIENT) @Override public default void registerRender(ItemModelMesher mesher) { mesher.register(Item.getItemFromBlock((Block)this), 0, new ModelResourceLocation(RefStrings.MODID + ":" + this.getShorthandName(), "inventory")); } }
31.105263
147
0.778342
0bdd253b4a6b25d756d8d4cb6551666d9a2938f7
346
package org.robolectric.shadows; public class ShadowAClassWithoutShadowOfAssert extends AbstractShadowAClassWithoutShadowOfAssert<ShadowAClassWithoutShadowOfAssert, ShadowAClassWithoutShadowOf> { public ShadowAClassWithoutShadowOfAssert(ShadowAClassWithoutShadowOf actual) { super(actual, ShadowAClassWithoutShadowOfAssert.class); } }
34.6
162
0.869942
de2ac1c47cabd31b314b15ecfb97748bb0858eb5
2,118
package com.ibm.webapi; import javax.enterprise.context.ApplicationScoped; // Tenant //import io.quarkus.oidc.TenantResolver; import io.quarkus.oidc.TenantConfigResolver; import io.quarkus.oidc.OidcTenantConfig; import io.vertx.ext.web.RoutingContext; // ConfigProperties import org.eclipse.microprofile.config.inject.ConfigProperty; @ApplicationScoped public class CustomTenantConfigResolver implements TenantConfigResolver { @ConfigProperty(name = "appid.auth-server-url_tenant_A") private String auth_server_url_tenant_A; @ConfigProperty(name = "appid.client_id_tenant_A") private String client_id_tenant_A; @Override public OidcTenantConfig resolve(RoutingContext context) { System.out.println("-->log: com.ibm.web-api.CustomTenantResolver.resolve : " + context.request().path()); String path = context.request().path(); String[] parts = path.split("/"); if (parts.length == 0) { // resolve to default tenant configuration return null; } if ("articlesA".equals(parts[1])) { OidcTenantConfig config = new OidcTenantConfig(); System.out.println("-->log: com.ibm.web-api.CustomTenantResolver.resolve A: Issuer = " + config.getToken().getIssuer().toString()); System.out.println("-->log: com.ibm.web-api.CustomTenantResolver.resolve A: auth_server_url = " + auth_server_url_tenant_A); System.out.println("-->log: com.ibm.web-api.CustomTenantResolver.resolve A: client_id = " + client_id_tenant_A); config.setTenantId("tenantA"); config.setAuthServerUrl(auth_server_url_tenant_A); config.setClientId(client_id_tenant_A); //OidcTenantConfig.Credentials credentials = new OidcTenantConfig.Credentials(); //credentials.setSecret(secret_tenant_A); //config.setCredentials(credentials); System.out.println("-->log: com.ibm.web-api.CustomTenantResolver.resolve A: " + config.toString()); return config; } else { return null; } } }
38.509091
143
0.680359
bc9df2564bfc34900f1785643d65209b7e4e1b15
3,758
/** * Copyright 2014-2015 Joshua Asbury (@theoriginalbit) * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.moarperipherals.tile; import com.moarperipherals.util.InventoryUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; /** * @author theoriginalbit * @since 13/10/2014 */ public abstract class TileInventory extends TileMoarP implements ISidedInventory { private final ItemStack[] inventory; public TileInventory(int size) { inventory = new ItemStack[size]; } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); InventoryUtil.readInventoryFromNBT(this, tag); } @Override public void writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); InventoryUtil.writeInventoryToNBT(this, tag); } @Override public int getSizeInventory() { return inventory.length; } @Override public ItemStack getStackInSlot(int slot) { return inventory[slot]; } @Override public ItemStack decrStackSize(int slot, int amount) { ItemStack stack = inventory[slot]; if (stack != null) { if (stack.stackSize <= amount) { inventory[slot] = null; } else { stack = stack.splitStack(amount); if (stack.stackSize == 0) { inventory[slot] = null; } } markDirty(); updateAnim(); } return stack; } @Override public ItemStack getStackInSlotOnClosing(int slot) { ItemStack stack = inventory[slot]; if (stack != null) { inventory[slot] = null; } updateAnim(); return stack; } @Override public void setInventorySlotContents(int slot, ItemStack stack) { inventory[slot] = stack; if (stack != null && stack.stackSize > getInventoryStackLimit()) { stack.stackSize = getInventoryStackLimit(); } markDirty(); updateAnim(); } @Override public abstract String getInventoryName(); @Override public boolean hasCustomInventoryName() { return false; } @Override public int getInventoryStackLimit() { return 64; } @Override public boolean isUseableByPlayer(EntityPlayer player) { return worldObj.getTileEntity(xCoord, yCoord, zCoord) == this && player.getDistanceSq(xCoord + 0.5d, yCoord + 0.5d, zCoord + 0.5d) <= 64d; } @Override public void openInventory() { } @Override public void closeInventory() { } @Override public boolean isItemValidForSlot(int slot, ItemStack stack) { return true; } @Override public int[] getAccessibleSlotsFromSide(int side) { return InventoryUtil.makeSlotArray(this); } @Override public boolean canInsertItem(int slot, ItemStack stack, int side) { return true; } @Override public boolean canExtractItem(int slot, ItemStack stack, int side) { return true; } }
26.27972
146
0.636243
ea278787dcf01d1a3cacd54ff2633f4b85e3c94b
1,872
package br.com.zupacademy.fabio.casadocodigo.controller; import br.com.zupacademy.fabio.casadocodigo.controller.dto.ClienteDto; import br.com.zupacademy.fabio.casadocodigo.controller.form.ClienteForm; import br.com.zupacademy.fabio.casadocodigo.entity.Cliente; import br.com.zupacademy.fabio.casadocodigo.repository.ClienteRepository; import br.com.zupacademy.fabio.casadocodigo.repository.EnderecoRepository; import br.com.zupacademy.fabio.casadocodigo.repository.EstadoRepository; import br.com.zupacademy.fabio.casadocodigo.validator.EstadosPorPaisValidator; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import javax.transaction.Transactional; import javax.validation.Valid; @RestController @RequestMapping("/clientes") public class ClienteController { private final EstadoRepository estadoRepository; private final ClienteRepository clienteRepository; private final EnderecoRepository enderecoRepository; public ClienteController(EstadoRepository estadoRepository, ClienteRepository clienteRepository, EnderecoRepository enderecoRepository) { this.estadoRepository = estadoRepository; this.clienteRepository = clienteRepository; this.enderecoRepository = enderecoRepository; } @InitBinder("clienteForm") public void init(WebDataBinder dataBinder) { dataBinder.addValidators(new EstadosPorPaisValidator(estadoRepository)); } @PostMapping @Transactional public ResponseEntity<ClienteDto> cadastrar(@RequestBody @Valid ClienteForm clienteForm) { Cliente cliente = clienteForm.converterToCliente(estadoRepository, enderecoRepository); this.clienteRepository.save(cliente); return ResponseEntity.ok(new ClienteDto(cliente)); } }
41.6
100
0.797543
10abecf8ace09c560e3534b598ef29aca09f6530
1,939
package paycalc; import java.nio.charset.StandardCharsets; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; public class Rest { // Makes REST requests using the HTTP GET method. public static String Get(String basic_auth, String url, String[] params) { // Create HTTP Client that processes cookies using standard specification. RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); HttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); // Format HTTP GET request. String request_string = url; String delimeter = "?"; for (String param : params) { request_string += delimeter + param; delimeter = "&"; } HttpGet req = new HttpGet(request_string); // Enable basic authentication, and set the authentication header. byte[] encodedAuth = Base64.encodeBase64(basic_auth.getBytes(StandardCharsets.ISO_8859_1)); String authHeader = "Basic " + new String(encodedAuth); req.setHeader(HttpHeaders.AUTHORIZATION, authHeader); String response_body = ""; // Execute the HTTP request and extract the response body. try { HttpResponse response = httpclient.execute(req); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { response_body = EntityUtils.toString(response.getEntity()); } else { System.err.println("API server returned non-ok response"); } } catch (Exception e) { System.err.println("Error encountered in HttpGet"); } req.releaseConnection(); return response_body; } }
35.907407
99
0.75606
5a4ca78fff858de29a9c14c93eced8d16fc960b8
1,648
package at.renehollander.advancedmanager.block.base; import at.renehollander.advancedmanager.Reference; import at.renehollander.advancedmanager.creative.AwesomeModCreativeTab; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraftforge.fml.common.registry.GameRegistry; import org.apache.commons.lang3.Validate; /** * Abstract Block class that takes common code and simplifies it, * * @author Rene Hollander * @version 1.0.0 * @since 1.0.0 */ public abstract class BlockAdvancedManager extends Block { private final String name; /** * Creates a new block with the given material and name and registeres everything. * * @param material Material of the new block * @param name Name of the new block */ public BlockAdvancedManager(Material material, String name) { super(material); Validate.notNull(name); this.name = name; setUnlocalizedName(Reference.MODID + "_" + this.getName()); setCreativeTab(AwesomeModCreativeTab.AWESOME_MOD_CREATIVE_TAB); GameRegistry.registerBlock(this, Reference.MODID + ":" + getName()); } /** * Creates a new block with the given name and a default material (rock) and registeres everything. * * @param name Name of the block * @see BlockAdvancedManager#BlockAdvancedManager(Material, String) */ public BlockAdvancedManager(String name) { this(Material.rock, name); } /** * Gets the name of the block * * @return Name of the block */ public String getName() { return this.name; } }
28.413793
103
0.688714
0480c9a46bddc69df077202cfa5e4a6b3404ef0f
4,023
package es.ucm.fdi.tp.view; import java.awt.Color; import es.ucm.fdi.tp.base.model.GameState; import es.ucm.fdi.tp.ttt.TttAction; import es.ucm.fdi.tp.ttt.TttState; public class TableTtt extends Table { int numOfRows = 3; int numOfCols = 3; private GameView grande; // Tablero private GameState tablero; private int jugador; GUIController controlador; /** * Constructora del tablero del juego Tres en raya * @param controlador * @param player jugador * @param tablero */ public TableTtt(GUIController controlador, int player, GameState tablero) { this.jugador = player; this.tablero = tablero; this.controlador = controlador; } @Override /** * Realiza una accion en la celda dada por fila y columna * @param row fila dada * @param col columna dada * @param clickCount numero de clicks hechos * @param mouseButton boton con el que se ha hecho el click */ protected void mouseClicked(int row, int col, int clickCount, int mouseButton) { if(!tablero.isFinished()){ controlador.makeMove(new TttAction(this.jugador, row, col)); } } @Override /** * Muestra la tecla pulsada * @param keyCode tecla pulsada */ protected void keyTyped(int keyCode) { //System.out.println("Key " + keyCode + " pressed .."); // Lo quitamos porque en la parte grafica no se mira la consola // Si se quiere usar descomentar y ya } @Override /** * Devuelve la forma correspondiente a ese jugador * @param player jugador * @return forma */ protected Shape getShape(int player) { return Shape.CIRCLE; } @Override /** * Devuelve lo que se encuentra en la posicion dada * @param row fila dada * @param col columna dada * @return valor */ protected Integer getPosition(int row, int col) { return this.getPositionAux(row, col); } @Override /** * Devuelve el numero de filas * @return numero de filas */ protected int getNumRows() { return numOfRows; } @Override /** * Devuelve el numero de columnas * @return numero de columnas */ protected int getNumCols() { return numOfCols; } @Override /** * Devuelve el color asociado a ese jugador * @return color */ protected Color getColor(int player) { return this.getColorAux(player); } @Override /** * Devuelve el color del fondo * @return color */ protected Color getBackground(int row, int col) { return Color.LIGHT_GRAY; // use this for 2 chess like board //return (row+col) % 2 == 0 ? Color.LIGHT_GRAY : Color.BLACK; } @Override protected int getSepPixels() { return 1; // put to 0 if you don't want a separator between // cells } /** * Devuelve lo que se encuentra en la posicion dada * @param row fila dada * @param col columna dada * @return valor o null */ protected Integer getPositionAux(int row, int col) { if(this.tablero.getBoard()[row][col] >= 0) return this.tablero.getBoard()[row][col]; else return null; } /** * Devuelve el color asociado al jugador * @param player * @return color */ protected Color getColorAux(int player) { //return player == 0 ? Color.BLUE : Color.RED; if(player == 0) return grande.getPanelDialogo().getInfo().colorFicha(player); else if (player == 1) return grande.getPanelDialogo().getInfo().colorFicha(player); else return null; } @Override /** * Actualiza el estado del juego * @param state estado nuevo */ public void update(GameState state) { this.tablero = state; repaint(); } /** * Da valor a la vista para poder usarla desde aqui * @param grande vista de la parte grafica */ public void setGrande(GameView grande){ this.grande = grande; } /** * Devuelve el estado actual * @return estado */ public GameState getState(){ return this.tablero; } }
21.745946
122
0.637832
84119a8f6cbf13b3e0d880f461cb07e85a2ebaa8
1,984
package codeforces.round_650_699.round_657; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public final class C { public static void main(String[] args) { final Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); final int t = Integer.parseInt(in.nextLine()); for (int x = 0; x < t; x++) { final int n = in.nextInt(); final int m = in.nextInt(); final int[] a = new int[m]; final int[] b = new int[m]; final List<Long> al = new ArrayList<>(); for (int i = 0; i < m; i++) { a[i] = in.nextInt(); b[i] = in.nextInt(); al.add(((long) a[i] << 30) + b[i]); } Collections.sort(al); Collections.reverse(al); int maxB = 0; long ans = 0; final long[] sum = new long[m]; final int[] AA = new int[m]; for (int i = 0; i < m; i++) { final int A = (int) (al.get(i) >>> 30); final int B = (int) (al.get(i) & ((1L << 30) - 1)); sum[i] = i == 0 ? A : A + sum[i - 1]; AA[i] = A; maxB = Math.max(maxB, B); if (i + 1 <= n) { ans = Math.max(ans, (long) maxB * (n - i - 1) + sum[i]); } int lo = -1, hi = Math.min(i - 1, n - 2); while (lo < hi) { final int mid = (lo + hi + 1) / 2; if (AA[mid] >= B) { lo = mid; } else { hi = mid - 1; } } ans = Math.max(ans, (long) B * (n - lo - 2) + A + (lo < 0 ? 0 : sum[lo])); } System.out.println(ans); } } }
34.807018
93
0.410282
82ef5725cb1e9b8b764e8ae5164d0e6fc3559d09
8,592
package com.paypal.integ.odak.stmts; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; import java.sql.Date; import java.sql.NClob; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; /** * * NOT IN USE currently * * Do we need Statement and CallableStatement (extends PreparedStatement). * * Why use Statement directly with OCC use cases? * * */ public class OdakPreparedStatement extends OdakStatement implements PreparedStatement { private PreparedStatement pStatement; private Connection conn; public OdakPreparedStatement(Connection conn, PreparedStatement preparedStatement) { super(conn, preparedStatement); this.conn = conn; this.pStatement = preparedStatement; } @Override public ResultSet executeQuery() throws SQLException { return pStatement.executeQuery(); } @Override public int executeUpdate() throws SQLException { return pStatement.executeUpdate(); } @Override public void setNull(int parameterIndex, int sqlType) throws SQLException { pStatement.setNull(parameterIndex, sqlType); } @Override public void setBoolean(int parameterIndex, boolean x) throws SQLException { pStatement.setBoolean(parameterIndex, x); } @Override public void setByte(int parameterIndex, byte x) throws SQLException { pStatement.setByte(parameterIndex, x); } @Override public void setShort(int parameterIndex, short x) throws SQLException { pStatement.setShort(parameterIndex, x); } @Override public void setInt(int parameterIndex, int x) throws SQLException { pStatement.setInt(parameterIndex, x); } @Override public void setLong(int parameterIndex, long x) throws SQLException { pStatement.setLong(parameterIndex, x); } @Override public void setFloat(int parameterIndex, float x) throws SQLException { pStatement.setFloat(parameterIndex, x); } @Override public void setDouble(int parameterIndex, double x) throws SQLException { pStatement.setDouble(parameterIndex, x); } @Override public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { pStatement.setBigDecimal(parameterIndex, x); } @Override public void setString(int parameterIndex, String x) throws SQLException { pStatement.setString(parameterIndex, x); } @Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { pStatement.setBytes(parameterIndex, x); } @Override public void setDate(int parameterIndex, Date x) throws SQLException { pStatement.setDate(parameterIndex, x); } @Override public void setTime(int parameterIndex, Time x) throws SQLException { pStatement.setTime(parameterIndex, x); } @Override public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { pStatement.setTimestamp(parameterIndex, x); } @Override public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { pStatement.setAsciiStream(parameterIndex, x, length); } @Override public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { pStatement.setUnicodeStream(parameterIndex, x, length); } @Override public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { pStatement.setBinaryStream(parameterIndex, x, length); } @Override public void clearParameters() throws SQLException { pStatement.clearParameters(); } @Override public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { pStatement.setObject(parameterIndex, x, targetSqlType); } @Override public void setObject(int parameterIndex, Object x) throws SQLException { pStatement.setObject(parameterIndex, x); } @Override public boolean execute() throws SQLException { return pStatement.execute(); } @Override public void addBatch() throws SQLException { pStatement.addBatch(); } @Override public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { // TODO Auto-generated method stub } @Override public void setRef(int parameterIndex, Ref x) throws SQLException { // TODO Auto-generated method stub } @Override public void setBlob(int parameterIndex, Blob x) throws SQLException { // TODO Auto-generated method stub } @Override public void setClob(int parameterIndex, Clob x) throws SQLException { // TODO Auto-generated method stub } @Override public void setArray(int parameterIndex, Array x) throws SQLException { // TODO Auto-generated method stub } @Override public ResultSetMetaData getMetaData() throws SQLException { return pStatement.getMetaData(); } @Override public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { pStatement.setDate(parameterIndex, x, cal); } @Override public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { pStatement.setTime(parameterIndex, x, cal); } @Override public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { // TODO Auto-generated method stub } @Override public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { // TODO Auto-generated method stub } @Override public void setURL(int parameterIndex, URL x) throws SQLException { // TODO Auto-generated method stub } @Override public ParameterMetaData getParameterMetaData() throws SQLException { // TODO Auto-generated method stub return null; } @Override public void setRowId(int parameterIndex, RowId x) throws SQLException { // TODO Auto-generated method stub } @Override public void setNString(int parameterIndex, String value) throws SQLException { // TODO Auto-generated method stub } @Override public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void setNClob(int parameterIndex, NClob value) throws SQLException { // TODO Auto-generated method stub } @Override public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { // TODO Auto-generated method stub } @Override public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { // TODO Auto-generated method stub } @Override public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { // TODO Auto-generated method stub } @Override public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { // TODO Auto-generated method stub } @Override public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { // TODO Auto-generated method stub } @Override public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { // TODO Auto-generated method stub } @Override public void setClob(int parameterIndex, Reader reader) throws SQLException { // TODO Auto-generated method stub } @Override public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { // TODO Auto-generated method stub } @Override public void setNClob(int parameterIndex, Reader reader) throws SQLException { // TODO Auto-generated method stub } }
23.096774
112
0.767225
261510acf3e735c92b410f552f23c06c5911055b
8,683
/* * 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.netbeans.modules.testng.ui.wizards; import java.awt.Component; import java.io.IOException; import java.util.*; import javax.swing.JComponent; import javax.swing.event.ChangeListener; import org.netbeans.api.java.project.JavaProjectConstants; import org.netbeans.api.project.*; import org.netbeans.api.templates.TemplateRegistration; import org.netbeans.modules.testng.api.TestNGSupport; import org.netbeans.spi.java.project.support.ui.templates.JavaTemplates; import org.netbeans.spi.project.ui.templates.support.Templates; import org.openide.WizardDescriptor; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataFolder; import org.openide.loaders.DataObject; import org.openide.util.NbBundle; @TemplateRegistration(folder = "UnitTests", position = 1200, content = "../resources/TestNGSuite.xml.template", scriptEngine = "freemarker", displayName = "#TestNGSuite_displayName", description = "/org/netbeans/modules/testng/ui/resources/newTestSuite.html", iconBase = "org/netbeans/modules/testng/ui/resources/testng.gif", category="junit") @NbBundle.Messages("TestNGSuite_displayName=TestNG Test Suite") public final class NewTestSuiteWizardIterator implements WizardDescriptor.InstantiatingIterator<WizardDescriptor> { private transient int index; private transient WizardDescriptor.Panel[] panels; private transient WizardDescriptor wiz; public NewTestSuiteWizardIterator() { } private WizardDescriptor.Panel[] createPanels(final WizardDescriptor wizardDescriptor) { // Ask for Java folders Project project = Templates.getProject(wizardDescriptor); Sources sources = ProjectUtils.getSources(project); SourceGroup[] groups = getTestRoots(sources); if (groups.length == 0) { if (SourceGroupModifier.createSourceGroup(project, JavaProjectConstants.SOURCES_TYPE_JAVA, JavaProjectConstants.SOURCES_HINT_TEST) != null) { groups = getTestRoots(sources); } } if (groups.length == 0) { groups = sources.getSourceGroups(Sources.TYPE_GENERIC); } return new WizardDescriptor.Panel[]{ JavaTemplates.createPackageChooser(project, groups) }; } private String[] createSteps(String[] before, WizardDescriptor.Panel[] panels) { assert panels != null; // hack to use the steps set before this panel processed int diff = 0; if (before == null) { before = new String[0]; } else if (before.length > 0) { diff = ("...".equals(before[before.length - 1])) ? 1 : 0; // NOI18N } String[] res = new String[(before.length - diff) + panels.length]; for (int i = 0; i < res.length; i++) { if (i < (before.length - diff)) { res[i] = before[i]; } else { res[i] = panels[i - before.length + diff].getComponent().getName(); } } return res; } public Set<DataObject> instantiate() throws IOException { FileObject targetFolder = Templates.getTargetFolder(wiz); TestNGSupport.findTestNGSupport(FileOwnerQuery.getOwner(targetFolder)).configureProject(targetFolder); String targetName = Templates.getTargetName(wiz); DataFolder df = DataFolder.findFolder(targetFolder); FileObject template = Templates.getTemplate(wiz); DataObject dTemplate = DataObject.find(template); String pkgName = getSelectedPackageName(targetFolder); String suiteName = pkgName + " suite"; String projectName = ProjectUtils.getInformation(FileOwnerQuery.getOwner(targetFolder)).getName(); if (pkgName == null || pkgName.trim().length() < 1) { pkgName = ".*"; //NOI18N suiteName = "All tests for " + projectName; } Map<String, String> props = new HashMap<String, String>(); props.put("suiteName", projectName); props.put("testName", suiteName); props.put("pkg", pkgName); DataObject dobj = dTemplate.createFromTemplate(df, targetName, props); return Collections.singleton(dobj); } public void initialize(WizardDescriptor wiz) { this.wiz = wiz; index = 0; panels = createPanels(wiz); // Make sure list of steps is accurate. String[] beforeSteps = null; Object prop = wiz.getProperty("WizardPanel_contentData"); // NOI18N if (prop != null && prop instanceof String[]) { beforeSteps = (String[]) prop; } String[] steps = createSteps(beforeSteps, panels); for (int i = 0; i < panels.length; i++) { Component c = panels[i].getComponent(); if (steps[i] == null) { // Default step name to component name of panel. // Mainly useful for getting the name of the target // chooser to appear in the list of steps. steps[i] = c.getName(); } if (c instanceof JComponent) { // assume Swing components JComponent jc = (JComponent) c; // Step #. jc.putClientProperty("WizardPanel_contentSelectedIndex", Integer.valueOf(i)); // NOI18N // Step name (actually the whole list for reference). jc.putClientProperty("WizardPanel_contentData", steps); // NOI18N } } } public void uninitialize(WizardDescriptor wiz) { this.wiz = null; panels = null; } public String name() { return ""; // NOI18N } public boolean hasNext() { return index < panels.length - 1; } public boolean hasPrevious() { return index > 0; } public void nextPanel() { if (!hasNext()) { throw new NoSuchElementException(); } index++; } public void previousPanel() { if (!hasPrevious()) { throw new NoSuchElementException(); } index--; } public WizardDescriptor.Panel current() { return panels[index]; } public final void addChangeListener(ChangeListener l) { } public final void removeChangeListener(ChangeListener l) { } private static String getSelectedPackageName(FileObject targetFolder) { Project project = FileOwnerQuery.getOwner(targetFolder); Sources sources = ProjectUtils.getSources(project); SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA); String packageName = null; for (int i = 0; i < groups.length && packageName == null; i++) { packageName = FileUtil.getRelativePath(groups[i].getRootFolder(), targetFolder); } if (packageName != null) { packageName = packageName.replaceAll("/", "."); // NOI18N } return packageName; } private SourceGroup[] getTestRoots(Sources srcs) { SourceGroup[] groups = srcs.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA); assert groups != null : "Cannot return null from Sources.getSourceGroups: " + srcs; //XXX - have to filter out regular source roots, there should //be better way to do this... (Hint: use UnitTestForSourceQuery) //${test - Ant based projects //2TestSourceRoot - Maven projects List<SourceGroup> result = new ArrayList<SourceGroup>(2); for (SourceGroup sg : groups) { if (sg.getName().startsWith("${test") || "2TestSourceRoot".equals(sg.getName())) { //NOI18N result.add(sg); } } return result.toArray(new SourceGroup[result.size()]); } }
38.93722
153
0.640908
3621f2ef72f414e3a1a872aed3e55276778bbb00
1,005
package com.ruoyi.system.service; import java.util.List; import com.ruoyi.system.domain.BasWord; /** * wordService接口 * * @author ruoyi * @date 2020-08-06 */ public interface IBasWordService { /** * 查询word * * @param id wordID * @return word */ public BasWord selectBasWordById(Long id); /** * 查询word列表 * * @param basWord word * @return word集合 */ public List<BasWord> selectBasWordList(BasWord basWord); /** * 新增word * * @param basWord word * @return 结果 */ public int insertBasWord(BasWord basWord); /** * 修改word * * @param basWord word * @return 结果 */ public int updateBasWord(BasWord basWord); /** * 批量删除word * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteBasWordByIds(String ids); /** * 删除word信息 * * @param id wordID * @return 结果 */ public int deleteBasWordById(Long id); }
16.209677
60
0.553234
6a166ba81ea7359aa4d31b0bad0379d6f2e514a0
4,736
package fitaview.automaton.transition; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import fitaview.Pair; import fitaview.Triple; import fitaview.automaton.Variable; public abstract class Transitions<K, V> { protected Map<Pair<Variable, K>, V> map = new HashMap<>(); private Function<K, String> keyConversion; private Function<V, String> valueConversion; public Transitions(Function<K, String> keyConversion, Function<V, String> valueConversion) { if(keyConversion == null || valueConversion == null) throw new IllegalArgumentException("Conversion function is null"); this.keyConversion = keyConversion; this.valueConversion = valueConversion; } /** * Testing if specified variable and arguments are present in transition relation. * @param var variable * @param key arguments of transition * @return {@code true} if there is transition entry with the exact arguments */ public boolean containsKey(Variable var, K key) { return map.containsKey(Pair.make(var, key)); } /** * Testing if specified variable and arguments fit for any entry in transition relation. * @param var variable * @param key arguments of transition * @return {@code true} if there is any transition entry fitting the arguments */ public abstract boolean containsEntry(Variable var, K key); /** * Adding new arguments-result entry to transition relation for specified variable. * @param var variable * @param key arguments of transition * @param value result of transition */ public void add(Variable var, K key, V value) throws DuplicatedTransitionException, IllegalTransitionException { if(containsKey(var, key)) throw new DuplicatedTransitionException( String.format("Duplicated transition entry for %s + %s", var.toString(), key.toString())); map.put(Pair.make(var, key), value); } /** * Getting all results of transition relation for specified arguments and variable. * @param var variable * @param key arguments of transition * @return list of possible results of transition for the arguments * @throws NoSuchTransitionException if there is no entry for specified arguments with variable. */ public abstract List<V> getAll(Variable var, K key) throws NoSuchTransitionException; /** * Getting first matched result of transition relation for specified arguments and variable. * @param var variable * @param key arguments of transition * @return matched results of transition for the arguments * @throws NoSuchTransitionException if there is no entry for specified arguments with variable. */ public abstract V getMatched(Variable var, K key) throws NoSuchTransitionException; /** * /** * Converting each key and value in transition relation to strings according to conversion functions. * @return transition relation with string representations */ public Map<Pair<Variable, String>, String> convertToStringMap() { Map<Pair<Variable, String>, String> stringMap = new HashMap<>(); map.forEach((key, value) -> stringMap.put( Pair.make(key.getFirst(), keyConversion.apply(key.getSecond())), valueConversion.apply(value))); return stringMap; } @Override public int hashCode() { return map.hashCode(); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(!(obj instanceof Transitions)) return false; Transitions<?, ?> other = (Transitions<?, ?>)obj; return Objects.equals(this.map, other.map); } @Override public String toString() { return String.format("Transitions::%s", map.toString()); } /** * Checking if arguments of transition contain null value. * @param key arguments of transition * @return {@code true} if arguments of transition have null, otherwise {@code false} */ protected abstract boolean hasNull(K key); /** * Sending transition entry. * @param var variable * @param key arguments of transition * @param value result of transition */ protected void sendEntry(Variable var, K key, V value) { TransitionsSender.getInstance() .send(Triple.make(var, keyConversion.apply(key), valueConversion.apply(value))); } }
32.438356
105
0.653927
33606a51adb2143b84ebff71055ccb459137127e
1,324
package legacyfeed; import java.util.HashMap; import java.util.Map; public class SimpleMessage { String name; Map<String,String> values = new HashMap<String, String>(); public SimpleMessage(String name) { this.name = name; } public void put(String attribute, String value) { values.put(attribute, value); } public String get(String attribute) { return values.get(attribute); } private static String dropWhiteSpace(String source) { return (source == null) ? null : source.replaceAll("\\s", ""); } public int getInt(String attribute) { return Integer.parseInt(dropWhiteSpace(get(attribute))); } public boolean getBool(String attribute) { return "True".equals(dropWhiteSpace(get(attribute))); } public double tryGetDouble(String attribute, double defaultValue) { String value = get(attribute); if (value != null) { return Double.parseDouble(dropWhiteSpace(value)); } return defaultValue; } public double getDouble(String attribute) { return Double.parseDouble(dropWhiteSpace(get(attribute))); } public int size() { return values.size(); } public String getName() { return name; } public Map<String, String> getValues() { return values; } @Override public String toString() { return String.format("%s, %d values", name, values.size()); } }
20.6875
68
0.701662
91cc2153ad80f58e7db2a6a4ec9b278799362c3f
1,580
package com.song.deviceinfo.ui.partitions; import com.song.deviceinfo.model.beans.PartitionsBean; import com.song.deviceinfo.ui.base.BaseAdapter; import com.song.deviceinfo.ui.base.BaseFragment; import com.song.deviceinfo.ui.base.BaseViewModel; import com.song.deviceinfo.utils.LogUtils; import com.song.deviceinfo.utils.ThreadPoolUtils; import org.json.JSONArray; import java.util.List; import androidx.lifecycle.ViewModelProviders; /** * Created by chensongsong on 2020/5/29. */ public class PartitionsFragment extends BaseFragment<PartitionsBean> { @Override protected BaseAdapter crateAdapter() { return new PartitionsAdapter(getContext()); } @Override protected BaseViewModel crateViewModel() { return ViewModelProviders.of(this).get(PartitionsViewModel.class); } @Override protected void refreshData() { ThreadPoolUtils.getInstance().execute(() -> { final List<PartitionsBean> list = getPartitionsInfo(); JSONArray jsonArray = new JSONArray(); for (PartitionsBean bean : list) { try { jsonArray.put(bean.toJSON()); } catch (Exception e) { e.printStackTrace(); } } LogUtils.printLongString(jsonArray.toString()); mainHandler.post(() -> { viewModel.setValue(list); }); }); } private List<PartitionsBean> getPartitionsInfo() { return ((PartitionsViewModel) viewModel).getPartitionsInfo(); } }
28.727273
74
0.648101
5e8277f859d6775e0ce547f10c5c4fa8a0d21589
1,498
package de.quinscape.exceed.runtime.template; import com.google.common.collect.ImmutableMap; import de.quinscape.exceed.runtime.util.RequestUtil; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; public class BaseTemplateTest { @Test public void testTemplate() throws Exception { assertThat(render("ABC", null), is("ABC")); assertThat(render("[$A]", ImmutableMap.of("A", "foo")), is("[foo]")); assertThat(render("[$a]", ImmutableMap.of("A", "foo")), is("[$a]")); assertThat(render("$A]", ImmutableMap.of("A", "foo")), is("foo]")); assertThat(render("[$A", ImmutableMap.of("A", "foo")), is("[foo")); assertThat(render("$A", ImmutableMap.of("A", "foo")), is("foo")); assertThat(render("1 $A 2 $B 3", ImmutableMap.of("A", "foo", "B", "bar")), is("1 foo 2 bar 3")); assertThat(render("$A$B", ImmutableMap.of("A", "foo", "B", "bar")), is("foobar")); assertThat(render("\\$A", ImmutableMap.of("A", "foo")), is("$A")); assertThat(render("\\\\$A", ImmutableMap.of("A", "foo")), is("\\$A")); } private String render(String s, Map<String, Object> map) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); new BaseTemplate(s).write(os, map); return new String(os.toByteArray(), RequestUtil.UTF_8); } }
37.45
104
0.622163
e4735a0934a7f7bf6fc9c0af89d619324628adac
923
package com.example.activitytest.view; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.example.activitytest.R; import com.example.activitytest.view.BaseActivity; import java.util.List; public class random1Activity extends BaseActivity { Button bt; TextView tv; int[] a={1,2,3,4,5,6}; List<String> list; int position; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_random); bt= (Button) findViewById(R.id.click); tv= (TextView) findViewById(R.id.tv); position=(int)(Math.random()*6); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tv.setText("你好" + a[position]); } }); } }
23.666667
58
0.655471
b97baf4627f58a3958ea39ef63e931ca8386a20a
1,918
/* * Copyright (c) 2020. Yuriy Stul */ package com.stulsoft.pjava.basics.optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * Playing with Optional * * @author Yuriy Stul. */ public class POptional2 { private final static Logger logger = LoggerFactory.getLogger(POptional2.class); private record DataObject(String name) { } public static void main(String[] args) { logger.info("==>main"); testF1(); test2(); test3(); logger.info("<==main"); } private static Optional<Integer> f1(boolean tofail) { return tofail ? Optional.empty() : Optional.of(123); } private static void testF1() { logger.info("==>testF1"); Optional<Integer> r = f1(false); r.ifPresent(i -> logger.info("(1) Result is {}", i)); boolean isPresent = r.isPresent(); logger.info("(1.1) isPresent is {}", isPresent); r = f1(true); r.ifPresent(i -> logger.info("(2) Result is {}", i)); isPresent = r.isPresent(); logger.info("(2.1) isPresent is {}", isPresent); logger.info("<==testF1"); } private static void test2() { logger.info("==>test2"); AtomicInteger i = new AtomicInteger(); Optional.of(123).ifPresent(i::set); logger.info("<==test2"); } private static void test3() { logger.info("==>test3"); AtomicReference<DataObject> dataObjectNull = new AtomicReference<>(); logger.info("{}", dataObjectNull.get()); AtomicReference<DataObject> dataObject = new AtomicReference<>(); Optional.of("some name").ifPresent(name -> dataObject.set(new DataObject(name))); logger.info("{}", dataObject); logger.info("<==test3"); } }
27.797101
89
0.605318
d1968928ea43bed2fcf39b2366cfe61613253763
968
package net.java.main.factories; import net.java.main.enums.UnitType; import net.java.main.interfaces.Position; import net.java.main.interfaces.Unit; import net.java.main.models.PositionImpl; import net.java.main.models.units.Carrier; import net.java.main.models.units.Marine; public final class UnitFactory { private UnitFactory(){ } public static Unit createUnit(UnitType unitType, String name, int xPosition, int yPosition) { Position position; switch(unitType){ case MARINE: position = new PositionImpl(xPosition, yPosition); return new Marine(name, position, CombatHandlerFactory.createMarineCombatHandler()); case CARRIER: position = new PositionImpl(xPosition, yPosition); return new Carrier(name, position, CombatHandlerFactory.createCarrierCombatHandler()); default: return null; } } }
28.470588
102
0.665289
20e089893218073e8172554652cd7a990a86810c
3,150
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. */ package com.hybris.ymkt.recommendationwebservices.validators; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.times; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.cms2.model.contents.components.AbstractCMSComponentModel; import de.hybris.platform.cmsfacades.common.validator.ValidationErrors; import de.hybris.platform.cmsfacades.common.validator.impl.DefaultValidationErrors; import de.hybris.platform.cmsfacades.common.validator.impl.DefaultValidationErrorsProvider; import java.io.IOException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import com.hybris.ymkt.recommendation.model.CMSSAPRecommendationComponentModel; @UnitTest public class RecommendationComponentValidatorTest { @Mock private AbstractCMSComponentModel model; @Spy private RecommendationComponentValidator validator; @Mock private DefaultValidationErrorsProvider validationErrorsProvider; @Before public void setup() throws IOException { MockitoAnnotations.initMocks(this); validator.setValidationErrorsProvider(validationErrorsProvider); Mockito.when(model.getProperty(CMSSAPRecommendationComponentModel.RECOTYPE)).thenReturn("1"); Mockito.when(model.getProperty(CMSSAPRecommendationComponentModel.LEADINGITEMTYPE)).thenReturn("1"); Mockito.when(model.getProperty(CMSSAPRecommendationComponentModel.LEADINGITEMDSTYPE)).thenReturn("1"); Mockito.when(model.getProperty(CMSSAPRecommendationComponentModel.CARTITEMDSTYPE)).thenReturn("1"); } @Test public void testAddValidatorRule() throws IOException { //Test that a new rule is added final ValidationErrors validationErrors = new DefaultValidationErrors(); Mockito.when(validationErrorsProvider.getCurrentValidationErrors()).thenReturn(validationErrors); validator.addValidatorRule("someField", "type.some.error.code"); Assert.assertEquals(1, validationErrors.getValidationErrors().size()); Assert.assertEquals("someField", validationErrors.getValidationErrors().get(0).getField()); } @Test public void testValidate() throws IOException { Mockito.doNothing().when(validator).addValidatorRule(anyString(), anyString()); //Test that validate() triggers 0 calls to addValidatorRule() validator.validate(model); Mockito.verify(validator, times(0)).addValidatorRule(anyString(), anyString()); Mockito.when(model.getProperty(CMSSAPRecommendationComponentModel.RECOTYPE)).thenReturn(""); Mockito.when(model.getProperty(CMSSAPRecommendationComponentModel.LEADINGITEMTYPE)).thenReturn(""); Mockito.when(model.getProperty(CMSSAPRecommendationComponentModel.LEADINGITEMDSTYPE)).thenReturn(""); Mockito.when(model.getProperty(CMSSAPRecommendationComponentModel.CARTITEMDSTYPE)).thenReturn(""); //Test that validate() triggers 4 calls to addValidatorRule() validator.validate(model); Mockito.verify(validator, times(4)).addValidatorRule(anyString(), anyString()); } }
36.627907
104
0.815873
bed5aaffd0f93c65054825dc000241f8852de014
537
package com.duff.animation; /** * Created by dingfeng on 2017/6/15. */ public class WipeDirection { public final static int LEFT_TO_RIGHT = 0; // 从左向右 public final static int RIGHT_TO_LEFT = 1; // 从右向左 public final static int TOP_TO_BOTTOM = 2; // 从上到下 public final static int BOTTOM_TO_TOP = 3; // 从下到上 public final static int CLOCKWISE = 4; // 顺时针 public final static int ANTI_CLOCKWISE = 5; // 逆时针 public final static int UNKNOWN = -1; public final static int DEFAULT_DIRECTION = RIGHT_TO_LEFT; }
29.833333
62
0.696462
fe8ba4c32ef6f5a8ae94123e776d111c93c96dcf
12,949
/* * This file is part of Baritone. * * Baritone is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Baritone is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Baritone. If not, see <https://www.gnu.org/licenses/>. */ package baritone.command.defaults; import baritone.Baritone; import baritone.api.IBaritone; import baritone.api.Settings; import baritone.api.command.Command; import baritone.api.command.argument.IArgConsumer; import baritone.api.command.exception.CommandException; import baritone.api.command.exception.CommandInvalidTypeException; import baritone.api.command.helpers.Paginator; import baritone.api.command.helpers.TabCompleteHelper; import baritone.api.utils.SettingsUtil; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.HoverEvent; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; import java.util.stream.Stream; import static baritone.api.command.IBaritoneChatControl.FORCE_COMMAND_PREFIX; import static baritone.api.utils.SettingsUtil.*; public class SetCommand extends Command { public SetCommand(IBaritone baritone) { super(baritone, "set", "setting", "settings"); } @Override public void execute(String label, IArgConsumer args) throws CommandException { String arg = args.hasAny() ? args.getString().toLowerCase(Locale.US) : "list"; if (Arrays.asList("s", "save").contains(arg)) { SettingsUtil.save(Baritone.settings()); logDirect("Settings saved"); return; } boolean viewModified = Arrays.asList("m", "mod", "modified").contains(arg); boolean viewAll = Arrays.asList("all", "l", "list").contains(arg); boolean paginate = viewModified || viewAll; if (paginate) { String search = args.hasAny() && args.peekAsOrNull(Integer.class) == null ? args.getString() : ""; args.requireMax(1); List<? extends Settings.Setting> toPaginate = (viewModified ? SettingsUtil.modifiedSettings(Baritone.settings()) : Baritone.settings().allSettings).stream() .filter(s -> !s.getName().equals("logger")) .filter(s -> s.getName().toLowerCase(Locale.US).contains(search.toLowerCase(Locale.US))) .sorted((s1, s2) -> String.CASE_INSENSITIVE_ORDER.compare(s1.getName(), s2.getName())) .collect(Collectors.toList()); Paginator.paginate( args, new Paginator<>(toPaginate), () -> logDirect( !search.isEmpty() ? String.format("All %ssettings containing the string '%s':", viewModified ? "modified " : "", search) : String.format("All %ssettings:", viewModified ? "modified " : "") ), setting -> { ITextComponent typeComponent = new TextComponentString(String.format( " (%s)", settingTypeToString(setting) )); typeComponent.getStyle().setColor(TextFormatting.DARK_GRAY); ITextComponent hoverComponent = new TextComponentString(""); hoverComponent.getStyle().setColor(TextFormatting.GRAY); hoverComponent.appendText(setting.getName()); hoverComponent.appendText(String.format("\nType: %s", settingTypeToString(setting))); hoverComponent.appendText(String.format("\n\nValue:\n%s", settingValueToString(setting))); hoverComponent.appendText(String.format("\n\nDefault Value:\n%s", settingDefaultToString(setting))); String commandSuggestion = Baritone.settings().prefix.getValue() + String.format("set %s ", setting.getName()); ITextComponent component = new TextComponentString(setting.getName()); component.getStyle().setColor(TextFormatting.GRAY); component.appendSibling(typeComponent); component.getStyle() .setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverComponent)) .setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, commandSuggestion)); return component; }, FORCE_COMMAND_PREFIX + "set " + arg + " " + search ); return; } args.requireMax(1); boolean resetting = arg.equalsIgnoreCase("reset"); boolean toggling = arg.equalsIgnoreCase("toggle"); boolean doingSomething = resetting || toggling; if (resetting) { if (!args.hasAny()) { logDirect("Please specify 'all' as an argument to reset to confirm you'd really like to do this"); logDirect("ALL settings will be reset. Use the 'set modified' or 'modified' commands to see what will be reset."); logDirect("Specify a setting name instead of 'all' to only reset one setting"); } else if (args.peekString().equalsIgnoreCase("all")) { SettingsUtil.modifiedSettings(Baritone.settings()).forEach(Settings.Setting::reset); logDirect("All settings have been reset to their default values"); SettingsUtil.save(Baritone.settings()); return; } } if (toggling) { args.requireMin(1); } String settingName = doingSomething ? args.getString() : arg; Settings.Setting<?> setting = Baritone.settings().allSettings.stream() .filter(s -> s.getName().equalsIgnoreCase(settingName)) .findFirst() .orElse(null); if (setting == null) { throw new CommandInvalidTypeException(args.consumed(), "a valid setting"); } if (!doingSomething && !args.hasAny()) { logDirect(String.format("Value of setting %s:", setting.getName())); logDirect(settingValueToString(setting)); } else { String oldValue = settingValueToString(setting); if (resetting) { setting.reset(); } else if (toggling) { if (setting.getValueClass() != Boolean.class) { throw new CommandInvalidTypeException(args.consumed(), "a toggleable setting", "some other setting"); } //noinspection unchecked setting.toggle(); logDirect(String.format( "Toggled setting %s to %s", setting.getName(), Boolean.toString((Boolean) setting.getValue()) )); } else { String newValue = args.getString(); try { SettingsUtil.parseAndApply(Baritone.settings(), arg, newValue); } catch (Throwable t) { t.printStackTrace(); throw new CommandInvalidTypeException(args.consumed(), "a valid value", t); } } if (!toggling) { logDirect(String.format( "Successfully %s %s to %s", resetting ? "reset" : "set", setting.getName(), settingValueToString(setting) )); } ITextComponent oldValueComponent = new TextComponentString(String.format("Old value: %s", oldValue)); oldValueComponent.getStyle() .setColor(TextFormatting.GRAY) .setHoverEvent(new HoverEvent( HoverEvent.Action.SHOW_TEXT, new TextComponentString("Click to set the setting back to this value") )) .setClickEvent(new ClickEvent( ClickEvent.Action.RUN_COMMAND, FORCE_COMMAND_PREFIX + String.format("set %s %s", setting.getName(), oldValue) )); logDirect(oldValueComponent); if ((setting.getName().equals("chatControl") && !(Boolean) setting.getValue() && !Baritone.settings().chatControlAnyway.getValue()) || setting.getName().equals("chatControlAnyway") && !(Boolean) setting.getValue() && !Baritone.settings().chatControl.getValue()) { logDirect("Warning: Chat commands will no longer work. If you want to revert this change, use prefix control (if enabled) or click the old value listed above.", TextFormatting.RED); } else if (setting.getName().equals("prefixControl") && !(Boolean) setting.getValue()) { logDirect("Warning: Prefixed commands will no longer work. If you want to revert this change, use chat control (if enabled) or click the old value listed above.", TextFormatting.RED); } } SettingsUtil.save(Baritone.settings()); } @Override public Stream<String> tabComplete(String label, IArgConsumer args) throws CommandException { if (args.hasAny()) { String arg = args.getString(); if (args.hasExactlyOne() && !Arrays.asList("s", "save").contains(args.peekString().toLowerCase(Locale.US))) { if (arg.equalsIgnoreCase("reset")) { return new TabCompleteHelper() .addModifiedSettings() .prepend("all") .filterPrefix(args.getString()) .stream(); } else if (arg.equalsIgnoreCase("toggle")) { return new TabCompleteHelper() .addToggleableSettings() .filterPrefix(args.getString()) .stream(); } Settings.Setting setting = Baritone.settings().byLowerName.get(arg.toLowerCase(Locale.US)); if (setting != null) { if (setting.getType() == Boolean.class) { TabCompleteHelper helper = new TabCompleteHelper(); if ((Boolean) setting.getValue()) { helper.append("true", "false"); } else { helper.append("false", "true"); } return helper.filterPrefix(args.getString()).stream(); } else { return Stream.of(settingValueToString(setting)); } } } else if (!args.hasAny()) { return new TabCompleteHelper() .addSettings() .sortAlphabetically() .prepend("list", "modified", "reset", "toggle", "save") .filterPrefix(arg) .stream(); } } return Stream.empty(); } @Override public String getShortDesc() { return "View or change settings"; } @Override public List<String> getLongDesc() { return Arrays.asList( "Using the set command, you can manage all of Baritone's settings. Almost every aspect is controlled by these settings - go wild!", "", "Usage:", "> set - Same as `set list`", "> set list [page] - View all settings", "> set modified [page] - View modified settings", "> set <setting> - View the current value of a setting", "> set <setting> <value> - Set the value of a setting", "> set reset all - Reset ALL SETTINGS to their defaults", "> set reset <setting> - Reset a setting to its default", "> set toggle <setting> - Toggle a boolean setting", "> set save - Save all settings (this is automatic tho)" ); } }
50.980315
199
0.558267
2c1524dd54c3ac7e5f18191622632c04005b6cb0
753
package ss.parser.mail; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.mail.internet.InternetAddress; import java.time.Duration; @Getter @Setter @Component @ConfigurationProperties("ss-parser.mail") class MailConfigImpl implements MailConfig { private boolean enabled; private Duration rate; private InternetAddress from; private InternetAddress[] to; private InternetAddress[] admin; private String subject; @PostConstruct private void init() { if (admin == null) { admin = new InternetAddress[]{to[0]}; } } }
24.290323
75
0.739708
931a97adfe28652a78cff17a79850c1ed96c9d3f
1,098
package ramdan.file.line.token.listener; import ramdan.file.line.token.Line; import ramdan.file.line.token.Tokens; import ramdan.file.line.token.callback.Callback; import ramdan.file.line.token.handler.DefaultLineTokenConverter; import ramdan.file.line.token.handler.LineTokenConverter; public class TokensCallbackLineListener implements LineListener { private Callback<Tokens> handler; private LineTokenConverter converter; public TokensCallbackLineListener(Callback<Tokens> handler) { this(handler,null); } public TokensCallbackLineListener(Callback<Tokens> handler, LineTokenConverter converter) { this.handler = handler; if(converter==null) { this.converter = DefaultLineTokenConverter.DEFAULT; }else { this.converter= converter; } } public void setConverter(LineTokenConverter converter) { if(converter==null) { return; } this.converter = converter; } @Override public void event(Line line) { handler.call(converter.convert(line)); } }
29.675676
95
0.700364
afa1cc84b738e4ce9771ca7ea257a5c9dd3dd510
1,382
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.contracts.reference; import java.util.List; import org.joda.time.DateTime; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.joda.time.DateTime; /** * The paged collection of all top level internet domains that the system supports including general, USA-specific, infrastructure, and country codes. The Internet Assigned Numbers Authority (IANA) maintains this list. */ @JsonIgnoreProperties(ignoreUnknown = true) public class TopLevelDomainCollection implements Serializable { // Default Serial Version UID private static final long serialVersionUID = 1L; /** * An array list of objects in the returned collection. */ protected List<String> items; public List<String> getItems() { return this.items; } public void setItems(List<String> items) { this.items = items; } /** * The number of results listed in the query collection, represented by a signed 64-bit (8-byte) integer. This value is system-supplied and read-only. */ protected Integer totalCount; public Integer getTotalCount() { return this.totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } }
28.204082
218
0.748191
d69808989e33c85d8143ae227d882ca6a53c9fa2
6,715
/* * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package stream.EventsTest; import java.io.StringReader; import java.io.StringWriter; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.Comment; import javax.xml.stream.events.DTD; import javax.xml.stream.events.EndDocument; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.ProcessingInstruction; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /* * @test * @bug 6631268 * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest * @run testng/othervm -DrunSecMngr=true -Djava.security.manager=allow stream.EventsTest.Issue41Test * @run testng/othervm stream.EventsTest.Issue41Test * @summary Test XMLEvent.writeAsEncodedUnicode can output the event content. */ @Listeners({jaxp.library.BasePolicy.class}) public class Issue41Test { public java.io.File input; public final String filesDir = "./"; protected XMLInputFactory inputFactory; protected XMLOutputFactory outputFactory; @Test public void testEvents() { XMLEventFactory f = XMLEventFactory.newInstance(); final String contents = "test <some> text & more! [[]] --"; final String prefix = "prefix"; final String uri = "http://foo"; final String localName = "elem"; try { StartDocument sd = f.createStartDocument(); writeAsEncodedUnicode(sd); Comment c = f.createComment("some comments"); writeAsEncodedUnicode(c); StartElement se = f.createStartElement(prefix, uri, localName); ProcessingInstruction pi = f.createProcessingInstruction("target", "data"); writeAsEncodedUnicode(pi); Namespace ns = f.createNamespace(prefix, uri); writeAsEncodedUnicode(ns); Characters characters = f.createCharacters(contents); writeAsEncodedUnicode(characters); // CData Characters cdata = f.createCData(contents); writeAsEncodedUnicode(cdata); // Attribute QName attrName = new QName("http://test.com", "attr", "ns"); Attribute attr = f.createAttribute(attrName, "value"); writeAsEncodedUnicode(attr); // prefix, uri, localName EndElement ee = f.createEndElement(prefix, uri, localName); writeAsEncodedUnicode(ee); EndDocument ed = f.createEndDocument(); writeAsEncodedUnicode(ed); } catch (Exception e) { Assert.fail(e.getMessage()); } } /** * DTDEvent instances constructed via event reader are missing the notation * and entity declaration information */ @Test public void testDTDEvent() { String XML = "<?xml version='1.0' ?>" + "<!DOCTYPE root [\n" + "<!ENTITY intEnt 'internal'>\n" + "<!ENTITY extParsedEnt SYSTEM 'url:dummy'>\n" + "<!NOTATION notation PUBLIC 'notation-public-id'>\n" + "<!NOTATION notation2 SYSTEM 'url:dummy'>\n" + "<!ENTITY extUnparsedEnt SYSTEM 'url:dummy2' NDATA notation>\n" + "]>" + "<root />"; try { XMLEventReader er = getReader(XML); XMLEvent evt = er.nextEvent(); // StartDocument evt = er.nextEvent(); // DTD if (evt.getEventType() != XMLStreamConstants.DTD) { Assert.fail("Expected DTD event"); } DTD dtd = (DTD) evt; writeAsEncodedUnicode(dtd); List entities = dtd.getEntities(); if (entities == null) { Assert.fail("No entity found. Expected 3."); } else { writeAsEncodedUnicode((XMLEvent) entities.get(0)); writeAsEncodedUnicode((XMLEvent) entities.get(1)); writeAsEncodedUnicode((XMLEvent) entities.get(2)); } List notations = dtd.getNotations(); if (notations == null) { Assert.fail("No notation found. Expected 2."); } else { writeAsEncodedUnicode((XMLEvent) notations.get(0)); writeAsEncodedUnicode((XMLEvent) notations.get(1)); } } catch (Exception e) { Assert.fail(e.getMessage()); } } private XMLEventReader getReader(String XML) throws Exception { inputFactory = XMLInputFactory.newInstance(); // Check if event reader returns the correct event XMLEventReader er = inputFactory.createXMLEventReader(new StringReader(XML)); return er; } /** * The return of XMLEvent writeAsEncodedUnicode method is not defined This * method merely tests that the output exists */ public void writeAsEncodedUnicode(XMLEvent evt) throws XMLStreamException { if (evt.getEventType() == XMLStreamConstants.END_DOCUMENT) { return; } StringWriter sw = new StringWriter(); evt.writeAsEncodedUnicode(sw); Assert.assertTrue(sw.toString().length() > 0); System.out.println(sw.toString()); } }
37.099448
150
0.658228
3132eb877c13e0568b2de77455417711c5fec456
4,897
package io.choerodon.iam.infra.annotation; import io.choerodon.core.exception.CommonException; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Field; import java.util.Map; /** * @author dengyouquan * 根据指定的命名规则解析请求参数,只能用在get方法自定义类上,不能使用在json数据转换中 **/ public class NamingRuleTransHandler implements HandlerMethodArgumentResolver { private static MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(NamingRuleTrans.class); } @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory binderFactory) { HttpServletRequest servletRequest = nativeWebRequest.getNativeRequest(HttpServletRequest.class); String contentType = servletRequest.getContentType(); if (!"GET".equals(servletRequest.getMethod()) || MediaType.APPLICATION_JSON_VALUE.equals(contentType)) { throw new CommonException("error.parse.json.methodArgumentResolver.notSupportJson"); } if (methodParameter.getParameterType().getDeclaredFields().length == 0) { throw new CommonException("error.parse.json.methodArgumentResolver.notEntity"); } Object result = null; try { NamingRuleTrans namingRuleTrans = methodParameter.getParameterAnnotation(NamingRuleTrans.class); NamingRuleTransStrategy strategy = namingRuleTrans.value(); Object obj = BeanUtils.instantiate(methodParameter.getParameterType()); BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(obj); Map<String, String[]> parameterMap = nativeWebRequest.getParameterMap(); for (Map.Entry<String, String[]> map : parameterMap.entrySet()) { String paramName = map.getKey(); String[] paramValue = map.getValue(); Field[] declaredFields = obj.getClass().getDeclaredFields(); for (Field declaredField : declaredFields) { String transParamName = null; switch (strategy) { case UNDER_LINE: transParamName = camelToUnderLine(paramName); break; case CAMEL: transParamName = underLineToCamel(paramName); break; default: transParamName = underLineToCamel(paramName); break; } if (declaredField.getName().equals(transParamName)) { wrapper.setPropertyValue(transParamName, paramValue); } } } result = obj; } catch (Exception e) { throw new CommonException("error.parse.json.methodArgumentResolver"); } return result; } private String underLineToCamel(String name) { StringBuilder result = new StringBuilder(); if (name == null || name.isEmpty()) { return ""; } else if (!name.contains("_")) { // 不含下划线,仅将首字母小写 return name.substring(0, 1).toLowerCase() + name.substring(1); } String[] camels = name.split("_"); for (String camel : camels) { if (camel.isEmpty()) { continue; } if (result.length() == 0) { result.append(camel.toLowerCase()); } else { result.append(camel.substring(0, 1).toUpperCase()); result.append(camel.substring(1).toLowerCase()); } } return result.toString(); } private String camelToUnderLine(String name) { StringBuilder sb = new StringBuilder(name); int temp = 0; for (int i = 0; i < name.length(); i++) { if (Character.isUpperCase(name.charAt(i))) { sb.insert(i + temp, "_"); temp += 1; } } return sb.toString().toLowerCase(); } }
43.336283
175
0.630182
0f2b907108cac50328bc295b8b441e7301d2dc12
2,340
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * BQOutboundInitiateOutputModelOutboundInstanceRecord */ public class BQOutboundInitiateOutputModelOutboundInstanceRecord { private Object customerContactDialogueRecord = null; private String eBranchOutboundConnectionStartTime = null; private String eBranchOutboundConnectionDuration = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: This is the payload of the exchange - it is the specific session within the contact that handles the customer interaction. Content passes through the E-Branch facility transparently * @return customerContactDialogueRecord **/ public Object getCustomerContactDialogueRecord() { return customerContactDialogueRecord; } public void setCustomerContactDialogueRecord(Object customerContactDialogueRecord) { this.customerContactDialogueRecord = customerContactDialogueRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::DateTime general-info: Log of the initial connection * @return eBranchOutboundConnectionStartTime **/ public String getEBranchOutboundConnectionStartTime() { return eBranchOutboundConnectionStartTime; } @JsonProperty("eBranchOutboundConnectionStartTime") public void setEBranchOutboundConnectionStartTime(String eBranchOutboundConnectionStartTime) { this.eBranchOutboundConnectionStartTime = eBranchOutboundConnectionStartTime; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Connection duration for capacity planning purposes * @return eBranchOutboundConnectionDuration **/ public String getEBranchOutboundConnectionDuration() { return eBranchOutboundConnectionDuration; } @JsonProperty("eBranchOutboundConnectionDuration") public void setEBranchOutboundConnectionDuration(String eBranchOutboundConnectionDuration) { this.eBranchOutboundConnectionDuration = eBranchOutboundConnectionDuration; } }
34.411765
306
0.806838
236e04b8201f8e3f19d1c522405770b73405c994
968
package com.pharmacySystem.DTOs; import com.pharmacySystem.model.grade.GradeType; public class CreateGradeDTO { private Long patientId; private Long gradedId; private GradeType gradeType; private int grade; public CreateGradeDTO() { } public CreateGradeDTO(Long patientId, Long gradedId, GradeType gradeType, int grade) { super(); this.patientId = patientId; this.gradedId = gradedId; this.gradeType = gradeType; this.grade = grade; } public Long getPatientId() { return patientId; } public void setPatientId(Long patientId) { this.patientId = patientId; } public Long getGradedId() { return gradedId; } public void setGradedId(Long gradedId) { this.gradedId = gradedId; } public GradeType getGradeType() { return gradeType; } public void setGradeType(GradeType gradeType) { this.gradeType = gradeType; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } }
17.925926
87
0.725207
6df5e9dd9cb276aed134ad69d572a1fdb751f76d
179
package br.acme.exception; @SuppressWarnings("serial") public class CpfInvalidoException extends Exception{ public CpfInvalidoException(String msgErro){ super(msgErro); } }
17.9
52
0.793296
51db7eb606171af45d1894c901978797d545e243
2,967
package com.thaidt.testopencv; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; import org.opencv.android.OpenCVLoader; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final int MY_CAMERA_REQUEST_CODE = 100; static final String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (OpenCVLoader.initDebug()) { Toast.makeText(this, "OpenCV initialize success", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "OpenCV initialize failed", Toast.LENGTH_LONG).show(); } if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE); } findViewById(R.id.colorBlobDetectionBtn).setOnClickListener(this); findViewById(R.id.drawHistogramBtn).setOnClickListener(this); findViewById(R.id.floodFillmBtn).setOnClickListener(this); findViewById(R.id.newFloodFillmBtn).setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.colorBlobDetectionBtn: startActivity(new Intent(this, ColorBlodDetectionActivity.class)); break; case R.id.drawHistogramBtn: startActivity(new Intent(this, EdgeDetectionActivity.class)); break; case R.id.floodFillmBtn: startActivity(new Intent(this, FloodFillActivity.class)); break; case R.id.newFloodFillmBtn: startActivity(new Intent(this, NewFloodFillActivity.class)); break; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == MY_CAMERA_REQUEST_CODE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show(); finish(); startActivity(new Intent(this, MainActivity.class)); } else { Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show(); } } } }
38.532468
121
0.675093
bb5468935c0475b3a6e2f3f807264d497b5fc169
3,703
package com.gempukku.swccgo.cards.set5.dark; import com.gempukku.swccgo.cards.AbstractUsedOrLostInterrupt; import com.gempukku.swccgo.cards.GameConditions; import com.gempukku.swccgo.cards.effects.CancelWeaponTargetingEffect; import com.gempukku.swccgo.common.CardSubtype; import com.gempukku.swccgo.common.Icon; import com.gempukku.swccgo.common.Side; import com.gempukku.swccgo.common.Uniqueness; import com.gempukku.swccgo.filters.Filters; import com.gempukku.swccgo.game.PhysicalCard; import com.gempukku.swccgo.game.SwccgGame; import com.gempukku.swccgo.logic.TriggerConditions; import com.gempukku.swccgo.logic.actions.PlayInterruptAction; import com.gempukku.swccgo.logic.effects.RespondablePlayCardEffect; import com.gempukku.swccgo.logic.effects.UseForceEffect; import com.gempukku.swccgo.logic.timing.Action; import com.gempukku.swccgo.logic.timing.Effect; import java.util.LinkedList; import java.util.List; /** * Set: Cloud City * Type: Interrupt * Subtype: Used Or Lost * Title: Force Field */ public class Card5_142 extends AbstractUsedOrLostInterrupt { public Card5_142() { super(Side.DARK, 4, "Force Field", Uniqueness.UNIQUE); setLore("Han was fast. Vader was faster."); setGameText("USED: Cancel an attempt to target a Dark Jedi with a character weapon. LOST: If one of your characters was just targeted by a weapon during a battle, use 3 Force to cancel the targeting."); addIcons(Icon.CLOUD_CITY); } @Override protected List<PlayInterruptAction> getGameTextOptionalBeforeActions(final String playerId, SwccgGame game, final Effect effect, final PhysicalCard self) { List<PlayInterruptAction> actions = new LinkedList<PlayInterruptAction>(); // Check condition(s) if (TriggerConditions.isTargetedByWeapon(game, effect, Filters.Dark_Jedi, Filters.character_weapon)) { final PlayInterruptAction action = new PlayInterruptAction(game, self, CardSubtype.USED); action.setText("Cancel weapon targeting"); // Allow response(s) action.allowResponses( new RespondablePlayCardEffect(action) { @Override protected void performActionResults(Action targetingAction) { // Perform result(s) action.appendEffect( new CancelWeaponTargetingEffect(action)); } } ); actions.add(action); } // Check condition(s) if (TriggerConditions.isTargetedByWeapon(game, effect, Filters.and(Filters.your(self), Filters.character), Filters.weapon) && GameConditions.isDuringBattle(game) && GameConditions.canUseForceToPlayInterrupt(game, playerId, self, 3)) { final PlayInterruptAction action = new PlayInterruptAction(game, self, CardSubtype.LOST); action.setText("Cancel weapon targeting"); // Pay cost(s) action.appendCost( new UseForceEffect(action, playerId, 3)); // Allow response(s) action.allowResponses( new RespondablePlayCardEffect(action) { @Override protected void performActionResults(Action targetingAction) { // Perform result(s) action.appendEffect( new CancelWeaponTargetingEffect(action)); } } ); actions.add(action); } return actions; } }
42.563218
210
0.644072
6c75f8a0b0a7c20ce5815677960e59a75a29674a
7,088
/* * 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.facebook.presto.verifier.framework; import com.facebook.presto.sql.parser.SqlParser; import com.facebook.presto.tests.StandaloneQueryRunner; import com.facebook.presto.verifier.event.VerifierQueryEvent; import com.facebook.presto.verifier.event.VerifierQueryEvent.EventStatus; import com.facebook.presto.verifier.prestoaction.JdbcPrestoAction; import com.facebook.presto.verifier.prestoaction.PrestoAction; import com.facebook.presto.verifier.prestoaction.PrestoActionConfig; import com.facebook.presto.verifier.prestoaction.PrestoExceptionClassifier; import com.facebook.presto.verifier.prestoaction.QueryActions; import com.facebook.presto.verifier.prestoaction.QueryActionsConfig; import com.facebook.presto.verifier.retry.RetryConfig; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Optional; import static com.facebook.presto.verifier.VerifierTestUtil.CATALOG; import static com.facebook.presto.verifier.VerifierTestUtil.SCHEMA; import static com.facebook.presto.verifier.VerifierTestUtil.setupPresto; import static com.facebook.presto.verifier.event.VerifierQueryEvent.EventStatus.FAILED; import static com.facebook.presto.verifier.event.VerifierQueryEvent.EventStatus.SUCCEEDED; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestExplainVerification { private static final String SUITE = "test-suite"; private static final String NAME = "test-query"; private static final String TEST_ID = "test-id"; private static final QueryConfiguration QUERY_CONFIGURATION = new QueryConfiguration(CATALOG, SCHEMA, Optional.of("user"), Optional.empty(), Optional.empty()); private static final SqlParser sqlParser = new SqlParser(); private static StandaloneQueryRunner queryRunner; @BeforeClass public void setupClass() throws Exception { queryRunner = setupPresto(); } @Test public void testSuccess() { Optional<VerifierQueryEvent> event = runVerification("SELECT 1"); assertTrue(event.isPresent()); assertEvent(event.get(), SUCCEEDED); assertEquals(event.get().getMatchType(), "MATCH"); assertEquals(event.get().getControlQueryInfo().getQuery(), "EXPLAIN (FORMAT JSON)\nSELECT 1\n\n"); assertEquals(event.get().getTestQueryInfo().getQuery(), "EXPLAIN (FORMAT JSON)\nSELECT 1\n\n"); assertNotNull(event.get().getControlQueryInfo().getJsonPlan()); assertNotNull(event.get().getTestQueryInfo().getJsonPlan()); } @Test public void testPlanChanged() { Optional<VerifierQueryEvent> event = runVerification("SELECT 1", "SELECT 2"); assertTrue(event.isPresent()); // Explain verification do not fail in case of plan changes. assertEvent(event.get(), SUCCEEDED); assertEquals(event.get().getMatchType(), "PLAN_CHANGED"); assertEquals(event.get().getControlQueryInfo().getQuery(), "EXPLAIN (FORMAT JSON)\nSELECT 1\n\n"); assertEquals(event.get().getTestQueryInfo().getQuery(), "EXPLAIN (FORMAT JSON)\nSELECT 2\n\n"); assertNotNull(event.get().getControlQueryInfo().getJsonPlan()); assertNotNull(event.get().getTestQueryInfo().getJsonPlan()); } @Test public void testSkipControl() { Optional<VerifierQueryEvent> event = runVerification("SHOW FUNCTIONS"); assertTrue(event.isPresent()); assertEvent(event.get(), SUCCEEDED); assertNull(event.get().getMatchType()); assertNull(event.get().getControlQueryInfo()); assertEquals(event.get().getTestQueryInfo().getQuery(), "EXPLAIN (FORMAT JSON)\nSHOW FUNCTIONS"); assertNotNull(event.get().getTestQueryInfo().getJsonPlan()); } @Test public void testFailure() { Optional<VerifierQueryEvent> event = runVerification("SELECT 1", "SELECT x"); assertTrue(event.isPresent()); assertEvent(event.get(), FAILED); assertNull(event.get().getMatchType()); assertEquals(event.get().getControlQueryInfo().getQuery(), "EXPLAIN (FORMAT JSON)\nSELECT 1\n\n"); assertEquals(event.get().getTestQueryInfo().getQuery(), "EXPLAIN (FORMAT JSON)\nSELECT x\n\n"); assertNotNull(event.get().getControlQueryInfo().getJsonPlan()); assertNull(event.get().getTestQueryInfo().getJsonPlan()); } private Optional<VerifierQueryEvent> runVerification(String query) { return runVerification(query, query); } private Optional<VerifierQueryEvent> runVerification(String controlQuery, String testQuery) { SourceQuery sourceQuery = new SourceQuery(SUITE, NAME, controlQuery, testQuery, QUERY_CONFIGURATION, QUERY_CONFIGURATION); PrestoExceptionClassifier exceptionClassifier = PrestoExceptionClassifier.defaultBuilder().build(); VerificationContext verificationContext = VerificationContext.create(NAME, SUITE); VerifierConfig verifierConfig = new VerifierConfig().setTestId(TEST_ID); RetryConfig retryConfig = new RetryConfig(); QueryActionsConfig queryActionsConfig = new QueryActionsConfig(); PrestoAction prestoAction = new JdbcPrestoAction( exceptionClassifier, sourceQuery.getControlConfiguration(), verificationContext, new PrestoActionConfig() .setHosts(queryRunner.getServer().getAddress().getHost()) .setJdbcPort(queryRunner.getServer().getAddress().getPort()), queryActionsConfig.getMetadataTimeout(), queryActionsConfig.getChecksumTimeout(), retryConfig, retryConfig, verifierConfig); return new ExplainVerification( new QueryActions(prestoAction, prestoAction, prestoAction), sourceQuery, exceptionClassifier, verificationContext, verifierConfig, sqlParser).run().getEvent(); } private void assertEvent( VerifierQueryEvent event, EventStatus expectedStatus) { assertEquals(event.getSuite(), SUITE); assertEquals(event.getTestId(), TEST_ID); assertEquals(event.getName(), NAME); assertEquals(event.getStatus(), expectedStatus.name()); } }
44.3
163
0.709227
a42674385cadc2a0b59d00716446bdd4433e831f
810
package com.sercapnp.lang; /** * Created by striky on 6/26/17. */ import com.intellij.openapi.fileTypes.LanguageFileType; import org.jetbrains.annotations.*; import javax.swing.*; public class CapnpFileType extends LanguageFileType { public static final CapnpFileType INSTANCE = new CapnpFileType(); private CapnpFileType() { super(CapnpLanguage.INSTANCE); } @NotNull @Override public String getName() { return "Capnp file"; } @NotNull @Override public String getDescription() { return "Capnp language file"; } @NotNull @Override public String getDefaultExtension() { return "Capnp"; } @Nullable @Override public Icon getIcon() { return null; //return CapnpIcons.FILE; } }
17.608696
69
0.639506
525435dab43b0172275626f102cd0960f49fe625
329
package com.rajesh.spring.core; public class OldRunner { public static void main(String[] args) { HelloBean1 bean1 = new HelloBean1(); bean1.setMessage("Hello World !!"); bean1.sayHello(); HelloBean2 bean2 = new HelloBean2(); bean2.setMessage("Hello World !!"); bean2.setPerson("Rajesh"); bean2.sayHello(); } }
21.933333
41
0.693009
8643bbf722bc2edc06540c6cae8e22775e1e710b
567
package plugins.haesleinhuepf.implementations.generated; import plugins.haesleinhuepf.AbstractCLIJ2Block; import net.haesleinhuepf.clij2.plugins.DivideByGaussianBackground; // this is generated code. See src/test/java/net/haesleinhuepf/clicy/codegenerator for details public class CLIJ2_DivideByGaussianBackgroundBlock extends AbstractCLIJ2Block { /** * Applies Gaussian blur to the input image and divides the original by the result. */ public CLIJ2_DivideByGaussianBackgroundBlock() { super(new DivideByGaussianBackground()); } }
37.8
94
0.790123
29b19cb6de9248ef931916a641fe15984adb620c
5,068
package net.qreact.app.apprate; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.util.Log; import android.view.View; import android.widget.RatingBar; import androidx.annotation.NonNull; public final class QreactRate { private Integer appTitle = R.string.popupTitle; private String qreactToken = ""; private int daysUntilPrompt = 0; // minimum number of days private int launchesUntilPrompt = 0; // minimum number of launches private int targetLevel = 0; private int ratedIndex = 0; private Boolean neverShow = false; private QreactDialog dialog = null; private Context mContext = null; private SharedPreferences prefs; public QreactRate prepare(@NonNull Context context) { mContext = context; prefs = context.getSharedPreferences("qreact", 0); if (prefs.getBoolean("qreactNeverAgain", false)) { neverShow = true; return this; } SharedPreferences.Editor editor = prefs.edit(); // increment launch counter long launchCt = prefs.getLong("qreactLaunchCt", 0) + 1; editor.putLong("qreactLaunchCt", launchCt); // get date first launch long dateFirstLaunch = prefs.getLong("qreactDateFirst", 0); if (dateFirstLaunch == 0) { dateFirstLaunch = System.currentTimeMillis(); editor.putLong("qreactDateFirst", dateFirstLaunch); } if (launchCt >= launchesUntilPrompt) { if (System.currentTimeMillis() >= (dateFirstLaunch + (daysUntilPrompt * 24 * 60 * 60 * 1000))) { if (dialog == null) { dialog = new QreactDialog(context); dialog.setAppTitle(appTitle); } prepareDialog(); } } editor.apply(); return this; } private void prepareDialog() { final SharedPreferences.Editor editor = prefs.edit(); dialog.getRatingBar().setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float v, boolean b) { ratedIndex = (int)v; } }); dialog.getNeverBtn().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { editor.putBoolean("qreactNeverAgain", true); dialog.dismiss(); } }); dialog.getCancelBtn().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); dialog.getRateBtn().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(ratedIndex <= targetLevel) { onQreact(); } else { onPlayStore(); } } }); editor.apply(); } private void onPlayStore() { if(mContext == null) return; String packageName = mContext.getPackageName(); try { String marketPrefix = "market://details?id="; mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(marketPrefix + packageName))); } catch (android.content.ActivityNotFoundException e) { String playStorePrefix = "https://play.google.com/store/apps/details?id="; mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(playStorePrefix + packageName))); } } private void onQreact() { try { String qreactUrl = "https://www.qreact.net/public/form?token="; mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qreactUrl + qreactToken))); } catch (android.content.ActivityNotFoundException e) { Log.d("ActivityFoundException", e.toString()); } } public void show() { if (!neverShow) dialog.show(); } public QreactRate setDialog(@NonNull QreactDialog dialog) { this.dialog = dialog; return this; } public QreactRate setAppTitle(@NonNull Integer appTitle) { this.appTitle = appTitle; return this; } public QreactRate setDaysUntilPrompt(int day) { this.daysUntilPrompt = day > 0 ? day : 0; return this; } public QreactRate setLaunchesUntilPrompt(int day) { this.launchesUntilPrompt = day > 0 ? day : 0; return this; } public QreactRate setToken(String token) { this.qreactToken = token != null ? token : ""; return this; } public QreactRate setTargetLevel(int targetLevel) { if (targetLevel >= 1 && targetLevel <= 5) { this.targetLevel = targetLevel; } return this; } }
30.715152
109
0.588003
721f5382c47436c240a2e56cfc27ec8584792c81
5,240
import java.io.*; import java.util.*; class WordPuzzle { public static void main(String[] args) { new WordPuzzle().run(); } class $R { InputStream in; byte b; byte[] buf; int bi, bz; $R(InputStream I) { in=I; buf=new byte[65536]; bi=bz=0; read(); } boolean hasNext() { skip(); return b >= 0; } void skip() { while (b >= 0 && b <= 32) read(); } String next() { StringBuilder sb = new StringBuilder(); for (skip(); b > 32; read()) sb.append((char)b); return sb.length() == 0 ? null : sb.toString(); } String nextLine() { StringBuilder sb = new StringBuilder(); for (; b != 10 && b != 13; read()) sb.append((char)b); while (b == 10 || b == 13) read(); return sb.toString(); } int nextInt() { int i=0; boolean s=false; skip(); if (b == '-') { s=true; read(); } for (; b > 32; read()) i = i*10 + b-48; return s ? -i : i; } void read() { if (bi==bz) { bi=0; try { bz=in.read(buf); } catch(Exception e) { bz=-1; } } b = bz == -1 ? -1 : buf[bi++]; } } class $W extends PrintWriter { $W() { super(new BufferedOutputStream(System.out)); } } class $G { class E { int u, v, w; E(int U, int V, int W) { u=U; v=V; w=W; } } class EL extends ArrayList<E> { EL(){super();} EL(int c){super(c);} } EL ae; EL[] ve; int[] in, out; int n, m; $G(int N) { n=N; init(); } $G(int N, int M) { n=N; m=M; init(); } void init() { ae = m==0 ? new EL() : new EL(m); ve = new EL[n]; out = new int[n]; in = new int[n]; } void add(int u, int v, int w) { E e = new E(u, v, w); ae.add(e); check(u).add(e); out[u]++; in[v]++; } void addm(int u, int v, int w) { add(u, v, w); m++; } EL check(int v) { return ve[v] == null ? (ve[v]=new EL()) : ve[v]; } E edge(int v, int i) { return ve[v].get(i); } // Auxiliary types/attr class VL extends ArrayList<Integer> {} class VLL extends ArrayList<VL> {} class VQ extends ArrayDeque<Integer> {} class EQ extends ArrayDeque<E> {} VQ vq; boolean[] col; int[] dis, glow, gidx; int gcnt; // Euler trails VL _trail; EQ[] _adjq; VL eulerTrail() { _adjq = new EQ[n]; int nOdd = 0, start = 0; for (int u = 0; u < n; u++) { _adjq[u] = new EQ(); if (start == 0 && out[u] > 0) start = u; for (int i = 0; i < out[u]; i++) _adjq[u].add(edge(u, i)); } for (int v = 0; v < n; v++) { int diff = Math.abs(in[v] - out[v]); if (diff > 1) return null; if (diff == 1) { if (++nOdd > 2) return null; if (out[v] > in[v]) start = v; } } _trail = new VL(); eulerBuildTrail(start); Collections.reverse(_trail); return _trail; } void eulerBuildTrail(int u) { while(! _adjq[u].isEmpty()) { E e = _adjq[u].remove(); eulerBuildTrail(e.v); } _trail.add(u); } } class WordQueue extends ArrayDeque<String> {} int N; $G g; WordQueue[][] words; // words indexed by first and last letter void run() { $R $r = new $R(System.in); $W $w = new $W(); int T = $r.nextInt(); for (int ncase = 1; ncase <= T; ncase++) { N = $r.nextInt(); g = new $G(26); words = new WordQueue[26][26]; for (int i = 0; i < N; i++) { String node = $r.next(); int first = (int) node.charAt(0) - 'a'; int last = (int) node.charAt(node.length() - 1) - 'a'; addWord(first, last, node); g.addm(first, last, 0); } $G.VL trail = g.eulerTrail(); $w.print("Case " + ncase + ": "); if (trail == null || trail.size() != N + 1) $w.println("No"); else { $w.println("Yes"); int pre = trail.get(0); boolean firstPrint = true; for (int i = 1, nv = trail.size(); i < nv; i++) { int cur = trail.get(i); String w = getWord(pre, cur); if (w == null) break; if (firstPrint) firstPrint = false; else $w.print(' '); $w.print(w); pre = cur; } $w.println(); } } $w.close(); } void addWord(int first, int last, String w) { if (words[first][last] == null) words[first][last] = new WordQueue(); words[first][last].add(w); } String getWord(int first, int last) { if (words[first][last] == null || words[first][last].isEmpty()) return null; return words[first][last].remove(); } }
34.248366
78
0.422328
a431503f5993fe471568f5fc6288b01327ca7789
24,876
package com.dwarfeng.tpnclib.core.control; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Set; import java.util.StringTokenizer; import java.util.WeakHashMap; import java.util.concurrent.Executors; import javax.swing.Icon; import javax.swing.text.StyledDocument; import com.dwarfeng.dutil.basic.cna.model.DefaultReferenceModel; import com.dwarfeng.dutil.basic.cna.model.DelegateListModel; import com.dwarfeng.dutil.basic.cna.model.ListModel; import com.dwarfeng.dutil.basic.cna.model.ReferenceModel; import com.dwarfeng.dutil.basic.cna.model.SyncListModel; import com.dwarfeng.dutil.basic.cna.model.SyncReferenceModel; import com.dwarfeng.dutil.basic.prog.DefaultVersion; import com.dwarfeng.dutil.basic.prog.ProcessException; import com.dwarfeng.dutil.basic.prog.ProgramObverser; import com.dwarfeng.dutil.basic.prog.RuntimeState; import com.dwarfeng.dutil.basic.prog.Version; import com.dwarfeng.dutil.basic.prog.VersionType; import com.dwarfeng.dutil.basic.str.Name; import com.dwarfeng.dutil.develop.backgr.Background; import com.dwarfeng.dutil.develop.backgr.ExecutorServiceBackground; import com.dwarfeng.dutil.develop.backgr.Task; import com.dwarfeng.dutil.develop.backgr.obv.BackgroundObverser; import com.dwarfeng.dutil.develop.cfg.ConfigUtil; import com.dwarfeng.dutil.develop.cfg.DefaultExconfigModel; import com.dwarfeng.dutil.develop.cfg.ExconfigModel; import com.dwarfeng.dutil.develop.cfg.SyncExconfigModel; import com.dwarfeng.dutil.develop.cfg.obv.ExconfigObverser; import com.dwarfeng.dutil.develop.i18n.DelegateI18nHandler; import com.dwarfeng.dutil.develop.i18n.I18nHandler; import com.dwarfeng.dutil.develop.i18n.I18nUtil; import com.dwarfeng.dutil.develop.i18n.SyncI18nHandler; import com.dwarfeng.dutil.develop.resource.DelegateResourceHandler; import com.dwarfeng.dutil.develop.resource.ResourceHandler; import com.dwarfeng.dutil.develop.resource.ResourceUtil; import com.dwarfeng.dutil.develop.resource.SyncResourceHandler; import com.dwarfeng.tpnclib.core.model.cm.DelegateLoggerHandler; import com.dwarfeng.tpnclib.core.model.cm.LoggerHandler; import com.dwarfeng.tpnclib.core.model.cm.SyncLoggerHandler; import com.dwarfeng.tpnclib.core.model.eum.CoreConfiguration; import com.dwarfeng.tpnclib.core.model.eum.DialogMessage; import com.dwarfeng.tpnclib.core.model.eum.DialogOption; import com.dwarfeng.tpnclib.core.model.eum.DialogOptionCombo; import com.dwarfeng.tpnclib.core.model.eum.ModalConfiguration; import com.dwarfeng.tpnclib.core.model.eum.TpncLibProperty; import com.dwarfeng.tpnclib.core.model.io.DefaultPluginClassLoader; import com.dwarfeng.tpnclib.core.model.io.PluginClassLoader; import com.dwarfeng.tpnclib.core.model.struct.PieceCata; import com.dwarfeng.tpnclib.core.model.struct.Toolkit; import com.dwarfeng.tpnclib.core.model.struct.Toolkit.BackgroundType; import com.dwarfeng.tpnclib.core.util.ModelUtil; import com.dwarfeng.tpnclib.core.view.gui.MainFrame; import com.dwarfeng.tpnclib.core.view.struct.GuiManager; import com.dwarfeng.tpnclib.core.view.struct.WindowSuppiler; /** * TODO 详细的介绍。 * * @author DwArFeng * @since 0.0.1-alpha */ public final class TpncLib { public final class TpncLibToolkit implements Toolkit { /** * {@inheritDoc} */ @Override public boolean addCoreConfigObverser(ExconfigObverser coreConfigObverser) throws IllegalStateException { return coreConfigModel.addObverser(coreConfigObverser); } /** * {@inheritDoc} */ @Override public boolean addProgramObverser(ProgramObverser obverser) throws IllegalStateException { synchronized (programObversers) { return programObversers.add(obverser); } } /** * {@inheritDoc} */ @Override public void disposeMainFrame() throws IllegalStateException { synchronized (mainFrameLock) { if (Objects.isNull(mainFrame)) { return; } mainFrame.dispose(); mainFrame = null; } } /** * {@inheritDoc} */ @Override public void error(String message, Throwable t) throws IllegalStateException { Objects.requireNonNull(message, "入口参数 message 不能为 null。"); Objects.requireNonNull(t, "入口参数 t 不能为 null。"); loggerHandler.error(message, t); } /** * {@inheritDoc} */ @Override public void exit() throws IllegalStateException, ProcessException { synchronized (startExitLock) { if (isDisposeFlag()) { if (getRuntimeState() == RuntimeState.RUNNING) { throw new IllegalStateException("程序正在运行"); } if (getRuntimeState() == RuntimeState.NOT_START) { throw new IllegalStateException("程序还未启动"); } throw new IllegalStateException("由于释放标志为 true,程序无法释放"); } setDisposeFlag(true); // 开启释放过程 final Task task = new DisposeTask(TpncLib.this); task.run(); // 解除自身引用 INSTANCES.remove(this); // 反编织观察网络。 coreConfigModel.removeObverser(coreConfigObverser); concurrentBackground.removeObverser(backgroundObverser); queueBackground.removeObverser(backgroundObverser); // 判断是否出现异常。 if (Objects.nonNull(task.getThrowable())) { throw new ProcessException("释放过程失败", task.getThrowable()); } // 设置程序的运行状态为已经结束 setRuntimeState(RuntimeState.ENDED); } } /** * {@inheritDoc} */ @Override public void fatal(String message, Throwable t) throws IllegalStateException { Objects.requireNonNull(message, "入口参数 message 不能为 null。"); Objects.requireNonNull(t, "入口参数 t 不能为 null。"); loggerHandler.fatal(message, t); } /** * {@inheritDoc} */ @Override public SyncReferenceModel<Name> getAnchorInstrItemModel() throws IllegalArgumentException { return anchorInstructionItemModel; } /** * {@inheritDoc} */ @Override public ReferenceModel<Name> getAnchorInstrItemModelReadOnly() throws IllegalArgumentException { return com.dwarfeng.dutil.basic.cna.model.ModelUtil.readOnlyReferenceModel(anchorInstructionItemModel, name -> { return name; }); } /** * {@inheritDoc} */ @Override public SyncReferenceModel<PieceCata> getAnchorPieceCataModel() { return anchorPieceCataModel; } /** * {@inheritDoc} */ @Override public ReferenceModel<PieceCata> getAnchorPieceCataModelReadOnly() { return com.dwarfeng.dutil.basic.cna.model.ModelUtil.readOnlyReferenceModel(anchorPieceCataModel, pieceCata -> { return ModelUtil.unmodifiablePieceCata(pieceCata); }); } /** * {@inheritDoc} */ @Override public Background getBackground(BackgroundType type) throws IllegalStateException { Objects.requireNonNull(type, "入口参数 type 不能为 null。"); switch (type) { case CONCURRENT: return concurrentBackground; case FIFO: return queueBackground; } throw new IllegalArgumentException("入口参数 " + type + " 不合法"); } /** * {@inheritDoc} */ @Override public SyncExconfigModel getCoreConfigModel() throws IllegalStateException { return coreConfigModel; } /** * {@inheritDoc} */ @Override public ExconfigModel getCoreConfigModelReadOnly() throws IllegalStateException { return ConfigUtil.unmodifiableExconfigModel(coreConfigModel); } /** * {@inheritDoc} */ @Override public int getExitCode() throws IllegalStateException { synchronized (exitCodeLock) { return exitCode; } } /** * {@inheritDoc} */ @Override public SyncReferenceModel<StyledDocument> getInstrDocModel() throws IllegalArgumentException { return instrDocModel; } /** * {@inheritDoc} */ @Override public SyncListModel<Name> getInstrItemModel() throws IllegalArgumentException { return instrItemModel; } /** * {@inheritDoc} */ @Override public ListModel<Name> getInstrItemModelReadOnly() throws IllegalArgumentException { return com.dwarfeng.dutil.basic.cna.model.ModelUtil.readOnlyListModel(instrItemModel, name -> { return name; }); } /** * {@inheritDoc} */ @Override public SyncI18nHandler getLabelI18nHandler() throws IllegalStateException { return labelI18nHandler; } /** * {@inheritDoc} */ @Override public I18nHandler getLabelI18nHandlerReadOnly() throws IllegalStateException { return I18nUtil.readOnlyI18nHandler(labelI18nHandler); } /** * {@inheritDoc} */ @Override public PluginClassLoader getLibraryClassLoader() throws IllegalStateException { return libraryClassLoader; } @Override public SyncLoggerHandler getLoggerHandler() throws IllegalStateException { return loggerHandler; } @Override public LoggerHandler getLoggerHandlerReadOnly() throws IllegalStateException { return ModelUtil.unmodifiableLoggerHandler(loggerHandler); } /** * {@inheritDoc} */ @Override public SyncI18nHandler getLoggerI18nHandler() throws IllegalStateException { return loggerI18nHandler; } /** * {@inheritDoc} */ @Override public I18nHandler getLoggerI18nHandlerReadOnly() throws IllegalStateException { return I18nUtil.readOnlyI18nHandler(loggerI18nHandler); } /** * {@inheritDoc} */ @Override public MainFrame getMainFrame() throws IllegalStateException { synchronized (mainFrameLock) { return mainFrame; } } /** * {@inheritDoc} */ @Override public SyncExconfigModel getModalConfigModel() throws IllegalStateException { return modalConfigModel; } /** * {@inheritDoc} */ @Override public ExconfigModel getModalConfigModelReadOnly() throws IllegalStateException { return ConfigUtil.unmodifiableExconfigModel(modalConfigModel); } /** * {@inheritDoc} */ @Override public SyncListModel<PieceCata> getPieceCataModel() { return pieceCataModel; } /** * {@inheritDoc} */ @Override public ListModel<PieceCata> getPieceCataModelReadOnly() { return com.dwarfeng.dutil.basic.cna.model.ModelUtil.readOnlyListModel(pieceCataModel, pieceCata -> { return ModelUtil.unmodifiablePieceCata(pieceCata); }); } /** * {@inheritDoc} */ @Override public String getProperty(TpncLibProperty property) throws IllegalStateException { Objects.requireNonNull(property, "入口参数 property 不能为 null。"); synchronized (property) { return properties.getOrDefault(property, DEFAULT_PROPERTIES.get(property)); } } /** * {@inheritDoc} */ @Override public SyncResourceHandler getResourceHandler() throws IllegalStateException { return resourceHandler; } /** * {@inheritDoc} */ @Override public ResourceHandler getResourceHandlerReadOnly() throws IllegalStateException { return ResourceUtil.readOnlyResourceHandler(resourceHandler); } /** * {@inheritDoc} */ @Override public RuntimeState getRuntimeState() throws IllegalStateException { synchronized (runtimeStateLock) { return runtimeState; } } /** * {@inheritDoc} */ @Override public boolean hasPermission(Method method) { return true; } /** * {@inheritDoc} */ @Override public void info(String message) throws IllegalStateException { Objects.requireNonNull(message, "入口参数 message 不能为 null。"); loggerHandler.info(message); } /** * {@inheritDoc} */ @Override public void newMainFrame() throws IllegalStateException { synchronized (mainFrameLock) { if (Objects.nonNull(mainFrame)) { return; } mainFrame = new MainFrame(guiManager, labelI18nHandler, pieceCataModel, anchorPieceCataModel, instrDocModel); } } /** * {@inheritDoc} */ @Override public void setExitCode(int exitCode) throws IllegalStateException { synchronized (exitCodeLock) { TpncLib.this.exitCode = exitCode; } } /** * {@inheritDoc} */ @Override public void setRuntimeState(RuntimeState runtimeState) throws IllegalStateException { synchronized (runtimeStateLock) { RuntimeState oldState = TpncLib.this.runtimeState; TpncLib.this.runtimeState = runtimeState; fireRuntimeStateChanged(oldState, runtimeState); } } @Override public DialogOption showConfirmDialog(Object message) throws IllegalStateException { // TODO Auto-generated method stub return null; } @Override public DialogOption showConfirmDialog(Object message, String title, DialogOptionCombo dialogOptionCombo) throws IllegalStateException { // TODO Auto-generated method stub return null; } @Override public DialogOption showConfirmDialog(Object message, String title, DialogOptionCombo dialogOptionCombo, DialogMessage dialogMessage) throws IllegalStateException { // TODO Auto-generated method stub return null; } @Override public DialogOption showConfirmDialog(Object message, String title, DialogOptionCombo dialogOptionCombo, DialogMessage dialogMessage, Icon icon) throws IllegalStateException { // TODO Auto-generated method stub return null; } @Override public void showExternalWindow(String key) { // TODO Auto-generated method stub } @Override public void showExternalWindow(WindowSuppiler suppiler) { // TODO Auto-generated method stub } @Override public String showInputDialog(Object message) throws IllegalStateException { // TODO Auto-generated method stub return null; } @Override public String showInputDialog(Object message, Object initialSelectionValue) throws IllegalStateException { // TODO Auto-generated method stub return null; } @Override public String showInputDialog(Object message, String title, DialogMessage dialogMessage) throws IllegalStateException { // TODO Auto-generated method stub return null; } @Override public Object showInputDialog(Object message, String title, DialogMessage dialogMessage, Icon icon, Object[] selectionValues, Object initialSelectionValue) throws IllegalStateException { // TODO Auto-generated method stub return null; } @Override public void showMessageDialog(Object message) throws IllegalStateException { // TODO Auto-generated method stub } @Override public void showMessageDialog(Object message, String title, DialogMessage dialogMessage) throws IllegalStateException { // TODO Auto-generated method stub } @Override public void showMessageDialog(Object message, String title, DialogMessage dialogMessage, Icon icon) throws IllegalStateException { // TODO Auto-generated method stub } @Override public int showOptionDialog(Object message, String title, DialogOptionCombo dialogOptionCombo, DialogMessage dialogMessage, Icon icon, Object[] options, Object initialValue) throws IllegalStateException { // TODO Auto-generated method stub return 0; } /** * {@inheritDoc} */ @Override public void start() throws IllegalStateException, ProcessException { synchronized (startExitLock) { if (isStartFlag()) { if (getRuntimeState() == RuntimeState.RUNNING) { throw new IllegalStateException("程序正在运行"); } if (getRuntimeState() == RuntimeState.ENDED) { throw new IllegalStateException("程序已经结束"); } throw new IllegalStateException("由于启动标志为 true,程序无法启动"); } setStartFlag(true); // 编织观察网络 coreConfigModel.addObverser(coreConfigObverser); concurrentBackground.addObverser(backgroundObverser); queueBackground.addObverser(backgroundObverser); // 开启初始化过程 final Task task = new PoseTask(TpncLib.this); task.run(); // 判断是否出现异常。 if (Objects.nonNull(task.getThrowable())) { throw new ProcessException("初始化过程失败", task.getThrowable()); } // 设置程序的运行状态为正在运行 setRuntimeState(RuntimeState.RUNNING); } } /** * {@inheritDoc} */ @Override public void submitTask(Task task, BackgroundType type) throws IllegalStateException { Objects.requireNonNull(task, "入口参数 task 不能为 null。"); Objects.requireNonNull(type, "入口参数 type 不能为 null。"); switch (type) { case CONCURRENT: concurrentBackground.submit(task); return; case FIFO: queueBackground.submit(task); return; } throw new IllegalArgumentException("入口参数 " + type + " 不合法"); } /** * {@inheritDoc} */ @Override public void trace(String message) throws IllegalStateException { Objects.requireNonNull(message, "入口参数 message 不能为 null。"); loggerHandler.trace(message); } /** * {@inheritDoc} */ @Override public void tryExit() throws IllegalStateException { // TODO 完善关闭程序的方法。 // manager.getBackgroundModel().submit(flowProvider.newClosingFlow()); } /** * {@inheritDoc} */ @Override public void warn(String message) throws IllegalStateException { Objects.requireNonNull(message, "入口参数 message 不能为 null。"); loggerHandler.warn(message); } /** * {@inheritDoc} */ @Override public void warn(String message, Throwable t) throws IllegalStateException { Objects.requireNonNull(message, "入口参数 message 不能为 null。"); Objects.requireNonNull(t, "入口参数 t 不能为 null。"); loggerHandler.warn(message, t); } private boolean isDisposeFlag() { synchronized (disposeFlagLock) { return disposeFlag; } } private boolean isStartFlag() { synchronized (startFlagLock) { return startFlag; } } private void setDisposeFlag(boolean disposeFlag) { synchronized (disposeFlagLock) { TpncLib.this.disposeFlag = disposeFlag; } } private void setStartFlag(boolean startFlag) { synchronized (startFlagLock) { TpncLib.this.startFlag = startFlag; } } } private final class TpncLibGuiManager implements GuiManager { /** * {@inheritDoc} */ @Override public void exit(ExecType type) { doTask(new ExitTask(TpncLib.this), type); } @Override public void setAnchorPieceCata(PieceCata newValue, ExecType type) { doTask(new SetAnchorPieceCataTask(TpncLib.this, newValue), type); } private void doTask(Task task, ExecType type) { Objects.requireNonNull(type, "入口参数 type 不能为 null。"); switch (type) { case CONCURRENT: getToolkit().submitTask(task, BackgroundType.CONCURRENT); return; case FIFO: getToolkit().submitTask(task, BackgroundType.FIFO); return; } throw new IllegalArgumentException("入口参数 " + type + " 不合法"); } } /** 程序的版本 */ public final static Version VERSION = new DefaultVersion.Builder().type(VersionType.ALPHA).firstVersion((byte) 0) .secondVersion((byte) 0).thirdVersion((byte) 1).buildDate("19700101").buildVersion('A').build(); private final static Map<TpncLibProperty, String> DEFAULT_PROPERTIES = new EnumMap<>(TpncLibProperty.class); /** 程序的实例列表,用于持有引用 */ private static final Set<TpncLib> INSTANCES = Collections.synchronizedSet(new HashSet<>()); static { DEFAULT_PROPERTIES.put(TpncLibProperty.NC_LIBRARY_PATH, "library/"); } // --------------------------------------------模型-------------------------------------------- // 并发后台 private final Background concurrentBackground = new ExecutorServiceBackground( Executors.newFixedThreadPool(4, ExecutorServiceBackground.THREAD_FACTORY), Collections.newSetFromMap(new WeakHashMap<>())); private final Background queueBackground = new ExecutorServiceBackground( Executors.newSingleThreadExecutor(ExecutorServiceBackground.THREAD_FACTORY), Collections.newSetFromMap(new WeakHashMap<>())); // 资源处理器 private final SyncResourceHandler resourceHandler = ResourceUtil.syncResourceHandler(new DelegateResourceHandler()); // 核心配置模型 private final SyncExconfigModel coreConfigModel = ConfigUtil .syncExconfigModel(new DefaultExconfigModel(Arrays.asList(CoreConfiguration.values()))); // 模态配置模型 private final SyncExconfigModel modalConfigModel = ConfigUtil .syncExconfigModel(new DefaultExconfigModel(Arrays.asList(ModalConfiguration.values()))); // 标签国际化处理器 private final SyncI18nHandler labelI18nHandler = I18nUtil.syncI18nHandler(new DelegateI18nHandler()); // 记录器国际化处理器 private final SyncI18nHandler loggerI18nHandler = I18nUtil.syncI18nHandler(new DelegateI18nHandler()); // 记录器接口 private final SyncLoggerHandler loggerHandler = ModelUtil.syncLoggerHandler(new DelegateLoggerHandler()); // 试件类型列表 private final SyncListModel<PieceCata> pieceCataModel = com.dwarfeng.dutil.basic.cna.model.ModelUtil .syncListModel(new DelegateListModel<>()); // 锚点试件类型 private final SyncReferenceModel<PieceCata> anchorPieceCataModel = com.dwarfeng.dutil.basic.cna.model.ModelUtil .syncReferenceModel(new DefaultReferenceModel<>()); // 指导条目列表模型 private final SyncListModel<Name> instrItemModel = com.dwarfeng.dutil.basic.cna.model.ModelUtil .syncListModel(new DelegateListModel<>()); // 锚点指导条目模型 private final SyncReferenceModel<Name> anchorInstructionItemModel = com.dwarfeng.dutil.basic.cna.model.ModelUtil .syncReferenceModel(new DefaultReferenceModel<>()); // 指导文档模型 private final SyncReferenceModel<StyledDocument> instrDocModel = com.dwarfeng.dutil.basic.cna.model.ModelUtil .syncReferenceModel(new DefaultReferenceModel<>()); // 库类加载器 private final PluginClassLoader libraryClassLoader = new DefaultPluginClassLoader(new URL[0], DefaultPluginClassLoader.class.getClassLoader()); // --------------------------------------------控制-------------------------------------------- /** 程序的侦听器集合 */ private final Set<ProgramObverser> programObversers = Collections.newSetFromMap(new WeakHashMap<>()); /** 程序的属性集合。 */ private final Map<String, String> properties = new HashMap<>(); /** 启动标志 */ private boolean startFlag = false; /** 启动标志同步锁 */ private final Object startFlagLock = new Object(); /** 释放标志 */ private boolean disposeFlag = false; /** 释放标识同步锁 */ private final Object disposeFlagLock = new Object(); /** 程序的状态 */ private RuntimeState runtimeState; /** 程序的状态的同步锁 */ private final Object runtimeStateLock = new Object(); /** 程序的退出代码 */ private int exitCode = Integer.MIN_VALUE; /** 程序的退出代码的同步锁 */ private final Object exitCodeLock = new Object(); /** 程序的工具包 */ private final Toolkit toolkit = new TpncLibToolkit(); /** 程序的启动-退出同步锁 */ private final Object startExitLock = new Object(); // --------------------------------------------视图-------------------------------------------- // 界面管理器。 private final GuiManager guiManager = new TpncLibGuiManager(); // 主界面。 private MainFrame mainFrame; private final Object mainFrameLock = new Object(); // --------------------------------------------观察器-------------------------------------------- /** 配置观察器。 */ private final ExconfigObverser coreConfigObverser = new CoreConfigObverserImpl(this); /** 后台模型侦听器 */ private final BackgroundObverser backgroundObverser = new BackgroundObverserImpl(this); /** * 新实例。 */ public TpncLib() { this(new String[0]); } /** * 新实例。 * * @param args * 参数名称与值。 * @throws NullPointerException * 入口参数为 <code>null</code>。 * @throws IllegalArgumentException * 参数<code>args</code> 不合法。 */ public TpncLib(String... args) { Objects.requireNonNull(args, "入口参数 args 不能为 null。"); // 加载系统参数 for (String string : args) { StringTokenizer st = new StringTokenizer(string, "="); String key; String value; try { key = st.nextToken(); value = st.nextToken(); } catch (NoSuchElementException e) { throw new IllegalArgumentException("非法的参数:" + string); } if (!DEFAULT_PROPERTIES.containsKey(key)) { throw new IllegalArgumentException("不存在的键:" + key); } properties.put(key, value); } // 为自己保留引用。 INSTANCES.add(this); } /** * 获取NoteWizard中的工具包。 * * @return NoteWizard中的工具包。 */ public Toolkit getToolkit() { return toolkit; } private void fireRuntimeStateChanged(RuntimeState oldState, RuntimeState newState) { for (ProgramObverser obverser : programObversers) { if (Objects.nonNull(obverser)) try { obverser.fireRuntimeStateChanged(oldState, newState); } catch (Exception e) { e.printStackTrace(); } } } }
28.925581
118
0.696133
5e1dc5bd289c3f3dd4f294685fdc126fde10da14
1,805
package view.buttons; import units.Status; import view.labels.ArmyInfoLabel; import javax.swing.*; import java.awt.*; public class ArmyButton extends CustomToggleButton { private Status status; private String cityName; private ImageIcon image; private final ArmyInfoLabel armyInfoLabel; public ArmyButton(int armyNumber, Status status, String cityName, int numberOfSoldiers) { JLabel pictureLabel = new JLabel(); this.status = status; this.cityName = cityName; this.armyInfoLabel = new ArmyInfoLabel(armyNumber, status, cityName, numberOfSoldiers); this.setBackground(Color.DARK_GRAY); this.setVisible(true); this.setPreferredSize(new Dimension(325, 135)); this.setLayout(new GridLayout(1, 2)); switch (cityName.toLowerCase()) { case "cairo": image = new ImageIcon("resources/images/CairoEditedKo2.jpg"); break; case "sparta": image = new ImageIcon("resources/images/SpartanKo2.jpg"); break; case "rome": image = new ImageIcon("resources/images/RomeEditedlko2.jpg"); break; } pictureLabel.setIcon(image); pictureLabel.setPreferredSize(new Dimension(200, 135)); pictureLabel.setVisible(true); this.add(pictureLabel); this.add(armyInfoLabel); } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public ArmyInfoLabel getArmyInfoLabel() { return armyInfoLabel; } }
28.650794
95
0.628255
a77dc8fd2d14defe83d5213993272ded18e76d19
7,065
/* * Copyright (C) 2005-2020 Gregory Hedlund & Yvan Rose * * 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 ca.phon.alignment; import java.util.*; /** * Represents alignments between two arrays of similar objects. * * */ public class AlignmentMap<T> { /** The value for an indel */ public static final int INDEL_VALUE = -1; /** The value for a spacer */ public static final int SPACER_VALUE = -2; /** The 'top' list of elements to align */ protected T[] topElements; /** The 'bottom' list of elements to align */ protected T[] bottomElements; /** The 'top' alignment values */ protected Integer[] topAlignment; /** The 'bottom' alignment values */ protected Integer[] bottomAlignment; /** Constructor */ public AlignmentMap() { super(); this.topAlignment = null; this.bottomAlignment = null; this.topAlignment = new Integer[0]; this.bottomAlignment = new Integer[0]; } /** Get the value of the bottom alignment */ public Integer[] getBottomAlignment() { return bottomAlignment; } /** Set the bottom alignment */ public void setBottomAlignment(Integer[] bottomAlignment) { this.bottomAlignment = bottomAlignment; } /** Get the bottom elements */ public T[] getBottomElements() { return bottomElements; } /** Set the bottom elements */ public void setBottomElements(T[] bottomElements) { this.bottomElements = bottomElements; } /** Get the top alignment */ public Integer[] getTopAlignment() { return topAlignment; } /** Set the top alignment */ public void setTopAlignment(Integer[] topAlignment) { this.topAlignment = topAlignment; } /** Get the top elements */ public T[] getTopElements() { return topElements; } /** Set the top elements */ public void setTopElements(T[] topElements) { this.topElements = topElements; } public List<T> getAligned(T[] eles) { return getAligned(Arrays.asList(eles)); } /** * Return the list of object that are aligned * with the given iterable list of object. * * @param eles * @return aligned lements */ public List<T> getAligned(Iterable<T> iterable) { final Iterator<T> itr = iterable.iterator(); final List<T> list = new ArrayList<T>(); while(itr.hasNext()) list.add(itr.next()); return getAligned(list); } /** * Return the list of objects that are aligned * with the given list of objects. * * This method does <b>not</b> return * <code>null</code> values for indel/spacers. * * @param eles * @return aligned elements */ public List<T> getAligned(List<T> eles) { final List<T> retVal = new ArrayList<T>(); if(eles.size() == 0) return retVal; final List<T> topElements = getTopAlignmentElements(); final List<T> btmElements = getBottomAlignmentElements(); final boolean isTop = topElements.containsAll(eles); final int startIdx = (isTop ? topElements.indexOf(eles.get(0)) : btmElements.indexOf(eles.get(0))); final int endIdx = (isTop ? topElements.indexOf(eles.get(eles.size()-1)) : btmElements.indexOf(eles.get(eles.size()-1))); if(startIdx < 0 || endIdx < 0) return retVal; for(int i = startIdx; i <= endIdx; i++) { final T ele = (isTop ? btmElements.get(i) : topElements.get(i)); if(ele != null) retVal.add((T)ele); } return retVal; } /** * Get the element aligned with the given element. * * @param ele * * @return element (if present) */ public Optional<T> getAlignedElement(T ele) { final List<T> eleList = Collections.singletonList(ele); final List<T> alignedEles = getAligned(eleList); if(alignedEles.size() > 0) { return Optional.of(alignedEles.get(0)); } else { return Optional.empty(); } } /** Get the top alignment as an array of elements */ public List<T> getTopAlignmentElements() { // if(this.topAlignment == null) // return null; List<T> retVal = new ArrayList<T>(); // if(topElements.length == 0) return null; // ArrayList<T> retVal = new ArrayList<T>(); // T[] retVal = (T[])Array.newInstance( // topElements[0].getClass(), topAlignment.length); for(int i = 0; i < topAlignment.length; i++) { if(topAlignment[i] == INDEL_VALUE || topAlignment[i] == SPACER_VALUE) { retVal.add(null); } else { int eleIdx = topAlignment[i]; if(eleIdx >= 0 && eleIdx < topElements.length) retVal.add(topElements[topAlignment[i]]); else retVal.add(null); } } return retVal; } /** Get the bottom alignment as an array of elements */ public List<T> getBottomAlignmentElements() { // if(this.bottomAlignment == null) // return null; // if(bottomElements.length == 0) return null; ArrayList<T> retVal = new ArrayList<T>(); // T[] retVal = (T[]) Array.newInstance( // bottomElements[0].getClass(), bottomAlignment.length); for(int i = 0; i < bottomAlignment.length; i++) { if( (bottomAlignment[i] == INDEL_VALUE || bottomAlignment[i] == SPACER_VALUE) || bottomAlignment[i] >= bottomElements.length ) { retVal.add(null); } else { retVal.add(bottomElements[bottomAlignment[i]]); } } return retVal; } /** * Returns the length of the alignment. * * @return int */ public int getAlignmentLength() { if(this.topAlignment == null) return 0; return this.topAlignment.length; } /** * Returns the set of aligned elements at the * given alignment position. * * @param alignmentIndex * @return T[0] the top alignment element, T[1] the bottom alignment element */ public List<T> getAlignedElements(int alignmentIndex) { if(alignmentIndex < 0 || alignmentIndex >= getAlignmentLength()) throw new ArrayIndexOutOfBoundsException(); Integer topValue = topAlignment[alignmentIndex]; Integer bottomValue = bottomAlignment[alignmentIndex]; List<T> retVal = new ArrayList<T>(); // Class theClass = null; // if(topElements.length > 0 && topElements[0] != null) { // theClass = topElements[0].getClass(); // } else if (bottomElements.length > 0 && bottomElements[0] != null) { // theClass = bottomElements[0].getClass(); // } // // if(theClass == null) theClass = Object.class; // // T[] retVal = (T[]) Array.newInstance( // theClass, 2); if(topValue >= topElements.length) // retVal[0] = null; retVal.add(null); else retVal.add( (topValue == INDEL_VALUE ? null : topElements[topValue])); if(bottomValue >= bottomElements.length) retVal.add(null); else retVal.add( (bottomValue == INDEL_VALUE ? null : bottomElements[bottomValue])); return retVal; } }
26.36194
123
0.6661
09e520a68acc6144d5e4b28f37ea8c8bedc27699
1,325
/** * Copyright (c) 2014, by the Authors: Antonio Sanchez (UBC) * * This software is freely available under a 2-clause BSD license. Please see * the LICENSE file in the ArtiSynth distribution directory for details. */ package artisynth.core.mfreemodels; import maspack.render.RenderProps; import artisynth.core.modelbase.RenderableComponentList; import artisynth.core.util.ScalableUnits; public class MFreeMuscleBundleList extends RenderableComponentList<MFreeMuscleBundle> implements ScalableUnits { protected static final long serialVersionUID = 1; public MFreeMuscleBundleList () { this (null, null); } public MFreeMuscleBundleList (String name, String shortName) { super (MFreeMuscleBundle.class, name, shortName); setRenderProps (createRenderProps()); } public boolean hasParameterizedType() { return false; } public RenderProps createRenderProps() { return RenderProps.createLineProps (this); } public void scaleDistance (double s) { for (int i = 0; i < size(); i++) { get (i).scaleDistance (s); } if (myRenderProps != null) { myRenderProps.scaleDistance (s); } } public void scaleMass (double s) { for (int i = 0; i < size(); i++) { get (i).scaleMass (s); } } }
25.980392
80
0.673208
af347c0ad31545524ed13a6dc98966f5a6c18d85
5,603
package com.centurylink.mdw.service.data.process; import com.centurylink.mdw.dataaccess.DataAccessException; import com.centurylink.mdw.dataaccess.DatabaseAccess; import com.centurylink.mdw.dataaccess.DocumentDbAccess; import com.centurylink.mdw.model.event.EventInstance; import com.centurylink.mdw.model.event.EventWaitInstance; import com.centurylink.mdw.model.variable.Document; import com.centurylink.mdw.model.variable.VariableInstance; import com.centurylink.mdw.model.workflow.Package; import com.centurylink.mdw.model.workflow.*; import com.centurylink.mdw.util.TransactionWrapper; import java.sql.SQLException; import java.util.Date; import java.util.List; public interface EngineDataAccess { Long createProcessInstance(ProcessInstance procinst) throws DataAccessException,SQLException; void setProcessCompletionTime(ProcessInstance pi) throws SQLException; void setActivityCompletionTime(ActivityInstance ai) throws SQLException; ProcessInstance getProcessInstance(Long procInstId) throws DataAccessException,SQLException; void setProcessInstanceStatus(Long procInstId, Integer status) throws DataAccessException,SQLException; void setProcessInstanceStartTime(Long processInstanceId) throws SQLException; void setProcessInstanceCompletionCode(Long procInstId, String completionCode) throws SQLException; List<ProcessInstance> getProcessInstances(Long procId, String ownerType, Long ownerId) throws SQLException; List<ProcessInstance> getChildProcessInstances(Long procInstId) throws SQLException; Integer lockProcessInstance(Long procInstId) throws SQLException; List<ProcessInstance> getProcessInstancesByMasterRequestId(String masterRequestId) throws SQLException; ActivityInstance getActivityInstance(Long actInstId) throws DataAccessException,SQLException; Long createActivityInstance(ActivityInstance act) throws DataAccessException,SQLException; void setActivityInstanceStatus(ActivityInstance actInst, Integer status, String status_message) throws DataAccessException,SQLException; List<ActivityInstance> getActivityInstances(Long actId, Long procInstId, boolean activeOnly, boolean isSynchActivity) throws SQLException; void updateActivityInstanceEndTime(Long actInstId, Date endtime) throws SQLException; int countActivityInstances(Long procInstId, Long activityId) throws SQLException; Integer lockActivityInstance(Long actInstId) throws SQLException; Long createTransitionInstance(TransitionInstance vo) throws DataAccessException,SQLException; void completeTransitionInstance(Long transInstId, Long actInstId) throws DataAccessException,SQLException; void cancelTransitionInstances(Long procInstId, String comment, Long transId) throws SQLException; int countTransitionInstances(Long pProcInstId, Long pWorkTransId) throws SQLException; void determineCompletedTransitions(Long pProcInstId, List<Transition> transitions) throws SQLException; Long createVariableInstance(VariableInstance var, Long processInstId, Package pkg) throws DataAccessException,SQLException; VariableInstance getVariableInstance(Long varInstId) throws DataAccessException,SQLException; VariableInstance getVariableInstance(Long procInstId, String varname) throws SQLException; void updateVariableInstance(VariableInstance var, Package pkg) throws DataAccessException,SQLException; List<VariableInstance> getProcessInstanceVariables(Long processInstanceId) throws DataAccessException,SQLException; /** * Always goes to the database. */ Document loadDocument(Long documentId, boolean forUpdate) throws DataAccessException, SQLException; Document getDocument(Long documentId, boolean forUpdate) throws DataAccessException, SQLException; Long createDocument(Document doc, Package pkg) throws DataAccessException, SQLException; void updateDocumentContent(Long documentId, String content) throws DataAccessException, SQLException; void updateDocumentInfo(Document doc) throws SQLException; Long getRequestCompletionTime(String ownerType, Long ownerId) throws SQLException; void setElapsedTime(String ownerType, Long instanceId, Long elapsedTime) throws SQLException; void removeEventWaitForActivityInstance(Long activityInstanceId, String reason) throws SQLException; void removeEventWaitForProcessInstance(Long processInstanceId) throws SQLException; Long recordEventWait(String eventName, boolean multipleRecepients, int preserveSeconds, Long actInstId, String compCode) throws SQLException; List<EventWaitInstance> recordEventArrive(String eventName, Long documentId) throws SQLException; Long recordEventLog(String name, String category, String subCategory, String source, String ownerType, Long ownerId, String user, String modUser, String comments) throws SQLException; void persistInternalEvent(String eventId, String message) throws SQLException; int deleteEventInstance(String eventName) throws SQLException; EventInstance lockEventInstance(String eventName) throws SQLException; TransactionWrapper startTransaction() throws DataAccessException; void stopTransaction(TransactionWrapper transaction) throws DataAccessException; DatabaseAccess getDatabaseAccess(); DocumentDbAccess getDocumentDbAccess(); int getPerformanceLevel(); }
33.753012
104
0.798679
193d71f4be034ef5e1a45caecec5541dc7ff3516
2,098
package com.example.demo.controller; import java.util.List; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demo.model.Ticket; import com.example.demo.repository.Repository; import com.example.demo.services.TicketService; @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api") public class TicketController { private static final Logger logger = LogManager.getLogger(TicketController.class.getName()); @Autowired private TicketService service; @Autowired Repository repository; @GetMapping("/Alltickets") public List<Ticket> getTickets(){ logger.info("Recieved Get All Tickets Request"); return service.getTickets(); } @PutMapping("/tutorials/{id}") public ResponseEntity<Ticket> updateTutorial(@PathVariable("id") Integer id, @RequestBody Ticket riembursement) { Optional<Ticket> tutorialData = repository.findById(id); if (tutorialData.isPresent()) { Ticket newobj = tutorialData.get(); newobj.setAmount(riembursement.getAmount()); newobj.setDescription(riembursement.getDescription()); newobj.setType(riembursement.getType()); newobj.setId(riembursement.getId()); newobj.setStatus(riembursement.getStatus()); newobj.setEmpId(riembursement.getEmpId()); newobj.setTime(riembursement.getTime()); return new ResponseEntity<>(repository.save(newobj), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } }
31.787879
114
0.791706
5c79f5fff2dee3b93c864bed911839ba7f5f8a73
693
package com.atusoft.infrastructure; import java.time.LocalDateTime; import com.atusoft.util.Util; import lombok.Data; @Data public class BaseEvent { String eventId=Util.getUUID(); LocalDateTime timestamp=LocalDateTime.now(); protected String businessId; // from client protected String causeEventId; //event who cause current event. protected String sourceId; //current event resource id String _token; //end user protected BaseEvent() { } protected BaseEvent(BaseDTO dto) { if (dto!=null) this._token=dto.get_token(); } protected BaseEvent(BaseEvent event) { if (event!=null) { this._token=event.get_token(); this.causeEventId=event.getEventId(); } } }
20.382353
64
0.735931
8cb8382885f4e41b0a98e2c72b4b38e7faa6489b
6,099
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package com.gemstone.gemfire.management.internal.web.controllers; import com.gemstone.gemfire.internal.lang.StringUtils; import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings; import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * The FunctionCommandsController class implements GemFire Management REST API web service endpoints for the * Gfsh Function Commands. * <p/> * @author John Blum * @see com.gemstone.gemfire.management.internal.cli.commands.FunctionCommands * @see com.gemstone.gemfire.management.internal.web.controllers.AbstractCommandsController * @see org.springframework.stereotype.Controller * @see org.springframework.web.bind.annotation.PathVariable * @see org.springframework.web.bind.annotation.RequestMapping * @see org.springframework.web.bind.annotation.RequestMethod * @see org.springframework.web.bind.annotation.RequestParam * @see org.springframework.web.bind.annotation.ResponseBody * @since 7.5 */ @Controller("functionController") @RequestMapping("/v1") @SuppressWarnings("unused") public class FunctionCommandsController extends AbstractCommandsController { @RequestMapping(value = "/functions", method = RequestMethod.GET) @ResponseBody public String listFunctions(@RequestParam(value = CliStrings.LIST_FUNCTION__GROUP, required = false) final String[] groups, @RequestParam(value = CliStrings.LIST_FUNCTION__MEMBER, required = false) final String[] members, @RequestParam(value = CliStrings.LIST_FUNCTION__MATCHES, required = false) final String matches) { final CommandStringBuilder command = new CommandStringBuilder(CliStrings.LIST_FUNCTION); if (hasValue(groups)) { command.addOption(CliStrings.LIST_FUNCTION__GROUP, StringUtils.concat(groups, StringUtils.COMMA_DELIMITER)); } if (hasValue(members)) { command.addOption(CliStrings.LIST_FUNCTION__MEMBER, StringUtils.concat(members, StringUtils.COMMA_DELIMITER)); } if (hasValue(matches)) { command.addOption(CliStrings.LIST_FUNCTION__MATCHES, matches); } return processCommand(command.toString()); } // TODO add Async functionality @RequestMapping(value = "/functions/{id}", method = RequestMethod.POST) @ResponseBody public String executeFunction(@PathVariable("id") final String functionId, @RequestParam(value = CliStrings.EXECUTE_FUNCTION__ONGROUP, required = false) final String groupName, @RequestParam(value = CliStrings.EXECUTE_FUNCTION__ONMEMBER, required = false) final String memberNameId, @RequestParam(value = CliStrings.EXECUTE_FUNCTION__ONREGION, required = false) final String regionNamePath, @RequestParam(value = CliStrings.EXECUTE_FUNCTION__ARGUMENTS, required = false) final String[] arguments, @RequestParam(value = CliStrings.EXECUTE_FUNCTION__FILTER, required = false) final String filter, @RequestParam(value = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR, required = false) final String resultCollector) { final CommandStringBuilder command = new CommandStringBuilder(CliStrings.EXECUTE_FUNCTION); command.addOption(CliStrings.EXECUTE_FUNCTION__ID, functionId); if (hasValue(groupName)) { command.addOption(CliStrings.EXECUTE_FUNCTION__ONGROUP, groupName); } if (hasValue(memberNameId)) { command.addOption(CliStrings.EXECUTE_FUNCTION__ONMEMBER, memberNameId); } if (hasValue(regionNamePath)) { command.addOption(CliStrings.EXECUTE_FUNCTION__ONREGION, regionNamePath); } if (hasValue(arguments)) { command.addOption(CliStrings.EXECUTE_FUNCTION__ARGUMENTS, StringUtils.concat(arguments, StringUtils.COMMA_DELIMITER)); } if (hasValue(filter)) { command.addOption(CliStrings.EXECUTE_FUNCTION__FILTER, filter); } if (hasValue(resultCollector)) { command.addOption(CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR, resultCollector); } return processCommand(command.toString()); } @RequestMapping(value = "/functions/{id}", method = RequestMethod.DELETE) @ResponseBody public String destroyFunction(@PathVariable("id") final String functionId, @RequestParam(value = CliStrings.DESTROY_FUNCTION__ONGROUP, required = false) final String groupName, @RequestParam(value = CliStrings.DESTROY_FUNCTION__ONMEMBER, required = false) final String memberNameId) { final CommandStringBuilder command = new CommandStringBuilder(CliStrings.DESTROY_FUNCTION); command.addOption(CliStrings.DESTROY_FUNCTION__ID, functionId); if (hasValue(groupName)) { command.addOption(CliStrings.DESTROY_FUNCTION__ONGROUP, groupName); } if (hasValue(memberNameId)) { command.addOption(CliStrings.DESTROY_FUNCTION__ONMEMBER, memberNameId); } return processCommand(command.toString()); } }
44.518248
147
0.742417
0f03719d1f04821185bd4d79a0ed3ac9101d97ef
2,285
package com.zm.json; import java.util.HashMap; import java.util.Map; import java.util.Stack; /** * Created by Administrator on 2017/3/15. */ public class JsonAnalysis { public static void main(String[] args){ String json = "{aa:11,bb:{cc:{dd:22}},ee:{ff:'33',gg:44}}"; if (json.length() - json.replace("{","").length() != json.length() - json.replace("}","").length()){ throw new IllegalStateException("expression is error."); } Stack stack = new Stack(); // Map result = new HashMap<>(); analysis(stack, json); // System.out.println(":".equals(":")); System.out.println(stack); // System.out.println(stackParam.pop()); } public static void analysis(Stack stack, String jsonString){ for (int i = 0; i < jsonString.length(); i++) { if(jsonString.charAt(i) == '}'){ doWithBrackets(stack); }else if (jsonString.charAt(i) == ',') { doWithBrackets(stack); stack.push(','); }else { stack.push(jsonString.charAt(i)); } } } public static void doWithBrackets(Stack stack){ StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); Map mapValue = new HashMap<>(); boolean isKey = false; while (stack.size()>0){ Object item = stack.pop(); boolean isMap = false; if (item instanceof Map){ isMap = true; }else { item = item.toString(); } if (!isKey && !item.equals(":")){ if (isMap){ mapValue.putAll((Map) item); }else { value.insert(0,item); } }else { if (!isKey){ isKey = true; continue; } if ( !item.equals("{") && !item.equals(",")){ key.insert(0,item); }else { break; } } } Map map = new HashMap<>(); map.put(key,value.length()==0 ? mapValue : value); stack.push(map); } }
27.53012
108
0.461269
2d05f6d6a7a27d0d7be1ed119f9faf73a1090422
3,939
package nl.tudelft.jpacman.level.specialpellet; import nl.tudelft.jpacman.board.Direction; import nl.tudelft.jpacman.board.Unit; import nl.tudelft.jpacman.level.Level; import nl.tudelft.jpacman.level.Player; import nl.tudelft.jpacman.npc.Ghost; import nl.tudelft.jpacman.npc.ghost.Navigation; import nl.tudelft.jpacman.sprite.PacManSprites; import nl.tudelft.jpacman.sprite.Sprite; import java.util.List; import java.util.Map; /** * A Fish pellet ({@link SpecialPellet}) is a penalty that locks pacman down still in his square, with variation * considering the current state of the level. * The duration of the non-movable state for Pacman depends on the distance of the closest Ghost. There is a base time * anyway, so sometimes Pacman will be fated to die but that's his fault, don't eat Nemo Pacman ! The closer a ghost * is, the less time he will be trapped though. * * @author Rémy Decocq */ public class FishPellet extends SpecialPellet { /** * Considered ghosts distance */ public static final int GHOST_DIST_THRESH = 12; /** * Basic time for the penalty */ public static final long BASIC_DURATION = 1000L; /** * Increased time when effect is stronger */ public static final long INCREASED_DURATION = 3000L; /** * The oriented sprites to modify Pacman skin during effect */ private static final Map<Direction, Sprite> pacmanSprites = new PacManSprites().getPacmanFishSprites(); /** * Creates a new pellet. * * @param points The point value of this pellet. * @param sprite The sprite of this pellet. */ public FishPellet(int points, Sprite sprite) { super(points, sprite); } /** * Compute effect duration based on the closes ghost distance, using a complying formula when he's less than * {@link #GHOST_DIST_THRESH} away. * @param player the pacman. * @return the duration effect in milliseconds. */ private long getDuration(Player player){ Unit nearestGhost = Navigation.findNearest(Ghost.class, player.getSquare()); if (nearestGhost == null) return BASIC_DURATION; List<Direction> path = Navigation.shortestPath(nearestGhost.getSquare(), player.getSquare(), nearestGhost); if (path == null) return BASIC_DURATION; int ghostDist = path.size(); if (ghostDist > GHOST_DIST_THRESH) return INCREASED_DURATION; // A ghost is close, let's evaluate a approximately fair duration (ghostDist <= THRESH), the closer the ghost is // the shorter the duration should be long durationDiff = INCREASED_DURATION - BASIC_DURATION; return BASIC_DURATION + (durationDiff / (1 + (GHOST_DIST_THRESH - ghostDist))); } /** * Called when this pellet is eaten by a Player (pacman) * @param level the current level * @param player who eat this pellet */ @Override public void onEat(Level level, Player player){ super.onEat(level, player); long duration = this.getDuration(player); player.setMovable(false); setNewStatePlayer(player, Player.SpecialStates.ON_FISH, pacmanSprites); scheduleEffectDuration(new StopFishEffect(player), duration); } private class StopFishEffect extends StopEffect{ /** * @param player the Pacman on which the effect has been activated. */ public StopFishEffect(Player player) { super(player); } /** * Reset the player special state (to {@link Player.SpecialStates#NONE}) and Pacman's sprites he * used at instantiation. The reset operated by superclass does not enable * resetting {@link Unit#isMovable()} so it is overloaded here. */ @Override public void run() { super.run(); player.setMovable(true); } } }
34.552632
120
0.667428
4f3018038ef6a47b7f8876e4181aac11ece2df49
5,899
package ro.pub.cs.systems.eim.lab04.contactsmanager; import java.util.ArrayList; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.os.Bundle; import android.provider.ContactsContract; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; public class ContactsManagerActivity extends Activity { private Button showHideButton = null; private EditText nameText = null; private EditText phoneText = null; private EditText emailText = null; private EditText addressText = null; private Button saveButton = null; private Button cancelButton = null; private EditText jobText = null; private EditText companyText = null; private EditText websiteText = null; private EditText imText = null; private LinearLayout container2 = null; private ShowHideButtonListener showHideButtonListener = new ShowHideButtonListener(); private SaveButtonListener saveButtonListener = new SaveButtonListener(); private CancelButtonListener cancelButtonListener = new CancelButtonListener(); private class ShowHideButtonListener implements View.OnClickListener { @Override public void onClick(View view) { if (container2.getVisibility() == View.VISIBLE) { container2.setVisibility(View.INVISIBLE); showHideButton.setText(getResources().getString(R.string.show_info)); } else if (container2.getVisibility() == View.INVISIBLE) { container2.setVisibility(View.VISIBLE); showHideButton.setText(getResources().getString(R.string.hide_info)); } } } private class SaveButtonListener implements View.OnClickListener { @Override public void onClick(View view) { Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION); intent.setType(ContactsContract.RawContacts.CONTENT_TYPE); String name = nameText.getText().toString(); String phone = phoneText.getText().toString(); String email = emailText.getText().toString(); String address = addressText.getText().toString(); String jobTitle = jobText.getText().toString(); String company = companyText.getText().toString(); String website = websiteText.getText().toString(); String im = imText.getText().toString(); if (name != null) { intent.putExtra(ContactsContract.Intents.Insert.NAME, name); } if (phone != null) { intent.putExtra(ContactsContract.Intents.Insert.PHONE, phone); } if (email != null) { intent.putExtra(ContactsContract.Intents.Insert.EMAIL, email); } if (address != null) { intent.putExtra(ContactsContract.Intents.Insert.POSTAL, address); } if (jobTitle != null) { intent.putExtra(ContactsContract.Intents.Insert.JOB_TITLE, jobTitle); } if (company != null) { intent.putExtra(ContactsContract.Intents.Insert.COMPANY, company); } ArrayList<ContentValues> contactData = new ArrayList<ContentValues>(); if (website != null) { ContentValues websiteRow = new ContentValues(); websiteRow.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE); websiteRow.put(ContactsContract.CommonDataKinds.Website.URL, website); contactData.add(websiteRow); } if (im != null) { ContentValues imRow = new ContentValues(); imRow.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE); imRow.put(ContactsContract.CommonDataKinds.Im.DATA, im); contactData.add(imRow); } intent.putParcelableArrayListExtra(ContactsContract.Intents.Insert.DATA, contactData); startActivityForResult(intent, Constants.CONTACTS_MANAGER_REQUEST_CODE); } } private class CancelButtonListener implements View.OnClickListener { @Override public void onClick(View view) { setResult(Activity.RESULT_CANCELED, new Intent()); finish(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contacts_manager); showHideButton = (Button)findViewById(R.id.show_hide); showHideButton.setOnClickListener(showHideButtonListener); saveButton = (Button)findViewById(R.id.save); saveButton.setOnClickListener(saveButtonListener); cancelButton = (Button)findViewById(R.id.cancel); cancelButton.setOnClickListener(cancelButtonListener); container2 = (LinearLayout)findViewById(R.id.container2); nameText = (EditText)findViewById(R.id.name); phoneText = (EditText)findViewById(R.id.phone); emailText = (EditText)findViewById(R.id.email); addressText = (EditText)findViewById(R.id.address); jobText = (EditText)findViewById(R.id.job); companyText = (EditText)findViewById(R.id.company); websiteText = (EditText)findViewById(R.id.website); imText = (EditText)findViewById(R.id.im); Intent intent = getIntent(); if (intent != null) { String phone = intent.getStringExtra("ro.pub.cs.systems.eim.lab04.contactsmanager.PHONE_NUMBER_KEY"); if (phone != null) { phoneText.setText(phone); } else { Toast.makeText(this, getResources().getString(R.string.phone_number_error), Toast.LENGTH_LONG).show(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.contacts_manager, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
35.969512
112
0.748771
c016ec2d4b97257b1003336af96c8088633282db
396
package com.example.demo.cipher.keypair.service; import java.security.KeyPair; import java.security.PrivateKey; import java.security.PublicKey; import com.example.demo._domain.KeyPairPEM; public interface IKeyPairGeneratorProvider { KeyPair generateKeyPair(); KeyPairPEM generateKeyPairPEM(PublicKey publicKey, PrivateKey privateKey); PrivateKey buildPrivateKey(String privateKeyPEM); }
23.294118
75
0.833333
216d5fc5dbf651ae1b5fe0e66d4c77927df34356
1,115
package ddd; import ddd.application.service.pedidocasamento.PedidoCasamentoService; import ddd.domain.pedidocasamento.command.PedidoCasamentoCriarCommand; import ddd.domain.pedidocasamento.command.PedidoCasamentoMarcarEmAndamentoCommand; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.Assert; import java.util.UUID; @RunWith(SpringRunner.class) @SpringBootTest public class DddApplicationTests { @Autowired private PedidoCasamentoService pedidoCasamentoService; @Test public void criarPedidoCasamento() { UUID usuarioId = UUID.randomUUID(); UUID pedidoUUID = pedidoCasamentoService.criarNovoPedido(new PedidoCasamentoCriarCommand(usuarioId, "noivo", "noiva")); Assert.notNull("uuid", "uuid esta nulo"); pedidoCasamentoService.marcarComoEmAndamento(new PedidoCasamentoMarcarEmAndamentoCommand(usuarioId,pedidoUUID)); Assert.notNull("uuid", "uuid esta nulo"); } }
29.342105
121
0.827803
6cda1ee5b27137b7fa0075196fc44df97310e716
1,663
package common.toolkit.java.util; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Description:一个统计程序,用于统计压力测试时候的TPS计算 * * @author 银时 yinshi.nc@taobao.com */ public class StatisticsUtil { private static Log log = LogFactory.getLog( "commonStat" ); public static boolean NEED_STAT = false; public static int SECOND_OF_STAT_DELAY = 10; // 上次统计时间(这个值是通过 System.currentTimeMillis() 获取) public static long lastedTime = System.currentTimeMillis(); // 上次统计之后累计执行的次数 public static AtomicLong totalTransactions = new AtomicLong(); /** * 开始统计 */ public static void start( int secondOfStatDelay ) { SECOND_OF_STAT_DELAY = secondOfStatDelay; StatisticsUtil.NEED_STAT = true; ThreadUtil.startThread( new Runnable() { @Override public void run() { while ( StatisticsUtil.NEED_STAT ) { try { Thread.sleep( SECOND_OF_STAT_DELAY * 1000 ); } catch ( InterruptedException e ) { // TODO Auto-generated catch block e.printStackTrace(); } log.warn( ( StatisticsUtil.totalTransactions.get() * 1.0 ) / ( ( System.currentTimeMillis() - StatisticsUtil.lastedTime ) / 1000 ) ); StatisticsUtil.totalTransactions.set( 0 ); StatisticsUtil.lastedTime = System.currentTimeMillis(); } } } ); } /** * 停止统计 */ public static void stop() { StatisticsUtil.NEED_STAT = false; } public static void main( String[] args ) { StatisticsUtil.start( 10 ); while ( true ) { StatisticsUtil.totalTransactions.addAndGet( 1 ); } } }
24.820896
139
0.669874
5eb5ed2f843fb4109c9e2cccf90ab34602ca4bec
2,856
package de.codingair.codingapi.player.gui.inventory.gui.simple; import de.codingair.codingapi.player.gui.inventory.gui.GUI; import de.codingair.codingapi.player.gui.inventory.gui.itembutton.ItemButton; import de.codingair.codingapi.player.gui.inventory.gui.itembutton.ItemButtonOption; import de.codingair.codingapi.server.sounds.SoundData; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; public abstract class Button extends ItemButton { private Page link; private ClickType[] linkTrigger = null; public Button(int slot, ItemStack item) { super(slot, item); } public Button(int x, int y, ItemStack item) { super(x, y, item); } @Override public void onClick(InventoryClickEvent e) { onClick(e, (Player) e.getWhoClicked()); if(linkTrigger == null) proceed(e); else { for(ClickType clickType : linkTrigger) { if(clickType == e.getClick()) { proceed(e); break; } } } } private void proceed(InventoryClickEvent e) { if(this.link != null) getGUI().changePage(this.link); } public abstract void onClick(InventoryClickEvent e, Player player); public Page getLink() { return link; } public void setLink(Page link) { this.link = link; } @Override public GUI getInterface() { return (GUI) super.getInterface(); } public SimpleGUI getGUI() { return (SimpleGUI) super.getInterface(); } @Override public Button setOption(ItemButtonOption option) { return (Button) super.setOption(option); } @Override public Button setMoveable(boolean movable) { return (Button) super.setMoveable(movable); } @Override public Button setClickSound(Sound clickSound) { return (Button) super.setClickSound(clickSound); } @Override public Button setClickSound2(SoundData clickSound) { return (Button) super.setClickSound2(clickSound); } @Override public Button setCloseOnClick(boolean closeOnClick) { return (Button) super.setCloseOnClick(closeOnClick); } @Override public Button setOnlyLeftClick(boolean onlyLeftClick) { return (Button) super.setOnlyLeftClick(onlyLeftClick); } @Override public Button setOnlyRightClick(boolean onlyRightClick) { return (Button) super.setOnlyRightClick(onlyRightClick); } public ClickType[] getLinkTrigger() { return linkTrigger; } public Button setLinkTrigger(ClickType... linkTrigger) { this.linkTrigger = linkTrigger; return this; } }
26.691589
83
0.660014
e8ad5dd767acb9f1d075e41282bee66c0e29edc2
3,542
package uk.gov.companieshouse.orders.api.util; import uk.gov.companieshouse.orders.api.model.TimestampedEntity; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.Is.is; /** * Test utility that verifies the timestamp fields on {@link TimestampedEntity} instances. */ public class TimestampedEntityVerifier { /** * the start of the test, prior to the invocation of the method under test */ private LocalDateTime intervalStart; /** * the end of the test, after the invocation of the method under test */ private LocalDateTime intervalEnd; /** Use to record the start of the test, rounded down to the closest millisecond, prior to the invocation of the method under test. * @return the recorded start timestamp */ public LocalDateTime start() { intervalStart = LocalDateTime.now().truncatedTo(ChronoUnit.MILLIS); return intervalStart; } /** Use to record the end of the test, rounded up to the closest millisecond, after the invocation of the method under test. * @return the recorded end timestamp */ public LocalDateTime end() { intervalEnd = LocalDateTime.now().truncatedTo(ChronoUnit.MILLIS).plusNanos(1000000); return intervalEnd; } /** * Verifies that the entity created at and updated at timestamps are within the expected interval * for the creation. * @param createdEntity the created entity */ public void verifyCreationTimestampsWithinExecutionInterval(final TimestampedEntity createdEntity) { checkIntervalRecorded(); assertThat(createdEntity.getCreatedAt().isAfter(intervalStart) || createdEntity.getCreatedAt().isEqual(intervalStart), is(true)); assertThat(createdEntity.getCreatedAt().isBefore(intervalEnd) || createdEntity.getCreatedAt().isEqual(intervalEnd), is(true)); assertThat(createdEntity.getUpdatedAt().isAfter(intervalStart) || createdEntity.getUpdatedAt().isEqual(intervalStart), is(true)); assertThat(createdEntity.getUpdatedAt().isBefore(intervalEnd) || createdEntity.getUpdatedAt().isEqual(intervalEnd), is(true)); } /** * Verifies that the updated entity updated at timestamp is within the expected interval * for the update. * @param updatedEntity the updated entity */ public void verifyUpdatedAtTimestampWithinExecutionInterval(final TimestampedEntity updatedEntity) { checkIntervalRecorded(); assertThat(updatedEntity.getUpdatedAt().isAfter(updatedEntity.getCreatedAt()) || updatedEntity.getUpdatedAt().isEqual(updatedEntity.getCreatedAt()), is(true)); assertThat(updatedEntity.getUpdatedAt().isAfter(intervalStart) || updatedEntity.getUpdatedAt().isEqual(intervalStart), is(true)); assertThat(updatedEntity.getUpdatedAt().isBefore(intervalEnd) || updatedEntity.getUpdatedAt().isEqual(intervalEnd), is(true)); } /** * Checks that the interval start and end points have been recorded correctly. */ private void checkIntervalRecorded() { assertThat("start() must already have been called at this point!", intervalStart, is(notNullValue())); assertThat("end() must already have been called at this point!", intervalEnd, is(notNullValue())); } }
40.712644
135
0.705816
6bfd3a007be7d39600b0736529bc30077bbc476b
5,532
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.metadata.pgcatalog; import com.google.common.collect.ImmutableMap; import io.crate.action.sql.SessionContext; import io.crate.analyze.WhereClause; import io.crate.execution.engine.collect.NestableCollectExpression; import io.crate.metadata.ColumnIdent; import io.crate.metadata.RelationName; import io.crate.metadata.Routing; import io.crate.metadata.RoutingProvider; import io.crate.metadata.RowGranularity; import io.crate.metadata.expressions.RowCollectExpressionFactory; import io.crate.metadata.table.ColumnRegistrar; import io.crate.metadata.table.StaticTableInfo; import io.crate.protocols.postgres.types.PGType; import io.crate.types.DataTypes; import org.elasticsearch.cluster.ClusterState; import java.util.Collections; import java.util.Map; import static io.crate.metadata.pgcatalog.OidHash.schemaOid; public class PgTypeTable extends StaticTableInfo { public static final RelationName IDENT = new RelationName(PgCatalogSchemaInfo.NAME, "pg_type"); private static final Integer TYPE_NAMESPACE_OID = schemaOid(PgCatalogSchemaInfo.NAME); static class Columns { static final ColumnIdent OID = new ColumnIdent("oid"); static final ColumnIdent TYPNAME = new ColumnIdent("typname"); static final ColumnIdent TYPDELIM = new ColumnIdent("typdelim"); static final ColumnIdent TYPELEM = new ColumnIdent("typelem"); static final ColumnIdent TYPLEN = new ColumnIdent("typlen"); static final ColumnIdent TYPTYPE = new ColumnIdent("typtype"); static final ColumnIdent TYPBASETYPE = new ColumnIdent("typbasetype"); static final ColumnIdent TYPTYPMOD = new ColumnIdent("typtypmod"); static final ColumnIdent TYPNAMESPACE = new ColumnIdent("typnamespace"); static final ColumnIdent TYPARRAY = new ColumnIdent("typarray"); } private static final String TYPTYPE = "b"; public static Map<ColumnIdent, RowCollectExpressionFactory<PGType>> expressions() { return ImmutableMap.<ColumnIdent, RowCollectExpressionFactory<PGType>>builder() .put(Columns.OID, () -> NestableCollectExpression.forFunction(PGType::oid)) .put(Columns.TYPNAME, () -> NestableCollectExpression.forFunction(PGType::typName)) .put(Columns.TYPDELIM, () -> NestableCollectExpression.forFunction(PGType::typDelim)) .put(Columns.TYPELEM, () -> NestableCollectExpression.forFunction(PGType::typElem)) .put(Columns.TYPLEN, () -> NestableCollectExpression.forFunction(PGType::typeLen)) .put(Columns.TYPTYPE, () -> NestableCollectExpression.constant(TYPTYPE)) .put(Columns.TYPBASETYPE, () -> NestableCollectExpression.constant(0)) .put(Columns.TYPTYPMOD, () -> NestableCollectExpression.constant(-1)) .put(Columns.TYPNAMESPACE, () -> NestableCollectExpression.constant(TYPE_NAMESPACE_OID)) .put(Columns.TYPARRAY, () -> NestableCollectExpression.forFunction(PGType::typArray)) .build(); } PgTypeTable() { super(IDENT, new ColumnRegistrar(IDENT, RowGranularity.DOC) .register(Columns.OID.name(), DataTypes.INTEGER) .register(Columns.TYPNAME.name(), DataTypes.STRING) .register(Columns.TYPDELIM.name(), DataTypes.STRING) .register(Columns.TYPELEM.name(), DataTypes.INTEGER) .register(Columns.TYPLEN.name(), DataTypes.SHORT) .register(Columns.TYPTYPE.name(), DataTypes.STRING) .register(Columns.TYPBASETYPE.name(), DataTypes.INTEGER) .register(Columns.TYPTYPMOD.name(), DataTypes.INTEGER) .register(Columns.TYPNAMESPACE.name(), DataTypes.INTEGER) .register(Columns.TYPARRAY.name(), DataTypes.INTEGER), Collections.emptyList()); } @Override public RowGranularity rowGranularity() { return RowGranularity.DOC; } @Override public Routing getRouting(ClusterState clusterState, RoutingProvider routingProvider, WhereClause whereClause, RoutingProvider.ShardSelection shardSelection, SessionContext sessionContext) { return Routing.forTableOnSingleNode(IDENT, clusterState.getNodes().getLocalNodeId()); } }
45.719008
99
0.690709
abb66b48c8fcb369217b4e673aa680532dce3d28
1,161
/* Copyright 2015 Software Freedom Conservancy 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.openqa.selenium.remote; import org.openqa.selenium.remote.http.HttpMethod; public class CommandInfo { private final String url; private final HttpMethod method; /** * @deprecated replaced by org.openqa.selenium.remote.CommandInfo(String, HttpMethod). */ @Deprecated public CommandInfo(String url, HttpVerb verb) { this(url, verb.toHttpMethod()); } public CommandInfo(String url, HttpMethod method) { this.url = url; this.method = method; } String getUrl() { return url; } HttpMethod getMethod() { return method; } }
25.23913
88
0.740741
023ff3878642870f6b2e23e41033edc147e61167
1,126
/* * Copyright 2019 The JIMDB 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.jimdb.meta.client; import io.jimdb.common.exception.ErrorCode; import io.jimdb.common.exception.ErrorModule; import io.jimdb.common.exception.BaseException; /** * @version V1.0 */ public final class MetaException extends BaseException { private MetaException(ErrorCode code, String message, Throwable cause) { super(ErrorModule.META, code, message, cause); } public static MetaException get(ErrorCode code, String... params) { return new MetaException(code, message(code, params), null); } }
33.117647
74
0.746004
b1c1f39df416da4f63d0c55ad5145ea61e11910c
6,325
/* * Copyright (c) 2021 Tobias Briones. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause * * This file is part of Course Project at UNAH-MM545: Distributed Text File * System. * * This source code is licensed under the BSD-3-Clause License found in the * LICENSE file in the root directory of this source tree or at * https://opensource.org/licenses/BSD-3-Clause. */ package com.github.tobiasbriones.cp.rmifilesystem.server; import com.github.tobiasbriones.cp.rmifilesystem.model.FileSystemService; import com.github.tobiasbriones.cp.rmifilesystem.model.io.Directory; import com.github.tobiasbriones.cp.rmifilesystem.model.io.File; import com.github.tobiasbriones.cp.rmifilesystem.model.io.file.Result; import com.github.tobiasbriones.cp.rmifilesystem.model.io.file.text.TextFileContent; import com.github.tobiasbriones.cp.rmifilesystem.model.io.node.DirectoryNode; import com.github.tobiasbriones.cp.rmifilesystem.model.io.node.FileNode; import com.github.tobiasbriones.cp.rmifilesystem.model.io.node.FileSystem; import com.github.tobiasbriones.cp.rmifilesystem.model.io.node.FileSystems; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.rmi.RemoteException; import java.util.Comparator; import java.util.HashMap; import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.*; /** * @author Tobias Briones */ @DisplayName("Test basic AppFileSystemService functionality") class AppFileSystemServiceTest { private static final String DIR_1_NAME = "dir1"; private static final String TEXT_FILE_1_NAME = "file1.txt"; private static final String TEXT_FILE_1_CONTENT = "This is file 1"; private static final String TEXT_FILE_2_NAME = "file2.txt"; private static final String TEXT_FILE_2_CONTENT = "And this is file 2"; private FileSystemService service; AppFileSystemServiceTest() { service = null; } @BeforeEach void setUp() throws RemoteException { service = new AppFileSystemService(); final var root = new java.io.File(AppFileSystemService.ROOT); prepareFsRoot(root); setUpDefaultFs(root); } @Test @DisplayName("Read the default file system") void readFs() throws IOException { final FileSystemService.RealTimeFileSystem rtfs = service.getRealTimeFileSystem(); final FileSystem fs = FileSystems.buildFileSystem(rtfs, new HashMap<>(0)); assertNotNull(fs, "Expects the file system to not be null"); final DirectoryNode actual = fs.getRoot(); final var root = new DirectoryNode(Directory.of()); final var dir1 = new DirectoryNode(new Directory("/" + DIR_1_NAME)); final var file11 = new FileNode(new File.TextFile("/" + DIR_1_NAME + "/" + TEXT_FILE_1_NAME)); final var file1 = new FileNode(new File.TextFile("/" + TEXT_FILE_1_NAME)); root.addChildren(dir1, file1); dir1.addChild(file11); assertTrue(actual.hasChild(dir1.commonFile())); assertTrue(actual.hasChild(file1.commonFile())); assertTrue(dir1.hasChild(file11.commonFile())); } @Test @DisplayName("Read a specific text file") void readFile() throws IOException { final var file = new File.TextFile("/" + TEXT_FILE_1_NAME); final Result<TextFileContent> contentResult = service.readTextFile(file); assertThat(contentResult instanceof Result.Success, is(true)); final TextFileContent actual = contentResult.value(); assertThat(actual.value(), is(TEXT_FILE_1_CONTENT)); } @Test @DisplayName("Create a new directory") void writeDir() throws IOException { final var dir = new Directory("/new-dir"); service.writeDirectory(dir); assertTrue( Files.exists(Path.of(AppFileSystemService.ROOT, "new-dir")), "Expects the service created the new directory" ); } @Test @DisplayName("Write to a specific text file") void writeFile() throws IOException { final var file = new File.TextFile("/" + TEXT_FILE_1_NAME); final var contentValue = "New file content"; final var content = new TextFileContent(file, contentValue); service.writeTextFile(content); final Result<TextFileContent> newContentResult = service.readTextFile(file); assertThat(newContentResult instanceof Result.Success, is(true)); final TextFileContent actual = newContentResult.value(); assertThat(actual, is(content)); } private static void prepareFsRoot(java.io.File root) { if (root.exists()) { try (var stream = Files.walk(root.toPath())) { stream.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(java.io.File::delete); } catch (IOException e) { final var msg = "Fail to delete root directory before running tests: " + e; throw new RuntimeException(msg); } } if (!root.mkdir()) { final var msg = "Fail to setup tests: Couldn't make the root directory"; throw new RuntimeException(msg); } } /** * Setup this file structure: * * - / * - /dir1 * - /file2.txt * - /file1.txt * * @param root root file for the FS */ private static void setUpDefaultFs(java.io.File root) { final var dir1 = new java.io.File(root, DIR_1_NAME); final var file1 = new java.io.File(root, TEXT_FILE_1_NAME); final var file2 = new java.io.File(dir1, TEXT_FILE_2_NAME); if (!dir1.mkdir()) { final var msg = "Fail to create test directory: " + dir1; throw new RuntimeException(msg); } try { Files.writeString(file1.toPath(), TEXT_FILE_1_CONTENT); Files.writeString(file2.toPath(), TEXT_FILE_2_CONTENT); } catch (IOException e) { final var msg = "Fail to setup default FS: " + e; throw new RuntimeException(msg); } } }
35.533708
102
0.67004
9d4fa6ace3cfd25ba35992c4a7ec325ea2fb3fb6
778
package jp.chang.myclinic.recordbrowser.tracking.modelold; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import jp.chang.myclinic.dto.ConductShinryouDTO; import jp.chang.myclinic.dto.ShinryouMasterDTO; public class ConductShinryou { private int conductShinryouId; private StringProperty rep = new SimpleStringProperty(); public ConductShinryou(ConductShinryouDTO dto, ShinryouMasterDTO master) { this.conductShinryouId = dto.conductShinryouId; this.rep.setValue(master.name); } public int getConductShinryouId() { return conductShinryouId; } public String getRep() { return rep.get(); } public StringProperty repProperty() { return rep; } }
25.933333
78
0.733933
5b49bf22755a3d07a8716224388dc90008b56748
2,870
/* * Copyright 2017 David Karnok * * 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 hu.akarnokd.reactive4javaflow.impl.util; import hu.akarnokd.reactive4javaflow.impl.*; import java.lang.invoke.*; import java.util.Objects; public final class SpscArrayQueue<T> implements PlainQueue<T> { final T[] array; static final VarHandle ARRAY = MethodHandles.arrayElementVarHandle(Object[].class); final int mask; long producerIndex; static final VarHandle PRODUCER_INDEX = VH.find(MethodHandles.lookup(), SpscArrayQueue.class, "producerIndex", Long.TYPE); long consumerIndex; static final VarHandle CONSUMER_INDEX = VH.find(MethodHandles.lookup(), SpscArrayQueue.class, "consumerIndex", Long.TYPE); public SpscArrayQueue(int capacity) { int c = QueueHelper.pow2(capacity); this.array = (T[])new Object[c]; this.mask = c - 1; } @Override public boolean offer(T item) { Objects.requireNonNull(item, "item == null"); T[] a = array; int m = mask; long pi = producerIndex; int offset = (int)pi & m; if (ARRAY.getAcquire(a, offset) == null) { ARRAY.setRelease(a, offset, item); PRODUCER_INDEX.setRelease(this, pi + 1); return true; } return false; } @Override public T poll() { T[] a = array; int m = mask; long ci = consumerIndex; int offset = (int)ci & m; T v = (T)ARRAY.getAcquire(a, offset); if (v != null) { ARRAY.setRelease(a, offset, null); CONSUMER_INDEX.setRelease(this, ci + 1); } return v; } @Override public boolean isEmpty() { return (long)PRODUCER_INDEX.getAcquire(this) == (long)CONSUMER_INDEX.getAcquire(this); } @Override public void clear() { T[] a = array; int m = mask; long ci = consumerIndex; int offset = (int)ci & m; if (ARRAY.getAcquire(a, offset) != null) { for (;;) { ARRAY.setRelease(a, offset, null); offset = (offset + 1) & m; ci++; if (ARRAY.getAcquire(a, offset) == null) { break; } } CONSUMER_INDEX.setRelease(this, ci); } } }
28.7
126
0.597213
03f84febb5af76a7ea130cd0c7681cb9e8e0c1f5
3,276
package ru.stq.pft.addressbook.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stq.pft.addressbook.model.ContactData; import ru.stq.pft.addressbook.model.Groups; import java.io.File; import java.util.Arrays; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class ContactDetailsTests extends BaseTest { @BeforeMethod//pamiętaj że w tym teście porównywanie bez nazwiska panieńskiego, nie zapisuję się w szczególach; public void ensurePreconditions() { app.goTo().homePage(); if (app.db().contacts().size() == 0) { Groups groups = app.db().groups(); File photo=new File("src/test/resources/kwiatek.jpg"); app.contact().create(new ContactData() .withFirstName("Bozena") .withLastname( "Chilecka").withPhoto(photo).withCompany("OBI") .withTitle("Human Recources Manager").withAddress("Ordona 7B/41") .withMobilePhone("567098098").withHomePhone("22445959").withWorkPhone("2253454432") .withEmail("bozena.chilecka@gmail.com").withEmailSecond("bozenakam25@gmail.com") .withEmailThird("bozna@wp.pl").inGroup(groups.iterator().next()),true); } } @Test public void testContactDetails() { ContactData contact = app.contact().all().iterator().next(); ContactData contactEditInfoForm = app.contact().infoFormEditForm(contact); ContactData contactDetailsInfoForm = app.contact().infoFromDetails(contact); assertThat(margeDetails(contactEditInfoForm), equalTo(cleaned(contactDetailsInfoForm.getName()))); } private String margePhonesDetails(ContactData contact) { return Arrays.asList(contact.getHomePhone(), contact.getMobilePhone(), contact.getworkPhone()) .stream().filter((p) -> !p.equals("")) .map(ContactPhoneTests::cleaned) .collect(Collectors.joining("\n")); } public String mergeEmails(ContactData contact) { return Arrays.asList(contact.getEmail(),contact.getEmailSecond(),contact.getEmailThird()) .stream().filter((s -> !s.equals(""))) .map(ContactEmailTests::cleaned) .collect(Collectors.joining("\n")); } private String margeNameAndSurname(ContactData contact) { return Arrays.asList((contact.getFirstName() + " " + contact.getLastname()) .trim(),contact.getTitle(), contact.getCompany(), contact.getAddress()) .stream().filter((n) -> !n.equals("")) .collect(Collectors.joining("\n")); } private String margeDetails(ContactData contact) { return Arrays.asList(margeNameAndSurname(contact), margePhonesDetails(contact), mergeEmails(contact)) .stream().filter((d) -> !d.equals("")) .collect(Collectors.joining("\n")); } public String cleaned(String phone) { return phone.replaceAll("[A-Z]: ", "") .replaceAll("\n\n", "\n") .replaceAll("\n\nMember of: [A-Z,a-z]* *[0-9]*",""); } }
40.95
115
0.632479
83b9ca5b3ec7217c37f274fe5c9cb189417f5502
3,126
/* * Copyright 2000-2017 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.flow.spring; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import com.vaadin.flow.di.DefaultInstantiator; import com.vaadin.flow.i18n.I18NProvider; import com.vaadin.flow.internal.UsageStatistics; import com.vaadin.flow.server.VaadinService; import com.vaadin.flow.server.VaadinServiceInitListener; /** * Default Spring instantiator that is used if no other instantiator has been * registered. This implementation uses Spring beans. * * @author Vaadin Ltd * */ public class SpringInstantiator extends DefaultInstantiator { private ApplicationContext context; private AtomicBoolean loggingEnabled = new AtomicBoolean(true); /** * Creates a new spring instantiator instance. * * @param service * the service to use * @param context * the application context */ public SpringInstantiator(VaadinService service, ApplicationContext context) { super(service); this.context = context; UsageStatistics.markAsUsed("flow/SpringInstantiator", null); } @Override public Stream<VaadinServiceInitListener> getServiceInitListeners() { Stream<VaadinServiceInitListener> springListeners = context .getBeansOfType(VaadinServiceInitListener.class).values() .stream(); return Stream.concat(super.getServiceInitListeners(), springListeners); } @Override public I18NProvider getI18NProvider() { int beansCount = context.getBeanNamesForType(I18NProvider.class).length; if (beansCount == 1) { return context.getBean(I18NProvider.class); } else { if (loggingEnabled.compareAndSet(true, false)) { LoggerFactory.getLogger(SpringInstantiator.class.getName()) .info("The number of beans implementing '{}' is {}. Cannot use Spring beans for I18N, " + "falling back to the default behavior", I18NProvider.class.getSimpleName(), beansCount); } return super.getI18NProvider(); } } @Override public <T> T getOrCreate(Class<T> type) { if (context.getBeanNamesForType(type).length == 1) { return context.getBean(type); } return context.getAutowireCapableBeanFactory().createBean(type); } }
34.351648
111
0.680102
904d1f63abd001af04b7e432b5d24abc54478d46
3,542
package com.wwls.modules.shoppingmall.web.goods; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.wwls.common.config.Global; import com.wwls.common.persistence.Page; import com.wwls.common.web.BaseController; import com.wwls.common.utils.StringUtils; import com.wwls.modules.shoppingmall.entity.goods.GsOrder; import com.wwls.modules.shoppingmall.service.goods.GsOrderService; import com.wwls.modules.sys.utils.UserUtils; /** * 订单管理Controller * @author leixiaoming * @version 2019-03-15 */ @Controller @RequestMapping(value = "${adminPath}/shoppingmall/goods/gsOrder") public class GsOrderController extends BaseController { @Autowired private GsOrderService gsOrderService; @ModelAttribute public GsOrder get(@RequestParam(required=false) String id) { GsOrder entity = null; if (StringUtils.isNotBlank(id)){ entity = gsOrderService.get(id); } if (entity == null){ entity = new GsOrder(); } return entity; } @RequiresPermissions("shoppingmall:goods:gsOrder:view") @RequestMapping(value = {"list", ""}) public String list(GsOrder gsOrder, HttpServletRequest request, HttpServletResponse response, Model model) { gsOrder.setOffice(UserUtils.getUser().getOffice()); Page<GsOrder> page = gsOrderService.findPage(new Page<GsOrder>(request, response), gsOrder); model.addAttribute("page", page); return "modules/shoppingmall/goods/gsOrderList"; } @RequiresPermissions("shoppingmall:goods:gsOrder:view") @RequestMapping(value = "form") public String form(GsOrder gsOrder, Model model) { model.addAttribute("gsOrder", gsOrder); return "modules/shoppingmall/goods/gsOrderForm"; } @RequiresPermissions("shoppingmall:goods:gsOrder:edit") @RequestMapping(value = "save") public String save(GsOrder gsOrder, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, gsOrder)){ return form(gsOrder, model); } if (gsOrder.getIsNewRecord()) { gsOrder.setOffice(gsOrder.getCurrentUser().getOffice()); } gsOrderService.save(gsOrder); addMessage(redirectAttributes, "保存订单成功"); return "redirect:"+Global.getAdminPath()+"/shoppingmall/goods/gsOrder/?repage"; } /* * 发货 */ @RequiresPermissions("shoppingmall:goods:gsOrder:edit") @RequestMapping(value = "takeh") public String takeh(GsOrder gsOrder, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, gsOrder)){ return form(gsOrder, model); } if (gsOrder.getIsNewRecord()) { gsOrder.setOffice(gsOrder.getCurrentUser().getOffice()); } gsOrderService.takeh(gsOrder); addMessage(redirectAttributes, "发货成功"); return "redirect:"+Global.getAdminPath()+"/shoppingmall/goods/gsOrder/?repage"; } @RequiresPermissions("shoppingmall:goods:gsOrder:edit") @RequestMapping(value = "delete") public String delete(GsOrder gsOrder, RedirectAttributes redirectAttributes) { gsOrderService.delete(gsOrder); addMessage(redirectAttributes, "删除订单成功"); return "redirect:"+Global.getAdminPath()+"/shoppingmall/goods/gsOrder/?repage"; } }
35.069307
109
0.774421
ba83dbb3b7b69889f6f9928e7c0199c739a37a2e
292
package com.ucloud.library.netanalysis.module; /** * Created by joshua on 2018/9/19 15:14. * Company: UCloud * E-mail: joshua.yin@ucloud.cn */ public enum UCSdkStatus { /** 注册模块成功 */ REGISTER_SUCCESS, /** * appKey或者appSecret无效 */ APPKEY_OR_APPSECRET_ILLEGAL, }
18.25
46
0.657534
7acb1b4af325b83ab2005fb3a68d9ead167e9c74
682
package switchtwentytwenty.project.domain.aggregates.ledger; import org.junit.jupiter.api.Test; import switchtwentytwenty.project.domain.valueobject.ID; import static org.junit.jupiter.api.Assertions.*; class TransferTest { @Test void temporaryConstructorTest() { Transfer transfer = new Transfer(); assertNotNull(transfer); } @Test void temporaryIDTest() { Transfer transfer = new Transfer(); ID result = transfer.id(); assertNull(result); } @Test void temporaryHasIDTest() { Transfer transfer = new Transfer(); boolean result = transfer.hasID(null); assertFalse(result); } }
23.517241
60
0.664223
c526108b2e762ac78ec15cd0c937b3731ce66a5d
1,873
package se.basile.compax; import android.widget.ImageView; import android.widget.TextView; import java.util.Observable; import java.util.Observer; import se.basile.compax.nmea.ECRMB; import se.basile.compax.nmea.SentenceAbstr; import se.basile.compax.nmea.YDHDM; public class Bearing implements Observer { private ImageView bearingImageView; private ImageView miniCompassImageView; private TextView bearingTextView; private float bearing = 0.f; private float heading = 0.f; public Bearing(ImageView bearingImageView, ImageView miniCompassImageView, TextView bearingTextView){ this.bearingImageView = bearingImageView; this.miniCompassImageView = miniCompassImageView; this.bearingTextView = bearingTextView; } public void setRotationRelative(float heading){ this.heading = heading; bearingImageView.setRotation(bearing-heading); } public boolean isShown(){ return miniCompassImageView.isShown(); } public void setVisibility(int visibility){ miniCompassImageView.setVisibility(visibility); bearingTextView.setVisibility(visibility); } @Override public void update(Observable observable, Object object) { float newBearing = 0.f; SentenceAbstr sentence = (SentenceAbstr) object; if (sentence.getType()=="ECRMB") { ECRMB ecrmb = (ECRMB) sentence; newBearing = Math.round(Float.parseFloat(ecrmb.bearing)); if (newBearing != bearing){ bearing = newBearing; setRotationRelative(heading); bearingTextView.setText("Bearing\n"+ bearing+"°"); } } else if (sentence.getType()=="YDHDM") { YDHDM ydhdm = (YDHDM) sentence; setRotationRelative(Float.parseFloat(ydhdm.heading)); } } }
28.378788
105
0.675387
fdbb83b0e0030c1d9f3e56b543a64d489e476b59
824
package io.github.wrobezin.eunha.data.entity.rule; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.time.LocalDateTime; import java.util.List; /** * 用户自定义规则 * * @author yuan * @version 1.0 * @date 2020/3/30 13:50 */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @Document("rule") public class CustomizedRule { @Id private String id; /** 规则名 */ private String name; /** 抓取规则 */ private CrawlRule crawlRule; /** 兴趣规则 */ private InterestRule interestRule; /** 推送方式 */ private List<PushContact> pushContacts; private LocalDateTime createTime; private LocalDateTime updateTime; }
20.6
62
0.725728
9ff678e73e8f27b81767eb884264bc2959d53c50
2,495
package com.bughunters.site.ems.controller; import com.bughunters.site.ems.domain.Employee; import com.bughunters.site.ems.service.EmplpyeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Controller @RequestMapping("/employees") public class EmployeeControllerImpl implements EmployeeController { @Autowired private EmplpyeeService service; @GetMapping("/{id}") @Override public String findById(@PathVariable int id, Model model) { System.out.println("* EmplpoyeeController.FindById : "+id); Employee employee = service.findById(id); model.addAttribute("employee",employee); return "/employee"; } @GetMapping("/list") @Override public String findAll(Model model) { System.out.println("* EmplpoyeeController.FindAll() : "); List<Employee> allemployees = service.findAll(); // add the animals object to the view model.addAttribute("allemployees",allemployees); return "/employees"; } @GetMapping("/add") @Override public String add(Model model) { System.out.println("* EmplpoyeeController.Add() : "); model.addAttribute(new Employee()); return "add"; } @PostMapping("new") @Override public String create(Employee employee) { System.out.println("added "+employee); service.add(employee); return "redirect:/employees/list"; } @PostMapping("/update/{id}") @Override public String update (@PathVariable int id , Employee employee) { service.update(id,employee); return "redirect:/employees/list"; } @GetMapping("/delete/{id}") @Override public String delete (@PathVariable int id) { System.out.println("deleted "+id); service.delete(id); return "redirect:/employees/list"; } @GetMapping("/edit/{id}") @Override public String edit(@PathVariable int id, Model model) { Employee employee = service.findById(id); model.addAttribute("employee",employee); return "/edit"; } }
25.459184
67
0.670541
54d4aa4e9fab5797f78c008ce727e85efe2b93f8
1,611
package org.hisp.dhis.hr.action.indicator; import java.util.ArrayList; import java.util.Collection; import org.hisp.dhis.hr.AggregateAttribute; import org.hisp.dhis.hr.AggregateAttributeService; import org.hisp.dhis.hr.Attribute; import org.hisp.dhis.hr.AttributeService; import com.opensymphony.xwork2.Action; public class GetAggregateIndicatorListAction implements Action{ // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- private AggregateAttributeService aggregateAttributeService; public void setAggregateAttributeService( AggregateAttributeService aggregateAttributeService ) { this.aggregateAttributeService = aggregateAttributeService; } // ------------------------------------------------------------------------- // Output // ------------------------------------------------------------------------- private Collection<AggregateAttribute> aggregateAttributes = new ArrayList<AggregateAttribute>(); public Collection<AggregateAttribute> getAggregateAttributes() { return aggregateAttributes; } // ------------------------------------------------------------------------- // Action implementation // ------------------------------------------------------------------------- public String execute() throws Exception { aggregateAttributes = aggregateAttributeService.getAllAggregateAttribute(); return SUCCESS; } }
27.775862
101
0.517691
313fb345ba34b3e014a8694611483cab5b739a50
8,398
/* * $Id: TestCopyFormToContext.java 376714 2006-02-10 14:50:57Z husted $ * * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.struts.chain.commands.generic; import junit.framework.TestCase; import org.apache.struts.action.ActionForm; import org.apache.struts.action.DynaActionForm; import org.apache.struts.chain.contexts.MockActionContext; import org.apache.struts.config.ActionConfig; import org.apache.struts.config.FormBeanConfig; import org.apache.struts.config.FormPropertyConfig; import org.apache.struts.config.impl.ModuleConfigImpl; import org.apache.struts.mock.MockFormBean; /** * @version $Id: TestCopyFormToContext.java 161516 2005-04-15 19:22:47Z * germuska $ */ public class TestCopyFormToContext extends TestCase { private static final String POST_EXECUTION_CONTEXT_KEY = "afterTest"; private MockActionContext context = null; public static void main(String[] args) { junit.textui.TestRunner.run(TestCopyFormToContext.class); } /* * @see TestCase#setUp() */ protected void setUp() throws Exception { context = new MockActionContext(); ModuleConfigImpl moduleConfig = new ModuleConfigImpl("/"); context.setModuleConfig(moduleConfig); FormBeanConfig fooFBC = new FormBeanConfig(); fooFBC.setName("foo"); fooFBC.setType("org.apache.struts.mock.MockFormBean"); moduleConfig.addFormBeanConfig(fooFBC); FormBeanConfig barFBC = new FormBeanConfig(); barFBC.setName("bar"); barFBC.setType("org.apache.struts.action.DynaActionForm"); // use a different type so we can verify lookups better FormPropertyConfig fpc = new FormPropertyConfig(); fpc.setName("property"); fpc.setType("java.lang.String"); fpc.setInitial("test"); barFBC.addFormPropertyConfig(fpc); moduleConfig.addFormBeanConfig(barFBC); ActionConfig testActionConfig = new ActionConfig(); testActionConfig.setPath("/Test"); testActionConfig.setName("foo"); testActionConfig.setScope("request"); moduleConfig.addActionConfig(testActionConfig); moduleConfig.freeze(); // otherwise, ActionConfigMatcher will be null and we'll get an NPE... } public void testLookupByNameAndRequestScope() throws Exception { CopyFormToContext command = new CopyFormToContext(); String formName = "foo"; command.setFormName(formName); command.setScope("request"); command.setToKey(POST_EXECUTION_CONTEXT_KEY); assertNull(context.get(POST_EXECUTION_CONTEXT_KEY)); assertNull(context.getRequestScope().get(formName)); assertNull(context.getSessionScope().get(formName)); command.execute(context); assertNotNull(context.get(POST_EXECUTION_CONTEXT_KEY)); assertNotNull(context.getRequestScope().get(formName)); assertNull(context.getSessionScope().get(formName)); assertSame(context.get(POST_EXECUTION_CONTEXT_KEY), context.getRequestScope().get(formName)); ActionForm theForm = (ActionForm) context.get(POST_EXECUTION_CONTEXT_KEY); assertTrue(theForm instanceof MockFormBean); } public void testLookupByActionPath() throws Exception { CopyFormToContext command = new CopyFormToContext(); command.setActionPath("/Test"); command.setToKey(POST_EXECUTION_CONTEXT_KEY); String formName = "foo"; // we know this, even though it's not being used for the lookup. assertNull(context.get(POST_EXECUTION_CONTEXT_KEY)); assertNull(context.getRequestScope().get(formName)); assertNull(context.getSessionScope().get(formName)); command.execute(context); assertNotNull(context.get(POST_EXECUTION_CONTEXT_KEY)); assertNotNull(context.getRequestScope().get(formName)); assertNull(context.getSessionScope().get(formName)); assertSame(context.get(POST_EXECUTION_CONTEXT_KEY), context.getRequestScope().get(formName)); ActionForm theForm = (ActionForm) context.get(POST_EXECUTION_CONTEXT_KEY); assertTrue(theForm instanceof MockFormBean); } public void testLookupByNameAndSessionScope() throws Exception { CopyFormToContext command = new CopyFormToContext(); String formName = "bar"; command.setFormName(formName); command.setScope("session"); command.setToKey(POST_EXECUTION_CONTEXT_KEY); assertNull(context.get(POST_EXECUTION_CONTEXT_KEY)); assertNull(context.getRequestScope().get(formName)); assertNull(context.getSessionScope().get(formName)); command.execute(context); assertNotNull(context.get(POST_EXECUTION_CONTEXT_KEY)); assertNull(context.getRequestScope().get(formName)); assertNotNull(context.getSessionScope().get(formName)); assertSame(context.get(POST_EXECUTION_CONTEXT_KEY), context.getSessionScope().get(formName)); ActionForm theForm = (ActionForm) context.get(POST_EXECUTION_CONTEXT_KEY); assertTrue(theForm instanceof DynaActionForm); DynaActionForm dForm = (DynaActionForm) theForm; assertEquals("test", dForm.get("property")); } public void testExceptionHandlingWithNullFormName() throws Exception { CopyFormToContext command = new CopyFormToContext(); String formName = "bar"; // skip setting form name to test exception // command.setFormName(formName); command.setScope("session"); command.setToKey(POST_EXECUTION_CONTEXT_KEY); assertNull(context.get(POST_EXECUTION_CONTEXT_KEY)); assertNull(context.getRequestScope().get(formName)); assertNull(context.getSessionScope().get(formName)); try { command.execute(context); fail( "Execution should throw an exception when form name is not set."); } catch (IllegalStateException e) { ; // expected. } } public void testExceptionHandlingWithNullEverything() throws Exception { CopyFormToContext command = new CopyFormToContext(); String formName = "bar"; // skip setting form name to test exception // command.setFormName(formName); // command.setScope("session"); // command.setToKey(POST_EXECUTION_CONTEXT_KEY); assertNull(context.get(POST_EXECUTION_CONTEXT_KEY)); assertNull(context.getRequestScope().get(formName)); assertNull(context.getSessionScope().get(formName)); try { command.execute(context); fail( "Execution should throw an exception when no properties are set."); } catch (IllegalStateException e) { ; // expected. } } public void testCopyToDefaultContextKey() throws Exception { CopyFormToContext command = new CopyFormToContext(); String formName = "foo"; command.setFormName(formName); command.setScope("request"); assertNull(context.getActionForm()); assertNull(context.getRequestScope().get(POST_EXECUTION_CONTEXT_KEY)); assertNull(context.getSessionScope().get(POST_EXECUTION_CONTEXT_KEY)); command.execute(context); assertNotNull(context.getActionForm()); assertNotNull(context.getRequestScope().get(formName)); assertNull(context.getSessionScope().get(formName)); assertSame(context.getActionForm(), context.getRequestScope().get(formName)); ActionForm theForm = (ActionForm) context.getActionForm(); assertTrue(theForm instanceof MockFormBean); } }
34.846473
122
0.68552
7334d5e4e174a55dbb1bc51ccfa3f8f81af0b8be
749
/* * File: SymbolTableError.java * * Desc: contains the errors associated with * symbol table routines. */ package main.java.table.errors; /** * SymbolTableError * @author Luis Serazo */ public class SymbolTableError extends Error{ /** * SymbolTableError constructor * @param msg: the error message. */ private SymbolTableError(String msg){ super(msg); } /** * EntryAlreadyExists: throw error when an entry already exists in the table * @param name: the string name of the entry. * @return a SymbolTableError */ public static SymbolTableError EntryAlreadyExists(String name){ return new SymbolTableError("The entry: "+name+" already exists in the Symbol Table."); } }
24.16129
95
0.672897
0ba72805511ddad6170dabbe7c31f2311b0e245c
4,269
package calcmalc.structures; import org.junit.Test; import static org.junit.Assert.*; public class ListTest { @Test public void testListIsCreatedWithCorrectSize() { List<Integer> list = new List<>(); assertEquals(list.getSpace(), 8); } @Test public void testElementCanBePushedToList() { List<Integer> list = new List<>(); list.append(1); assertEquals(list.get(0), (Integer) 1); } @Test public void testElementsCanBePushedToList() { List<Integer> list = new List<>(); list.append(1); list.append(2); list.append(3); list.append(4); assertEquals(list.get(0), (Integer) 1); assertEquals(list.get(1), (Integer) 2); assertEquals(list.get(2), (Integer) 3); assertEquals(list.get(3), (Integer) 4); } @Test public void testListSizeGetExponentiallyLarger() { List<Integer> list = new List<>(); for (int i = 0; i <= 8; ++i) { list.append(i); } assertEquals(list.getSpace(), 16); for (int i = 8; i < 16; ++i) { list.append(i); } assertEquals(list.getSpace(), 32); for (int i = 16; i < 32; ++i) { list.append(i); } assertEquals(list.getSpace(), 64); } @Test public void testGetElementAtIncorrectIndex() { List<Integer> list = new List<>(); Exception exception = assertThrows(IllegalArgumentException.class, () -> { Integer i = list.get(-1); }); } @Test public void testGetElementAtIncorrectIndex2() { List<Integer> list = new List<>(); list.append(1); list.append(2); Exception exception = assertThrows(IllegalArgumentException.class, () -> { Integer i = list.get(2); }); } @Test public void testGetElementAtIncorrectIndex3() { List<Integer> list = new List<>(); list.append(1); list.append(2); assertEquals((Integer) 1, list.get(0)); assertEquals((Integer) 2, list.get(1)); Exception exception = assertThrows(IllegalArgumentException.class, () -> { Integer i = list.get(8); }); } @Test public void testSetInsertsValueAtIndex() { List<Integer> list = new List<>(); list.set(0, 2); assertEquals((Integer) 2, list.get(0)); } @Test public void testSetReplacesValueAtIndex() { List<Integer> list = new List<>(); list.append(1); list.append(5); list.append(7); assertEquals((Integer) 7, list.get(2)); list.set(2, 2); assertEquals((Integer) 2, list.get(2)); } @Test public void testListSetToPowerOfTwo() { List<Integer> list = new List<>(); list.append(1); // head = 0 list.append(1); // head = 1 list.append(1); // head = 2 list.append(1); // head = 3 list.append(1); // head = 4 list.append(1); // head = 5 list.append(1); // head = 6 assertEquals(8, list.getSpace()); list.append(1); // head = 7 list.set(7, 2); assertEquals(8, list.size()); assertEquals((Integer) 2, list.get(7)); assertEquals(16, list.getSpace()); } @Test public void testListIsEmpty() { List<Integer> list = new List<>(); assertTrue(list.isEmpty()); list.append(0); assertTrue(!list.isEmpty()); } @Test public void testSetThrowsOnIllegalIndex() { List<Integer> list = new List<>(); Exception exception = assertThrows(IllegalArgumentException.class, () -> { list.set(-1, 2); }); } @Test public void testSetThrowsOnIllegalIndex2() { List<Integer> list = new List<>(); list.append(1); Exception exception = assertThrows(IllegalArgumentException.class, () -> { list.set(2, 2); }); } @Test public void testSetIncreasesTheSizeOfTheArray() { List<Integer> list = new List<>(); list.append(1); Exception exception = assertThrows(IllegalArgumentException.class, () -> { list.set(2, 2); }); } }
26.68125
82
0.545561
266f16d8a7d7d735d07eda15f2737817058d7cc7
1,144
/* * 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.darkmidnight.slacklights; /** * * @author anthony */ public class DataSingleton { private static DataSingleton singleton; private double lastTimestamp = 0; private String lastQS = ""; private boolean isBlocked = false; private DataSingleton() { } public static DataSingleton getSingleton() { if (singleton == null) { singleton = new DataSingleton(); } return singleton; } public double getLastTimestamp() { return lastTimestamp; } public void setLastTimestamp(double lastTimestamp) { this.lastTimestamp = lastTimestamp; } public String getLastQS() { return lastQS; } public void setLastQS(String lastQS) { this.lastQS = lastQS; } public boolean isIsBlocked() { return isBlocked; } public void setIsBlocked(boolean isBlocked) { this.isBlocked = isBlocked; } }
20.428571
79
0.637238
cf2f6a74260ef3c0d7535f0a5ff8dd9ab54ac419
8,929
/* * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package nsk.jdi.ReferenceType.sourceName; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; import com.sun.jdi.*; import java.util.*; import java.io.*; /** * This test checks the method <code>sourceName()</code> * of the JDI interface <code>ReferenceType</code> of com.sun.jdi package */ public class sourcename001 { static ArgumentHandler argsHandler; static Log test_log_handler; static boolean verbose_mode = false; // test argument -verbose switches to true // - for more easy failure evaluation /** The main class sourceNames of the debugger & debugee applications. */ private final static String package_prefix = "nsk.jdi.ReferenceType.sourceName.", // package_prefix = "", // for DEBUG without package thisClassName = package_prefix + "sourcename001", debugeeName = thisClassName + "a"; static String this_class_source_name = "sourcename001.java"; static String debugee_source_name = "sourcename001a.java"; /** Debugee's classes for check **/ private final static String classes_for_check[][] = { {thisClassName, this_class_source_name}, {debugeeName, debugee_source_name}, {package_prefix + "ClassForCheck", debugee_source_name}, {package_prefix + "InterfaceForCheck", debugee_source_name}, {debugeeName+"$s_class", debugee_source_name}, {debugeeName+"$s_interf", debugee_source_name} }; /** * Re-call to <code>run(args,out)</code>, and exit with * either status 95 or 97 (JCK-like exit status). */ public static void main (String argv[]) { int exitCode = run(argv,System.out); System.exit(exitCode + 95/*STATUS_TEMP*/); } /** * JCK-like entry point to the test: perform testing, and * return exit code 0 (PASSED) or either 2 (FAILED). */ public static int run (String argv[], PrintStream out) { int v_test_result = new sourcename001().runThis(argv,out); if ( v_test_result == 2/*STATUS_FAILED*/ ) { print_log_anyway("\n==> nsk/jdi/ReferenceType/sourceName/sourcename001 test FAILED"); } else { print_log_anyway("\n==> nsk/jdi/ReferenceType/sourceName/sourcename001 test PASSED"); } return v_test_result; } private static void print_log_on_verbose(String message) { test_log_handler.display(message); } private static void print_log_anyway(String message) { test_log_handler.println(message); } /** * Non-static variant of the method <code>run(args,out)</code> */ private int runThis (String argv[], PrintStream out) { argsHandler = new ArgumentHandler(argv); verbose_mode = argsHandler.verbose(); test_log_handler = new Log(out, argsHandler); print_log_anyway("==> nsk/jdi/ReferenceType/sourceName/sourcename001 test LOG:"); print_log_anyway("==> test checks the sourceName() method of ReferenceType interface"); print_log_anyway(" of the com.sun.jdi package for ClassType, InterfaceType\n"); String debugee_launch_command = debugeeName; Binder binder = new Binder(argsHandler,test_log_handler); Debugee debugee = binder.bindToDebugee(debugee_launch_command); IOPipe pipe = new IOPipe(debugee); debugee.redirectStderr(out); print_log_on_verbose("--> sourcename001: sourcename001a debugee launched"); debugee.resume(); String line = pipe.readln(); if (line == null) { print_log_anyway("##> sourcename001: UNEXPECTED debugee's signal (not \"ready\") - " + line); return 2/*STATUS_FAILED*/; } if (!line.equals("ready")) { print_log_anyway("##> sourcename001: UNEXPECTED debugee's signal (not \"ready\") - " + line); return 2/*STATUS_FAILED*/; } else { print_log_on_verbose("--> sourcename001: debugee's \"ready\" signal recieved!"); } print_log_anyway ("--> sourcename001: check ReferenceType.sourceName() method for debugee's classes..."); int all_classes_count = 0; int class_not_found_errors = 0; int sourceName_method_exceptions = 0; int sourceName_method_errors = 0; for (int i=0; i<classes_for_check.length; i++) { String className = classes_for_check[i][0]; String source_class_name = classes_for_check[i][1]; all_classes_count++; ReferenceType refType = debugee.classByName(className); if (refType == null) { print_log_anyway("##> sourcename001: Could NOT FIND class: " + className); class_not_found_errors++; continue; } String ref_type_source_name = null; try { ref_type_source_name = refType.sourceName(); } catch (Throwable thrown) { print_log_anyway ("##> sourcename001: FAILED: refType.sourceName() threw unexpected exception - " + thrown); print_log_anyway ("##> refType = " + refType); sourceName_method_exceptions++; continue; } if ( ! ref_type_source_name.equals(source_class_name) ) { print_log_anyway ("##> sourcename001: FAILED: ReferenceType.sourceName() returned unexpected source name:"); print_log_anyway ("##> expected source name = " + source_class_name); print_log_anyway ("##> returned source name = " + ref_type_source_name); sourceName_method_errors++; } else { print_log_on_verbose ("--> sourcename001: PASSED: ReferenceType.sourceName() returned expected source name:"); print_log_on_verbose ("--> checked class source name = " + source_class_name); print_log_on_verbose ("--> returned source name = " + ref_type_source_name); } } print_log_anyway("--> sourcename001: check completed!"); print_log_anyway("--> sourcename001: number of checked classes = " + all_classes_count); if ( class_not_found_errors > 0 ) { print_log_anyway("##> sourcename001: \"class not found ERRORS\" number = " + class_not_found_errors); } if ( sourceName_method_exceptions > 0 ) { print_log_anyway("##> sourcename001: number of unexpected sourceName() methods exceptions = " + sourceName_method_exceptions); } print_log_anyway("##> sourcename001: sourceName() method errors number = " + sourceName_method_errors); int v_test_result = 0/*STATUS_PASSED*/; if (class_not_found_errors + sourceName_method_errors + sourceName_method_exceptions > 0) { v_test_result = 2/*STATUS_FAILED*/; } print_log_on_verbose("--> sourcename001: waiting for debugee finish..."); pipe.println("quit"); debugee.waitFor(); int status = debugee.getStatus(); if (status != 0/*STATUS_PASSED*/ + 95/*STATUS_TEMP*/) { print_log_anyway("##> sourcename001: UNEXPECTED Debugee's exit status (not 95) - " + status); v_test_result = 2/*STATUS_FAILED*/; } else { print_log_on_verbose("--> sourcename001: expected Debugee's exit status - " + status); } return v_test_result; } }
41.147465
111
0.612163