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
3a69df08f9a6574bebd47edaa50e495dee04d602
939
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.world.propagation; /** * An enum that describes how propagation rules have changes when blocks are replaced with others */ public enum PropagationComparison { /** * Propagation is restricted in some way it wasn't before */ MORE_RESTRICTED(true, false), /** * Propagation is identical to before */ IDENTICAL(false, false), /** * Propagation is strictly more permissive than before */ MORE_PERMISSIVE(false, true); private boolean restricting; private boolean permitting; PropagationComparison(boolean restricts, boolean permits) { this.restricting = restricts; this.permitting = permits; } public boolean isRestricting() { return restricting; } public boolean isPermitting() { return permitting; } }
24.076923
97
0.675186
b04d059c0d084538416e666f5d1ced9f501192ad
2,786
/* * 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.prestosql.server.testing; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import io.airlift.airline.Option; import java.util.ArrayList; import java.util.List; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; class TestingPrestoServerLauncherOptions { private static final Splitter CATALOG_OPTION_SPLITTER = Splitter.on(':').trimResults(); public static class Catalog { private final String catalogName; private final String connectorName; public Catalog(String catalogName, String connectorName) { this.catalogName = requireNonNull(catalogName, "catalogName is null"); this.connectorName = requireNonNull(connectorName, "connectorName is null"); } public String getCatalogName() { return catalogName; } public String getConnectorName() { return connectorName; } } @Option(name = "--catalog", title = "catalog", description = "Catalog:Connector mapping (can be repeated)") private List<String> catalogOptions = new ArrayList<>(); @Option(name = "--plugin", title = "plugin", description = "Fully qualified class name of plugin to be registered (can be repeated)") private List<String> pluginClassNames = new ArrayList<>(); public List<Catalog> getCatalogs() { return catalogOptions.stream().map(catalogOption -> { List<String> parts = ImmutableList.copyOf(CATALOG_OPTION_SPLITTER.split(catalogOption)); checkState(parts.size() == 2, "bad format of catalog definition '%s'; should be catalog_name:connector_name", catalogOption); return new Catalog(parts.get(0), parts.get(1)); }).collect(toList()); } public List<String> getPluginClassNames() { return pluginClassNames; } public void validate() { checkState(!pluginClassNames.isEmpty(), "some plugins must be defined"); checkState(!catalogOptions.isEmpty(), "some catalogs must be defined"); getCatalogs(); } }
34.825
137
0.691314
8e70670e83ae1f44478f9084a49144a2344419e0
1,155
package com.sandrew.bury.r2; import com.sandrew.bury.Session; import com.sandrew.bury.SqlSessionFactory; import com.sandrew.bury.SqlSessionFactoryBuilder; import com.sandrew.bury.callback.POCallBack; import com.sandrew.bury.model.SessionExt; import org.junit.Test; import java.util.List; public class QueryTestForExtModel { @Test public void test() { String configFile = "bury-config.xml"; SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(configFile); Session session = factory.openSession(); try { // 2.0版本查询 StringBuilder sql = new StringBuilder("select *, 'abc' as ext from tt_session"); List<SessionExt> list = session.select(sql.toString(), null, new POCallBack(SessionExt.class)); list.stream().forEach(item -> { System.out.println("id :" + item.getSessionId().getValue() + " session:" + item.getSession().getValue() + " ext:" + item.getExt() + " createdate : " + item.getCreateDate().getValue()); }); } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } }
26.25
189
0.681385
26ff643fd2f8660f33cb863169a76db6d839a576
1,663
/* * Copyright 2016-2022 Talsma ICT * * 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 nl.talsmasoftware.enumerables.jdbi3; import org.jdbi.v3.core.Jdbi; import org.jdbi.v3.core.argument.Arguments; import org.jdbi.v3.core.mapper.ColumnMappers; import org.jdbi.v3.core.spi.JdbiPlugin; /** * {@link JdbiPlugin JDBI plugin} that registers mappers for {@code Enumerable} subclasses. * <p> * This plugin registers itself when {@link Jdbi#installPlugins()} gets called, * bug can also be explicitly installed using {@link Jdbi#installPlugin(JdbiPlugin)}. * * @author Sjoerd Talsma */ public class EnumerableJdbiPlugin implements JdbiPlugin { /** * Registers the {@link EnumerableArgumentFactory} and {@link EnumerableColumnMapperFactory} with the provided * {@link Jdbi} instance. * * @param jdbi The JDBI instance to register the {@code Enumerable} mappings for. */ @Override public void customizeJdbi(Jdbi jdbi) { jdbi.getConfig(Arguments.class).register(new EnumerableArgumentFactory()); jdbi.getConfig(ColumnMappers.class).register(new EnumerableColumnMapperFactory()); } }
36.152174
114
0.734817
5d263dc6d3b5e8dfb54027be5b91a2962b80e00a
4,818
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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 co.elastic.apm.agent.testinstr; import co.elastic.apm.agent.bci.TracerAwareInstrumentation; import co.elastic.apm.agent.sdk.state.GlobalVariables; import co.elastic.apm.agent.sdk.weakconcurrent.DetachedThreadLocal; import co.elastic.apm.agent.sdk.weakconcurrent.WeakConcurrent; import net.bytebuddy.asm.Advice; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.matcher.ElementMatcher; import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static net.bytebuddy.matcher.ElementMatchers.named; public abstract class SystemEnvVariableInstrumentation extends TracerAwareInstrumentation { private static final DetachedThreadLocal<Map<String, String>> customEnvVariablesTL = GlobalVariables .get(SystemEnvVariableInstrumentation.class, "customEnvVariables", WeakConcurrent.<Map<String, String>>buildThreadLocal()); private static final String NULL_ENTRY = "null"; /** * Sets custom env variables that will be added to the actual env variables returned by {@link System#getenv()} or * {@link System#getenv(String)} on the current thread. Entries with {@literal null} values will allow to emulate * when those environment variables are not set. * <p> * NOTE: caller must clear the custom variables when they are not required anymore through {@link #clearCustomEnvVariables()}. * * @param customEnvVariables a map of key-value pairs that will be appended to the actual environment variables * returned by {@link System#getenv()} on the current thread */ public static void setCustomEnvVariables(Map<String, String> customEnvVariables) { Map<String, String> map = new HashMap<>(); for (Map.Entry<String, String> entry : customEnvVariables.entrySet()) { String value = entry.getValue(); if (value == null) { value = NULL_ENTRY; } map.put(entry.getKey(), value); } customEnvVariablesTL.set(map); } protected static Map<String, String> getCustomEnvironmentMap(Map<String, String> originalValues) { Map<String, String> customMap = customEnvVariablesTL.get(); if (customMap == null) { return originalValues; } Map<String, String> map = new HashMap<>(originalValues); for (Map.Entry<String, String> entry : customMap.entrySet()) { String value = entry.getValue(); //noinspection StringEquality if (value == null || value == NULL_ENTRY) { map.remove(entry.getKey()); } else { map.put(entry.getKey(), entry.getValue()); } } return map; } protected static String getCustomEnvironmentEntry(String key, @Nullable String originalValue) { Map<String, String> customMap = customEnvVariablesTL.get(); if (customMap == null) { return originalValue; } String customValue = customMap.get(key); //noinspection StringEquality if (customValue == NULL_ENTRY) { return null; } else if (customValue != null) { return customValue; } return originalValue; } public static void clearCustomEnvVariables() { customEnvVariablesTL.remove(); } @Override public ElementMatcher<? super TypeDescription> getTypeMatcher() { return named("java.lang.System"); } @Override public Collection<String> getInstrumentationGroupNames() { return Collections.emptyList(); } public static class AdviceClass { @Advice.AssignReturned.ToReturned @Advice.OnMethodExit(onThrowable = Throwable.class, inline = false) public static Map<String, String> alterEnvVariables(@Advice.Return Map<String, String> ret) { return getCustomEnvironmentMap(ret); } } }
38.854839
131
0.683064
894f5671dd84a3746683f3a9a7f36c29f63a4747
844
package com.example.threadpool; public class TestThreadPoolManager { public static void main(String[] args) { ThreadPoolManager poolManager = new ThreadPoolManager(10); poolManager.submitTask(new Runnable() { @Override public void run() { System.out.println("Starting Task A...."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Task A Completed...."); } }); poolManager.submitTask(new Runnable() { @Override public void run() { System.out.println("Starting Task B...."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Task B Completed...."); } }); } }
21.1
61
0.572275
ce071016f27cf164a95df6e0e79acebc9b77ca3b
388
package expression.constParser; import expression.myNumber.LongNumber; import expression.myNumber.MyNumber; public class LongConstParser implements ConstParser<Long> { @Override public MyNumber<Long> parse(String data) { return new LongNumber(Long.valueOf(data)); } @Override public MyNumber<Long> convert(int x) { return new LongNumber(x); } }
22.823529
59
0.713918
34f5d05d31c279be73681de848a4f355eee21d9b
1,338
package com.spring.cloud.transaction.api; import com.spring.cloud.transaction.api.repository.GoodsRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; 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.RestController; /** * @Author: 赵小超 * @Date: 2019/1/17 21:30 * @Description: */ @Slf4j @RestController public class GoodsController { @Autowired private GoodsRepository repository; @GetMapping(value = "/all") public Object getAll() { return repository.findAll(); } @GetMapping(value = "/{goodsId}") public Object getOne(@PathVariable int goodsId) { return repository.findById(goodsId).get(); } @Transactional @PutMapping(value = "/consumption/{goodsId}") public Object consumption(@PathVariable int goodsId, int count) throws Exception { int i = repository.consumption(goodsId, count); if (i != 1) { log.error("库存不足"); throw new Exception("库存不足"); } return "OK"; } }
29.733333
87
0.685351
f59d2fceab150d449d202ccc8181d26d040e2841
784
package com.github.dwaite.cyborg.electrode; public class CborException extends Exception { private static final long serialVersionUID = 1L; public CborException() { super(); // TODO Auto-generated constructor stub } public CborException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public CborException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public CborException(String message) { super(message); // TODO Auto-generated constructor stub } public CborException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
25.290323
111
0.762755
2d1c2628475f3221b156dfdcc4479af707883805
14,425
package org.example.work.fingerprint; import org.example.uitl.Keys; import org.example.kit.entity.ByteArray; import org.example.kit.io.ByteBuilder; import org.example.work.eigenword.EigenWord; import org.example.work.eigenword.ExtractEigenWord; import org.example.work.parse.Tag; import org.example.work.parse.nodes.Document; import org.example.work.parse.nodes.Element; import org.example.work.parse.nodes.Node; import org.example.work.parse.nodes.TextNode; import java.util.*; /** * @Classname ExtractFingerprint * @Description 提取指纹 * @Date 2020/11/2 19:36 * @Created by shuaif */ public class ExtractFingerprint { private static final int REQUEST_TAG = 0; private static final int RESPONSE_TAG = 1; private static final int HTML_HEAD_TAG = 2; private static final int HTML_BODY_TAG = 3; public static final int max_child_number_threshold = 200; public static final int max_parse_depth = 6; /** * BKDR算法实现,将字节数组映射为一个一个字节【辅助】 * @param byteArray 字节数组对应的字符串 * @return 字节 */ private static byte hashTo1Byte(String byteArray){ int hash = 1; for (byte b : byteArray.getBytes()) { hash = 31 * hash + b; } hash ^= hash >> 16; hash ^= hash >> 8; return (byte)hash; } /** * 构造指纹:指纹头(4bits标志位,12bits指纹体长度) + 指纹体【辅助】 * @param choice 标志位(0,1,2,3) * @param origin_fingerprint 原始指纹 * @return 指纹 */ public static byte[] constructFingerprint(int choice,byte[] origin_fingerprint){ byte flag = (byte)(choice << 4); byte length; // System.out.println("part fp size : " + origin_fingerprint.length); if (origin_fingerprint.length < 256) { length = (byte) (origin_fingerprint.length); } else { length = (byte) (0xFF & origin_fingerprint.length); flag = (byte) (flag ^ (origin_fingerprint.length >> 8)); } byte[] result = new byte[origin_fingerprint.length + 2]; result[0] = flag; result[1] = length; System.arraycopy(origin_fingerprint,0,result,2,origin_fingerprint.length); return result; } /** * 提取请求报头部指纹,主要针对cookie名字做处理 * @param cookie 请求头部的COOKIE字段值 */ public static byte[] handleRequestHeader(String cookie){ //TODO 爬虫获取网页响应的时候并没有提供cookie怎么获取。 byte[] result; String[] key_value = cookie.split(";"); result = new byte[key_value.length]; int i = 0; for (String key : key_value) { result[i] = hashTo1Byte(key); i++; } return constructFingerprint(REQUEST_TAG,result); } /** * 提取响应报文头部指纹,针对响应头部的键值对,对需要提取指纹的部分(包括key和value做指纹提取 * @param response_header 请求头部键值对 */ public static byte[] handleResponseHeader(String response_header){ // 头部字段处理 List<String> all_keys_list = new ArrayList<>(Arrays.asList(Keys.RESPONSE_HEADERS)); List<String> value_used_list = new ArrayList<>(Arrays.asList(Keys.RESPOSE_VALUE_USED)); List<String> key_not_used_list = new ArrayList<>(Arrays.asList(Keys.RESPONSE_KEY_NOT_USED)); // 获取头部键值对,用“:”分割 byte[] result = new byte[1024]; int i = 0; // index索引 String[] key_value = response_header.split("\r\n"); for (String s : key_value) { if (!s.contains("HTTP/")) { String[] split = s.split(":"); String key = split[0]; String value = split[1]; if (all_keys_list.contains(key)) { if (!key_not_used_list.contains(key)) { // 所有不提取key字段的也不提取value字段 result[i++] = hashTo1Byte(key); if (value_used_list.contains(key)) { // 判断是否需要提取首部值 result[i++] = hashTo1Byte(value); } } } else { // 扩展首部使用key result[i++] = hashTo1Byte(key); } } } return constructFingerprint(RESPONSE_TAG,new ByteArray(result,0,i).getBytes()); } /** * 对url字段去除host子串之后提取一个hash值 * @param byteArray URL * @return hash_to_1_byte */ private static byte urlHashTo1Byte(String byteArray) { if (byteArray.contains("http")) { String[] splits = byteArray.split("/"); StringBuilder val = new StringBuilder(); for (int i = 2; i < splits.length; i++) { val.append(splits[i]); } return hashTo1Byte(val.substring(0)); } return hashTo1Byte(byteArray); } /** * 根据key值获取ID值,针对HTML head部分的指纹提取 * @param key KEY * @return index */ private static int getIDKey(String key) { key = key.toLowerCase(); for (int i = 0; i < Keys.HEAD_PROPERTIES.length; i++) { if (key.equals(Keys.HEAD_PROPERTIES[i].toLowerCase())) { return i + 1; } } return -1; } static byte byteHash(ByteArray data){ if(data == null) return 0; int hash = data.hashCode(); hash ^= hash >>> 16; hash ^= hash >>> 8; return (byte)hash; } /** * 获取网页head部分的指纹,html_head部分类似于request_header部分的键值对 【IDkeyi, hash(value)】 * @param html_head head部分的DOM结构 */ public static byte[] handleHtmlHeader(Element html_head){ byte[] result = new byte[1024]; int i = 0; // index索引 // System.out.println(html_head.childrenSize()); if (html_head == null) { return new byte[0]; } for (Node node : html_head.children()) { if (!(node instanceof Element)) { continue; } Element element = (Element)node; Tag tag = element.getTag(); // System.out.println(tag.getName()); switch (tag.getName()) { case "meta": // 元数据通常以名称/值存在,如果没有name属性值,那么键值对可能以http-equiv的形式存在 ByteArray key = element.attr("name"); if (key == null) { key = element.attr("http-equiv"); } if (key == null) { // !name and !http-equiv 查看charset字段 ByteArray charset = element.attr("charset"); if (charset == null) { byte[] temp = element.attrs().length > 1 ? element.attrs()[0].getKey() : new byte[]{-1}; } } else { ByteArray content = element.attr("content"); int id = getIDKey(key.toStr()); result[i++] = (byte) (id == -1 ? (byteHash(key) | 0x80) : id); // if (content != null) // change // result[i++] = hashTo1Byte(content.toStr()); } case "link": ByteArray rel = element.attr("rel"); if (rel == null) { rel = element.attrs().length > 1 ? element.attrs()[0].getValue() : new ByteArray(new byte[]{-1}); } int id = getIDKey(rel.toStr().toLowerCase()); result[i++] = (byte) (id == -1 ? (byteHash(rel) | 0x80) : id); ByteArray href = element.attr("href"); if (href == null) { break; } result[i++] = urlHashTo1Byte(href.toStr()); case "title": result[i++] = (byte) 2; break;// 不提取 case "style": result[i++] = (byte) 1; if (element.hasChild()) { Node child = element.child(0); if (child instanceof TextNode) { result[i++] = hashTo1Byte(((TextNode) child).getText().toStr()); } } case "noscript": //TODO break; case "script": result[i++] = (byte) 3; ByteArray val = element.attr("src"); if (val != null) { // 标签有src属性,进行指纹提取 result[i++] = urlHashTo1Byte(val.toStr()); } break; default: result[i++] = (byte) element.getTagName().hashCode(); } } // System.out.println("i = " + i); return constructFingerprint(HTML_HEAD_TAG,new ByteArray(result,0,i).getBytes()); } /** * 获取网页body部分的指纹,html_body部分的指纹为树形指纹 * 标签节点[1bit 7bits tagID][1bit 7bits class hash],第一个1bit表示该节点是被否在其兄弟节点中最大,第二个1bit表示是否有孩子节点 * 文本节点[1bit 7bit 0x00][8bits text hash] * @param html_body body部分的DOM结构 * @param vector 网页特征向量 */ public static byte[] handleHtmlBody(Element html_body, List<EigenWord> vector){ if (html_body == null) { System.out.println("HTML Body is null"); return new byte[0]; } byte[] result = new byte[4096]; int i = 0; int oldi = i; Queue<Node> queue = new LinkedList<>(); // 队列用于层序遍历 Node[] leaf_nodes = new Node[0]; // 存放解析最大深度时候的所有节点(相当于叶子节点),用于特征词提取 queue.offer(html_body); // next_level存放下层节点数,to_be_access存放当前层待访问节点数,node_count记录总访问节点数,用于判断阈值(此间为200) int next_level = 0,to_be_access = 1, node_count = to_be_access; while (!queue.isEmpty()) { Node temp = queue.poll(); if (temp instanceof Element) { // 对元素节点进行操作 Element cur_elment = (Element)temp; int id = cur_elment.getTag().getId(); result[i++] = (byte) ((temp == temp.getParent().lastChild() ? 1<<7 : 0) | (id | 0x80)); // 从高到低前4位为class值的hash, 后4位为父元素在其兄弟节点的索引位置 ByteArray cssCLass = cur_elment.attr("class"); result[i++] = (byte) ((cur_elment.childrenSize() == 0 ? 0 : 1<<7) | (byteHash(cssCLass) | 0x80)); temp.setHashCode(result[i] << 8); int child_count = 0; boolean add_children = true; for (Node child : cur_elment.children()) { if (child instanceof TextNode || ((Element)child).getTag().isContentLevel()) // 记录文本相关节点个数 child_count++; } if (child_count > 3 && child_count > cur_elment.childrenSize() >> 1) { // 文本节点的数量超过三,大量文本后续不做 add_children = false; } if (add_children) { child_count = 0; for (Node child : cur_elment.children()) { queue.offer(child); child_count++; node_count++; if ((child_count > 29 || node_count > max_child_number_threshold) && child_count < cur_elment.childrenSize()) { // 节点个数太多,退出当前循环 if (child_count > 1) { queue.offer(cur_elment.lastChild()); child_count++; } break; } } next_level += child_count; } } else if (temp instanceof TextNode) { // 对文本节点提取指纹 TextNode text = (TextNode)temp; result[i++] = (byte) (temp == temp.getParent().lastChild() ? 1 << 7:0); result[i++] = hashTo1Byte(text.getText().toStr()); temp.setHashCode(result[i] << 8); } to_be_access--; // 更新待访问节点数目 if (to_be_access == 0) { to_be_access = next_level; next_level = 0; if (i-oldi >= 12) { // 指纹序列长度大于某阈值,进行指纹提取。 // TODO 提取一个特征词 byte[] seq = new ByteArray(result,oldi,i).getBytes(); vector.add(new EigenWord(ExtractEigenWord.hashTo60Bits(seq) ^ (ExtractEigenWord.BODY_LEVEL_TAG << 60))); } oldi = i; if (temp.getDepth() + 1 == max_parse_depth) { // 提取所有最大解析深度处的叶子节点,用于路径特征词提取 leaf_nodes = queue.toArray(new Node[0]); } } } // TODO 特征词提取 List<EigenWord> words = ExtractEigenWord.getBodyTreeEigenWord(html_body, leaf_nodes, max_parse_depth); if (words != null && words.size() != 0) vector.addAll(words); return constructFingerprint(HTML_BODY_TAG,new ByteArray(result,0,i).getBytes()); } /** * 提取指纹调度 (只用于测试输出指纹进行比较) * @param requestHeader 请求头部 * @param responseHeader 响应头部 * @param document 网页文档--包含解析出来的DOM树(HTML元素为根节点) */ public static byte[] extractFingerprint(ByteArray requestHeader, ByteArray responseHeader, Document document) { ByteBuilder fingerprint; byte[] request_fingerprint = new byte[0], response_fingerprint = new byte[0], html_head_fingerprint = new byte[0], html_body_fingerprint = new byte[0]; if (requestHeader != null) { // TODO 提取cookie字段 } if (responseHeader != null) { response_fingerprint = ExtractFingerprint.handleResponseHeader(new String(responseHeader.getBytes())); } if (document != null) { html_head_fingerprint = ExtractFingerprint.handleHtmlHeader(document.getHtml().childElement("head")); html_body_fingerprint = ExtractFingerprint.handleHtmlBody(document.getHtml().childElement("body"),new ArrayList<>()); } int length = request_fingerprint.length + response_fingerprint.length + html_head_fingerprint.length + html_body_fingerprint.length; fingerprint = new ByteBuilder(length); fingerprint.write(request_fingerprint); fingerprint.write(response_fingerprint); fingerprint.write(html_head_fingerprint); fingerprint.write(html_body_fingerprint); // Fingerprint fp = new Fingerprint(); // fp.setLastUpdate(new Timestamp(System.currentTimeMillis())); // // fp.setFpdata(fingerprint.getBytes()); return fingerprint.getBytes(); } }
39.629121
159
0.527556
6241fd7313f0d57b6c113b1610b4940adfde7afa
8,462
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicemix.jbi.messaging; import java.net.URI; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.concurrent.atomic.AtomicBoolean; import javax.jbi.messaging.InOnly; import javax.jbi.messaging.InOptionalOut; import javax.jbi.messaging.InOut; import javax.jbi.messaging.MessageExchange; import javax.jbi.messaging.MessageExchangeFactory; import javax.jbi.messaging.MessagingException; import javax.jbi.messaging.RobustInOnly; import javax.jbi.servicedesc.ServiceEndpoint; import javax.xml.namespace.QName; import org.apache.servicemix.JbiConstants; import org.apache.servicemix.id.IdGenerator; import org.apache.servicemix.jbi.framework.ComponentContextImpl; /** * Resolver for URI patterns * * @version $Revision$ */ public class MessageExchangeFactoryImpl implements MessageExchangeFactory { private QName interfaceName; private QName serviceName; private QName operationName; private ServiceEndpoint endpoint; private IdGenerator idGenerator; private ComponentContextImpl context; private AtomicBoolean closed; /** * Constructor for a factory * * @param idGen */ public MessageExchangeFactoryImpl(IdGenerator idGen, AtomicBoolean closed) { this.idGenerator = idGen; this.closed = closed; } protected void checkNotClosed() throws MessagingException { if (closed.get()) { throw new MessagingException("DeliveryChannel has been closed."); } } /** * Create an exchange from the specified pattern * * @param pattern * @return MessageExchange * @throws MessagingException */ public MessageExchange createExchange(URI pattern) throws MessagingException { checkNotClosed(); MessageExchange result = null; if (pattern != null) { if (pattern.equals(MessageExchangeSupport.IN_ONLY) || pattern.equals(MessageExchangeSupport.WSDL2_IN_ONLY)) { result = createInOnlyExchange(); } else if (pattern.equals(MessageExchangeSupport.IN_OUT) || pattern.equals(MessageExchangeSupport.WSDL2_IN_OUT)) { result = createInOutExchange(); } else if (pattern.equals(MessageExchangeSupport.IN_OPTIONAL_OUT) || pattern.equals(MessageExchangeSupport.WSDL2_IN_OPTIONAL_OUT)) { result = createInOptionalOutExchange(); } else if (pattern.equals(MessageExchangeSupport.ROBUST_IN_ONLY) || pattern.equals(MessageExchangeSupport.WSDL2_ROBUST_IN_ONLY)) { result = createRobustInOnlyExchange(); } } if (result == null) { throw new MessagingException("Do not understand pattern: " + pattern); } return result; } /** * create InOnly exchange * * @return InOnly exchange * @throws MessagingException */ public InOnly createInOnlyExchange() throws MessagingException { checkNotClosed(); InOnlyImpl result = new InOnlyImpl(getExchangeId()); setDefaults(result); return result; } /** * create RobustInOnly exchange * * @return RobsutInOnly exchange * @throws MessagingException */ public RobustInOnly createRobustInOnlyExchange() throws MessagingException { checkNotClosed(); RobustInOnlyImpl result = new RobustInOnlyImpl(getExchangeId()); setDefaults(result); return result; } /** * create InOut Exchange * * @return InOut exchange * @throws MessagingException */ public InOut createInOutExchange() throws MessagingException { checkNotClosed(); InOutImpl result = new InOutImpl(getExchangeId()); setDefaults(result); return result; } /** * create InOptionalOut exchange * * @return InOptionalOut exchange * @throws MessagingException */ public InOptionalOut createInOptionalOutExchange() throws MessagingException { checkNotClosed(); InOptionalOutImpl result = new InOptionalOutImpl(getExchangeId()); setDefaults(result); return result; } /** * Create an exchange that points at an endpoint that conforms to the * declared capabilities, requirements, and policies of both the consumer * and the provider. * * @param svcName * @param opName * the WSDL name of the operation to be performed * @return a message exchange that is initialized with given interfaceName, * operationName, and the endpoint decided upon by JBI. * @throws MessagingException */ public MessageExchange createExchange(QName svcName, QName opName) throws MessagingException { // TODO: look for the operation in the wsdl and infer the MEP checkNotClosed(); InOptionalOutImpl me = new InOptionalOutImpl(getExchangeId()); setDefaults(me); me.setService(svcName); me.setOperation(opName); return me; } protected String getExchangeId() { return idGenerator.generateId(); } /** * @return endpoint */ public ServiceEndpoint getEndpoint() { return endpoint; } /** * set endpoint * * @param endpoint */ public void setEndpoint(ServiceEndpoint endpoint) { this.endpoint = endpoint; } /** * @return interface name */ public QName getInterfaceName() { return interfaceName; } /** * set interface name * * @param interfaceName */ public void setInterfaceName(QName interfaceName) { this.interfaceName = interfaceName; } /** * @return service name */ public QName getServiceName() { return serviceName; } /** * set service name * * @param serviceName */ public void setServiceName(QName serviceName) { this.serviceName = serviceName; } /** * @return Returns the operationName. */ public QName getOperationName() { return operationName; } /** * @param operationName * The operationName to set. */ public void setOperationName(QName operationName) { this.operationName = operationName; } /** * Get the Context * * @return the context */ public ComponentContextImpl getContext() { return context; } /** * Set the Context * * @param context */ public void setContext(ComponentContextImpl context) { this.context = context; } protected void setDefaults(MessageExchangeImpl exchange) { exchange.setOperation(getOperationName()); if (endpoint != null) { exchange.setEndpoint(getEndpoint()); } else { exchange.setService(serviceName); exchange.setInterfaceName(interfaceName); } if (getContext() != null) { exchange.setSourceContext(getContext()); PojoMarshaler marshaler = getContext().getActivationSpec().getMarshaler(); if (marshaler != null) { exchange.setMarshaler(marshaler); } } exchange.setProperty(JbiConstants.DATESTAMP_PROPERTY_NAME, new PrettyCalendar()); } @SuppressWarnings("serial") public static class PrettyCalendar extends GregorianCalendar { public String toString() { return new SimpleDateFormat().format(getTime()); } } }
29.280277
126
0.649846
7ae189d21cad55b0392e0ddb05f31bae0b058996
673
package cn.mypandora.springboot.modular.system.model.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Login * * @author hankaibo * @date 2019/10/26 */ @ApiModel(value = "登录对象", description = "用户登录页面对象。") @Data @NoArgsConstructor @AllArgsConstructor public class Login { /** * 用户名称 */ @ApiModelProperty(value = "用户名称", required = true) private String username; /** * 用户密码 */ @ApiModelProperty(value = "用户密码", required = true) private String password; }
20.393939
57
0.661218
695076962ff1c7f3b978ff31676e8b79ad732584
161
package com.h5190077.can_caglar_kirici_final.application; import android.app.Application; public class KitaplarApplication extends android.app.Application { }
23
66
0.850932
3ebf947882d5ad3103c1712aa02ad1d6d23a873d
2,410
package org.ka.menkins.app; import com.hazelcast.core.ITopic; import io.prometheus.client.exporter.MetricsServlet; import lombok.extern.slf4j.Slf4j; import org.ka.menkins.app.init.AppConfig; import org.ka.menkins.storage.NodeRequest; import org.ka.menkins.storage.NodeRequestWithResources; import spark.Spark; import java.util.concurrent.BlockingQueue; import static spark.Spark.awaitInitialization; import static spark.Spark.delete; import static spark.Spark.get; import static spark.Spark.halt; import static spark.Spark.path; import static spark.Spark.port; import static spark.Spark.post; @Slf4j public class HttpServer { public static Runnable newInitializer(AppConfig config, BlockingQueue<NodeRequestWithResources> queue, ITopic<String> terminateTaskRequests) { return () -> { log.info("Starting http server"); port(config.getHttp().getPort()); path("/api/v1", () -> { post("/node", "application/json", ((request, response) -> { Metrics.Requests.total.inc(); var node = Json.from(request.bodyAsBytes(), NodeRequest.class); node.validate(); var added = queue.add(NodeRequestWithResources.from(node)); if (!added) { halt(500, "request " + node.getId() + " cannot be added to global queue"); } return ""; })); delete("/node/:id", (request, response) -> { Metrics.Requests.total.inc(); var id = request.params(":id"); terminateTaskRequests.publish(id); return "accepted"; }); }); get("/health", ((request, response) -> "up")); var metrics = new MetricsServlet(); get("/prometheus", ((request, response) -> { metrics.service(request.raw(), response.raw()); return ""; })); awaitInitialization(); log.info("Http server started"); }; } public static Runnable finalizeHttp() { return () -> { log.info("stopping http server"); Spark.awaitStop(); log.info("http server stopped"); }; } private HttpServer() {} }
33.013699
106
0.554772
af6c2de57b2f90ec868e7557d144173f0f068a5b
8,792
/** * * The MIT License * * Copyright 2018-2021 Paul Conti * * 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 builder.common; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.imageio.ImageIO; import builder.controller.Controller; import builder.prefs.GeneralEditor; import builder.prefs.GridEditor; import java.util.Base64; /** * The Class CommonUtils is a catch all for useful routines that don't seem to fit * in any other classes. * * @author Paul Conti * */ public class CommonUtils { /** The instance. */ private static CommonUtils instance = null; /** Backup Folder Name. */ private static final String BACKUP_FOLDER = "gui_backup"; /** * getInstance() - get our Singleton Object. * * @return instance */ public static synchronized CommonUtils getInstance() { if (instance == null) { instance = new CommonUtils(); } return instance; } /** * empty constructor. */ public CommonUtils() { } /** * fitToGrid() - Remaps coordinates to fit on our design canvas and stay inside * the margins. Doesn't handle widgets if they are too large to fit. * * @param x * the x * @param y * the y * @param widgetWidth * the widget width * @param widgetHeight * the widget height * @return p */ public Point fitToGrid(int x, int y, int widgetWidth, int widgetHeight) { GeneralEditor ed = GeneralEditor.getInstance(); int margins = ed.getMargins(); int canvas_width = Controller.getProjectModel().getWidth() - margins; int canvas_height = Controller.getProjectModel().getHeight() - margins; // force the new Coordinates fit on our canvas and inside the margins if ((x + widgetWidth) > canvas_width) x = canvas_width - widgetWidth; if (x < margins) x = margins; if ((y + widgetHeight) > canvas_height) y = canvas_height - widgetHeight; if (y < margins) y = margins; Point p = new Point(x, y); return p; } /** * snapToGrid() - Remaps coordinates to our nearest grid line. * * @param x * the x * @param y * the y * @return p */ public Point snapToGrid(int x, int y) { GridEditor ed = GridEditor.getInstance(); // check for snap to grid if (ed.getGridSnapTo()) { x = (x / ed.getGridMinorWidth()) * ed.getGridMinorWidth(); y = (y / ed.getGridMinorHeight()) * ed.getGridMinorHeight(); } Point p = new Point(x, y); return p; } /** * createElemName - Create Element Reference Name * strips "$" off of key to find number and adds the * number to the element reference name. * * @param key * the key * @param refName * the element reference name * @return the <code>String</code> with the new element ref name */ static public String createElemName(String key, String refName) { // first test to see if we have a ElementRef name if (refName == null || refName.isEmpty()) return new String(""); // We have one, now strip off the number from the key String sCount = ""; int n = key.indexOf("$"); sCount = key.substring(n+1); /* now check the refName and determine if it has a number * at the end. When we create elementrefs * we use the key number at the end but users * can and will add numbers themselves. * So if we find a number we will add "_keycount" * instead of simply "keycount". * This will only happen during a paste operation. */ int i = refName.length()-1; if(Character.isDigit(refName.charAt(i))) { return new String(refName + "_" + sCount); } return new String(refName + sCount); } /** * encodeToString() - . * * @param image * the image * @return imageString */ public String encodeToString(BufferedImage image) { String imageString = null; if (image == null) return ""; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ImageIO.write(image, "bmp", bos); byte[] imageBytes = bos.toByteArray(); imageString = Base64.getEncoder().encodeToString(imageBytes); bos.close(); } catch (IOException e) { e.printStackTrace(); } return imageString; } /** * decodeToImage() - . * * @param imageString * the image string * @return image */ public BufferedImage decodeToImage(String imageString) { BufferedImage image = null; byte[] imageByte; try { imageByte = Base64.getDecoder().decode(imageString); ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); image = ImageIO.read(bis); bis.close(); } catch (Exception e) { e.printStackTrace(); } return image; } /** * getWorkingDir - attempts to find the directory where our executable is * running. * * @return workingDir - our working directory */ public String getWorkingDir() { // The code checking for "lib" is to take care of the case // where we are running not inside eclipse IDE String workingDir; String strUserDir = System.getProperty("user.dir"); int n = strUserDir.indexOf("lib"); if (n > 0) { strUserDir = strUserDir.substring(0,n-1); // remove "/bin" } workingDir = strUserDir + System.getProperty("file.separator"); return workingDir; } /** * Backup file. * * @param file * the file */ static public void backupFile(File file) { String newTemplate = null; String backupName = null; File backupFile = null; File newFile = null; if(file.exists()) { // first check to see if we have a backup folder String strBackupDir = file.getParent() + System.getProperty("file.separator") + BACKUP_FOLDER; File backupDir = new File(strBackupDir); if (!backupDir.exists()) { backupDir.mkdir(); } // Make a backup copy of file and overwrite backup file if it exists. backupName = new String(file.getAbsolutePath() + ".bak"); backupFile = new File(backupName); if (backupFile.exists()) { // rename previous backup files so we don't lose them newTemplate = new String(strBackupDir + System.getProperty("file.separator") + file.getName() + ".##"); int idx = 0; String newName = newTemplate + String.valueOf(++idx); newFile = new File(newName); while (newFile.exists()) { newName = newTemplate + String.valueOf(++idx); newFile = new File(newName); } backupFile.renameTo(newFile); } copyFile(file, backupFile); } } /** * Copy file. * * @param inFile * the in file * @param outFile * the out file */ static public void copyFile(File inFile, File outFile) { InputStream inStream = null; OutputStream outStream = null; try{ inStream = new FileInputStream(inFile); outStream = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); // System.out.println("File is copied successfully!"); }catch(IOException e){ e.printStackTrace(); } } }
28.732026
84
0.636601
c936d2750ad10f3c12abeeb5bcc1b8f17f79d1b5
530
package net.minecraft.state.properties; import net.minecraft.util.IStringSerializable; public enum RedstoneSide implements IStringSerializable { UP("up"), SIDE("side"), NONE("none"); private final String name; private RedstoneSide(String name) { this.name = name; } public String toString() { return this.getString(); } public String getString() { return this.name; } public boolean func_235921_b_() { return this != NONE; } }
16.060606
55
0.611321
6ad183f6cea066e33136d90ed7cc89f96f9079c8
2,595
package com.mtons.mblog.web.controller.site.auth; import com.mtons.mblog.base.lang.Consts; import com.mtons.mblog.base.lang.Result; import com.mtons.mblog.modules.data.AccountProfile; import com.mtons.mblog.modules.data.UserVO; import com.mtons.mblog.modules.service.MailService; import com.mtons.mblog.modules.service.SecurityCodeService; import com.mtons.mblog.modules.service.UserService; import com.mtons.mblog.web.controller.BaseController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; /** * @author langhsu on 2015/8/14. */ @RestController @RequestMapping("/email") public class EmailController extends BaseController { @Autowired private UserService userService; @Autowired private MailService mailService; @Autowired private SecurityCodeService securityCodeService; private static final String EMAIL_TITLE = "[{0}]您正在使用邮箱安全验证服务"; @GetMapping("/send_code") public Result sendCode(String email, @RequestParam(name = "type", defaultValue = "1") Integer type) { Assert.hasLength(email, "请输入邮箱地址"); Assert.notNull(type, "缺少必要的参数"); String key = email; switch (type) { case Consts.CODE_BIND: AccountProfile profile = getProfile(); Assert.notNull(profile, "请先登录后再进行此操作"); key = String.valueOf(profile.getId()); UserVO exist = userService.getByEmail(email); Assert.isNull(exist, "该邮箱已被使用"); break; case Consts.CODE_FORGOT: UserVO user = userService.getByEmail(email); Assert.notNull(user, "账户不存在"); key = String.valueOf(user.getId()); break; case Consts.CODE_REGISTER: key = email; break; } String code = securityCodeService.generateCode(key, type, email); Map<String, Object> context = new HashMap<>(); context.put("code", code); String title = MessageFormat.format(EMAIL_TITLE, siteOptions.getValue("site_name")); mailService.sendTemplateEmail(email, title, Consts.EMAIL_TEMPLATE_CODE, context); return Result.successMessage("邮件发送成功"); } }
35.547945
105
0.687861
1982cce5c09de2fa028306489e5f8e838d4c4ba5
596
package com.systemmeltdown.robotlog.topics; import com.systemmeltdown.robotlog.lib.Utils; /** * Logs integers as a data topic. */ public class IntegerTopic extends DataTopic { private final int m_roundingFactor; public IntegerTopic(final String name, final int roundingFactor) { super(name, Integer.class); m_roundingFactor = roundingFactor; } public void log(final int value) { log(value, System.nanoTime()); } public void log(final int value, final long nanos) { final int roundedValue = Utils.roundByFactor(value, m_roundingFactor); super.log(roundedValue, nanos); } }
23.84
72
0.753356
7685edc2a7221e7e1040d39dfc02e4e2080905e9
1,308
package tw.waterball.judgegirl.academy.domain.usecases.group; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import tw.waterball.judgegirl.academy.domain.exceptions.DuplicateGroupNameException; import tw.waterball.judgegirl.academy.domain.repositories.GroupRepository; import tw.waterball.judgegirl.primitives.exam.Group; import javax.inject.Named; /** * @author - wally55077@gmail.com * @author - johnny850807@gmail.com (Waterball) */ @Named public class CreateGroupUseCase extends AbstractGroupUseCase { public CreateGroupUseCase(GroupRepository groupRepository) { super(groupRepository); } public void execute(Request request, Presenter presenter) throws DuplicateGroupNameException { Group group = new Group(request.name); groupNameShouldBeDistinct(group); presenter.showGroup(groupRepository.save(group)); } private void groupNameShouldBeDistinct(Group group) throws DuplicateGroupNameException { if (groupRepository.existsByName(group.getName())) { throw new DuplicateGroupNameException(); } } public interface Presenter { void showGroup(Group group); } @NoArgsConstructor @AllArgsConstructor public static class Request { public String name; } }
29.727273
98
0.745413
317d1b9a716b1bbe9aaa1fba7031ce43683c1cd5
2,027
package com.ucm.informatica.spread.Data; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.LocationManager; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import com.ucm.informatica.spread.Utils.CustomLocationListener; import static android.support.constraint.Constraints.TAG; public class LocationService extends Service{ private static final int LOCATION_INTERVAL = 5000; private static final float LOCATION_DISTANCE = 10; private CustomLocationListener locationListener; private LocationManager locationManager; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override public void onCreate() { initializeLocationManager(); try { locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, locationListener); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, locationListener); } catch (SecurityException | IllegalArgumentException e) { Log.e("LOCATION SERVICE", e.getMessage()); } } private void initializeLocationManager() { Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: "+ LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE); if (locationManager == null) { locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); } locationListener = new CustomLocationListener(getApplicationContext()); } }
34.355932
134
0.723236
3e09cacbbd93c1f37dd237e86f0b2925fcc266b5
1,612
package com.github.vvorks.builder.server.extender; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.github.vvorks.builder.common.lang.Strings; import com.github.vvorks.builder.server.domain.ClassContent; import com.github.vvorks.builder.server.domain.FieldContent; import com.github.vvorks.builder.server.domain.QueryContent; import com.github.vvorks.builder.server.grammar.ExprParser; import com.github.vvorks.builder.server.mapper.QueryMapper; @Component public class QueryExtender { private SqlWriter sqlWriter = SqlWriter.get(); @Autowired private QueryMapper queryMapper; @Autowired private ClassExtender classExtender; public String getTitleOrName(QueryContent q) { if (!Strings.isEmpty(q.getTitle())) { return q.getTitle(); } else { return q.getQueryName(); } } public String getUpperName(QueryContent q) { return Strings.toFirstUpper(q.getQueryName()); } public List<ClassExtender.JoinInfo> getJoins(QueryContent q) { return classExtender.getJoins(queryMapper.getOwner(q)); } public String getSqlExpr(QueryContent q) { ClassContent cls = queryMapper.getOwner(q); ClassExtender.ExprInfo info = classExtender.referExpr(cls, q.getFilter(), ExprParser.CODE_TYPE_WHERE); return info.getExpr().accept(sqlWriter, null); } public List<FieldContent> getArguments(QueryContent q) { ClassContent cls = queryMapper.getOwner(q); ClassExtender.ExprInfo info = classExtender.referExpr(cls, q.getFilter(), ExprParser.CODE_TYPE_WHERE); return info.getArguments(); } }
29.309091
104
0.7866
c0279b992a8eaa09f6f27310985934a88dc05fa1
4,642
/* * 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 com.anywide.dawdler.clientplug.web.handler; import java.io.PrintWriter; import java.lang.reflect.Method; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.anywide.dawdler.clientplug.annotation.RequestMapping; import com.anywide.dawdler.clientplug.web.bind.RequestMethodProcessor; import com.anywide.dawdler.clientplug.web.interceptor.HandlerInterceptor; import com.anywide.dawdler.clientplug.web.interceptor.InterceptorProvider; import com.anywide.dawdler.clientplug.web.plugs.AbstractDisplayPlug; import com.anywide.dawdler.clientplug.web.plugs.DisplaySwitcher; import com.anywide.dawdler.core.order.OrderData; import com.anywide.dawdler.util.ClassUtil; import com.anywide.dawdler.util.JsonProcessUtil; /** * @author jackson.song * @version V1.0 * @Title AbstractUrlHandler.java * @Description urlHendler父类 * @date 2007年4月18日 * @email suxuan696@gmail.com */ public abstract class AbstractUrlHandler { private final List<OrderData<HandlerInterceptor>> handlerInterceptors = InterceptorProvider .getHandlerInterceptors(); public boolean preHandle(Object target, ViewForward viewForward, RequestMapping requestMapping) throws Exception { if (handlerInterceptors != null) for (OrderData<HandlerInterceptor> handlerInterceptor : handlerInterceptors) { if (!handlerInterceptor.getData().preHandle(target, viewForward, requestMapping)) return false; } return true; } public void postHandle(Object target, ViewForward viewForward, RequestMapping requestMapping, Throwable ex) throws Exception { if (handlerInterceptors != null) { for (int i = handlerInterceptors.size(); i > 0; i--) { handlerInterceptors.get(i - 1).getData().postHandle(target, viewForward, requestMapping, ex); } } } public void afterCompletion(Object target, ViewForward viewForward, RequestMapping requestMapping, Throwable ex) { if (handlerInterceptors != null) { for (int i = handlerInterceptors.size(); i > 0; i--) { handlerInterceptors.get(i - 1).getData().afterCompletion(target, viewForward, requestMapping, ex); } } } public abstract boolean handleUrl(String urishort, String method, boolean isJson, HttpServletRequest request, HttpServletResponse response) throws ServletException; protected boolean invokeMethod(Object target, Method method, RequestMapping requestMapping, ViewForward viewForward, boolean responseBody) throws Throwable { try { if (!preHandle(target, viewForward, requestMapping)) return true; Object result = method.invoke(target, RequestMethodProcessor.process(target, viewForward, method)); if (responseBody && result != null) { HttpServletResponse response = viewForward.getResponse(); PrintWriter out = response.getWriter(); try { if (ClassUtil.isSimpleValueType(result.getClass())) { response.setContentType(AbstractDisplayPlug.MIME_TYPE_TEXT_HTML); out.print(result); out.flush(); } else { response.setContentType(AbstractDisplayPlug.MIME_TYPE_JSON); JsonProcessUtil.beanToJson(out, result); out.flush(); } } finally { out.close(); } return true; } postHandle(target, viewForward, requestMapping, viewForward.getInvokeException()); } catch (Throwable e) { viewForward.setInvokeException(e); } try { if (viewForward.getInvokeException() == null) { DisplaySwitcher.switchDisplay(viewForward); } else { throw viewForward.getInvokeException(); } } catch (Throwable e) { throw e; } finally { afterCompletion(target, viewForward, requestMapping, viewForward.getInvokeException()); } return true; } protected ViewForward createViewForward() { return ViewControllerContext.getViewForward(); } }
36.84127
117
0.758294
bd2e0b9d03c42b15da54da270f850904540fe2a8
3,898
package tsg.mwe; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.BitSet; import java.util.Scanner; import tsg.ParenthesesBlockPennStd.WrongParenthesesBlockException; import tsg.TSNodeLabel; import util.Utility; public class TSG_Frags_MWE_Eval_Inside { static String mwePrefix = "MW"; static int minMweCountToPrint = 10; private static void eval(String workingDir) throws FileNotFoundException, WrongParenthesesBlockException { File outputFile = new File(workingDir + "tsg_mwe_eval.txt"); PrintWriter pw = new PrintWriter(outputFile); String logLikeDir = workingDir + "LogLike/Frags/"; String mpiTotDir = workingDir + "MPI_tot/Frags/"; String insideDir = workingDir + "Inside_ratio/Frags/"; pw.println( "Ass.Meas." + "\t" + "Signature" + "\t" + "Sign.Length" + "\t" + "Tot.Frags" + "\t" + "Tot.MWE" + "\t" + "MWE%1" + "\t" + "MWE%1/2" + "\t" + "MWE%1/3" + "\t" + "MWE%1/4" + "\t" + "MWE%1/5" + "\t" + "MWE%1/6" + "\t" + "MWE%1/7" + "\t" + "MWE%1/8" + "\t" + "MWE%1/9" + "\t" + "MWE%1/10" ); for(File logLikeFragFile : new File(logLikeDir).listFiles()) { String file_name = logLikeFragFile.getName(); if (!file_name.startsWith("frags")) continue; evalFile(logLikeFragFile, pw, "LogLike"); } for(File mpiTotFragFile : new File(mpiTotDir).listFiles()) { String file_name = mpiTotFragFile.getName(); if (!file_name.startsWith("frags")) continue; evalFile(mpiTotFragFile, pw, "MpiTot"); } for(File insideFragFile : new File(insideDir).listFiles()) { String file_name = insideFragFile.getName(); if (!file_name.startsWith("frags")) continue; evalFile(insideFragFile, pw, "InsideRatio"); } pw.close(); System.out.println("Output file: " + outputFile); } private static void evalFile(File evalFile, PrintWriter pw, String assMeas) throws FileNotFoundException, WrongParenthesesBlockException { String file_name = evalFile.getName(); int secondUnderscoreIndex = Utility.indexOf(file_name, '_', 2); int dotIndex = file_name.indexOf('.'); String sign = file_name.substring(secondUnderscoreIndex + 1, dotIndex); int signlength = Integer.parseInt(file_name.substring(secondUnderscoreIndex-1, secondUnderscoreIndex)); Scanner scan = new Scanner(evalFile); BitSet mweIndex = new BitSet(); int countFrags = 0; while(scan.hasNextLine()) { String line = scan.nextLine(); TSNodeLabel frag = TSNodeLabel.newTSNodeLabelStd(line); if (frag.label().startsWith(mwePrefix) || frag.prole()==1 && frag.daughters[0].label().startsWith(mwePrefix)) mweIndex.set(countFrags); countFrags++; } int totMwe = mweIndex.cardinality(); if (totMwe<minMweCountToPrint) return; double[] percentages = getPercentages(countFrags, mweIndex); pw.print( assMeas + "\t" + //"Ass.Meas." sign + "\t" + //"Signature" signlength + "\t" + //"Sign.Length" countFrags + "\t" + //"Tot.Frags" totMwe //"Tot.MWE" ); for(double p : percentages) pw.print("\t" + p); pw.println(); } static double[] getPercentages(int totalFrags, BitSet mweIndex) { double[] result = new double[10]; for(int i=1; i<11; i++) { int fragsPartition = totalFrags/i; BitSet mweIndexPartition = mweIndex.get(0, fragsPartition); double mweTotal = mweIndexPartition.cardinality(); result[i-1] = mweTotal*100/fragsPartition; } return result; } public static void main(String[] args) throws FileNotFoundException, WrongParenthesesBlockException { //eval("/gardner0/data/TSG_MWE/Dutch/LassySmall/frag_MWE_AM_5_100/"); //eval("/gardner0/data/TSG_MWE/Dutch/LassySmall/frag_MWE_AM_2_10/"); eval("/gardner0/data/TSG_MWE/FTB/TreebankFrags/frag_MWE_AM_2_10_noPos/"); //eval("/gardner0/data/TSG_MWE/Dutch/LassySmall/TreebankFrags/frag_MWE_AM_2_10_noPos/"); } }
33.033898
139
0.68394
578fd7fe775de8f0b67d060f89f12f31e5914c98
8,103
package jetbrains.mps.baseLanguage.editor; /*Generated by MPS */ import jetbrains.mps.nodeEditor.menus.substitute.SubstituteMenuBase; import org.jetbrains.annotations.NotNull; import java.util.List; import jetbrains.mps.lang.editor.menus.MenuPart; import jetbrains.mps.openapi.editor.menus.substitute.SubstituteMenuItem; import jetbrains.mps.openapi.editor.menus.substitute.SubstituteMenuContext; import java.util.ArrayList; import jetbrains.mps.lang.editor.menus.substitute.ConstraintsFilteringSubstituteMenuPartDecorator; import jetbrains.mps.lang.editor.menus.EditorMenuDescriptorBase; import jetbrains.mps.smodel.SNodePointer; import jetbrains.mps.lang.editor.menus.substitute.SingleItemSubstituteMenuPart; import org.jetbrains.annotations.Nullable; import org.apache.log4j.Logger; import jetbrains.mps.lang.editor.menus.substitute.DefaultSubstituteMenuItem; import jetbrains.mps.openapi.editor.menus.EditorMenuTraceInfo; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.smodel.action.SNodeFactoryOperations; import org.jetbrains.mps.openapi.language.SConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import org.jetbrains.mps.openapi.language.SContainmentLink; public class TryUniversalStatement_SubstituteMenu extends SubstituteMenuBase { @NotNull @Override protected List<MenuPart<SubstituteMenuItem, SubstituteMenuContext>> getParts(final SubstituteMenuContext _context) { List<MenuPart<SubstituteMenuItem, SubstituteMenuContext>> result = new ArrayList<MenuPart<SubstituteMenuItem, SubstituteMenuContext>>(); result.add(new ConstraintsFilteringSubstituteMenuPartDecorator(new SMP_Action_493d70_a(), CONCEPTS.TryUniversalStatement$$M)); result.add(new ConstraintsFilteringSubstituteMenuPartDecorator(new SMP_Action_493d70_b(), CONCEPTS.TryUniversalStatement$$M)); return result; } @NotNull @Override public List<SubstituteMenuItem> createMenuItems(@NotNull SubstituteMenuContext context) { context.getEditorMenuTrace().pushTraceInfo(); context.getEditorMenuTrace().setDescriptor(new EditorMenuDescriptorBase("default substitute menu for " + "TryUniversalStatement", new SNodePointer("r:00000000-0000-4000-0000-011c895902c3(jetbrains.mps.baseLanguage.editor)", "5181868005210083928"))); try { return super.createMenuItems(context); } finally { context.getEditorMenuTrace().popTraceInfo(); } } private class SMP_Action_493d70_a extends SingleItemSubstituteMenuPart { @Nullable @Override protected SubstituteMenuItem createItem(SubstituteMenuContext _context) { Item item = new Item(_context); String description; try { description = "Substitute item: " + item.getMatchingText(""); } catch (Throwable t) { Logger.getLogger(getClass()).error("Exception while executing getMatchingText() of the item " + item, t); return null; } _context.getEditorMenuTrace().pushTraceInfo(); try { _context.getEditorMenuTrace().setDescriptor(new EditorMenuDescriptorBase(description, new SNodePointer("r:00000000-0000-4000-0000-011c895902c3(jetbrains.mps.baseLanguage.editor)", "5181868005210083933"))); item.setTraceInfo(_context.getEditorMenuTrace().getTraceInfo()); } finally { _context.getEditorMenuTrace().popTraceInfo(); } return item; } private class Item extends DefaultSubstituteMenuItem { private final SubstituteMenuContext _context; private EditorMenuTraceInfo myTraceInfo; public Item(SubstituteMenuContext context) { super(CONCEPTS.TryUniversalStatement$$M, context); _context = context; } private void setTraceInfo(EditorMenuTraceInfo traceInfo) { myTraceInfo = traceInfo; } @Nullable @Override public SNode createNode(@NotNull String pattern) { return SNodeFactoryOperations.createNewNode(CONCEPTS.TryUniversalStatement$$M, _context.getCurrentTargetNode()); } @Override public EditorMenuTraceInfo getTraceInfo() { return myTraceInfo; } @Override public boolean canExecute(@NotNull String pattern) { return canExecute_internal(pattern, false); } @Override public boolean canExecuteStrictly(@NotNull String pattern) { return canExecute_internal(pattern, true); } public boolean canExecute_internal(@NotNull String pattern, boolean strictly) { if (strictly) { return "try {".equals(pattern) || "try{".equals(pattern); } else { return "try {".startsWith(pattern) || "try{".startsWith(pattern); } } @Nullable @Override public String getDescriptionText(@NotNull String pattern) { return "try statement"; } @Nullable @Override public String getMatchingText(@NotNull String pattern) { return "try {"; } } } private class SMP_Action_493d70_b extends SingleItemSubstituteMenuPart { @Nullable @Override protected SubstituteMenuItem createItem(SubstituteMenuContext _context) { Item item = new Item(_context); String description; try { description = "Substitute item: " + item.getMatchingText(""); } catch (Throwable t) { Logger.getLogger(getClass()).error("Exception while executing getMatchingText() of the item " + item, t); return null; } _context.getEditorMenuTrace().pushTraceInfo(); try { _context.getEditorMenuTrace().setDescriptor(new EditorMenuDescriptorBase(description, new SNodePointer("r:00000000-0000-4000-0000-011c895902c3(jetbrains.mps.baseLanguage.editor)", "5181868005210239500"))); item.setTraceInfo(_context.getEditorMenuTrace().getTraceInfo()); } finally { _context.getEditorMenuTrace().popTraceInfo(); } return item; } private class Item extends DefaultSubstituteMenuItem { private final SubstituteMenuContext _context; private EditorMenuTraceInfo myTraceInfo; public Item(SubstituteMenuContext context) { super(CONCEPTS.TryUniversalStatement$$M, context); _context = context; } private void setTraceInfo(EditorMenuTraceInfo traceInfo) { myTraceInfo = traceInfo; } @Nullable @Override public SNode createNode(@NotNull String pattern) { SNode result = SNodeFactoryOperations.createNewNode(CONCEPTS.TryUniversalStatement$$M, _context.getCurrentTargetNode()); SNodeFactoryOperations.addNewChild(result, LINKS.resource$hgXi, null); return result; } @Override public EditorMenuTraceInfo getTraceInfo() { return myTraceInfo; } @Override public boolean canExecute(@NotNull String pattern) { return canExecute_internal(pattern, false); } @Override public boolean canExecuteStrictly(@NotNull String pattern) { return canExecute_internal(pattern, true); } public boolean canExecute_internal(@NotNull String pattern, boolean strictly) { if (strictly) { return "try (".equals(pattern) || "try(".equals(pattern); } else { return "try (".startsWith(pattern) || "try(".startsWith(pattern); } } @Nullable @Override public String getDescriptionText(@NotNull String pattern) { return "try with resources"; } @Nullable @Override public String getMatchingText(@NotNull String pattern) { return "try ("; } } } private static final class CONCEPTS { /*package*/ static final SConcept TryUniversalStatement$$M = MetaAdapterFactory.getConcept(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x4a434b86a54515f2L, "jetbrains.mps.baseLanguage.structure.TryUniversalStatement"); } private static final class LINKS { /*package*/ static final SContainmentLink resource$hgXi = MetaAdapterFactory.getContainmentLink(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x4a434b86a54515f2L, 0x4a434b86a54515feL, "resource"); } }
39.334951
253
0.722325
777111c8d01c41224e63a71faf5cc9139028d38f
1,667
/* * 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 sprites; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import misc.Updatable; import pong.Pong; /** * * @author thero */ public class Ball extends Sprite implements Updatable{ private final double BALL_WIDTH = 10; private final double BALL_HEIGHT = 10; private boolean isUp = true; private boolean isRight = false; private double xSpeed; private double ySpeed; public Ball(double startX, double startY) { xSpeed = 6; ySpeed = Math.random()*4 + 1.5; Rectangle ball = new Rectangle(BALL_WIDTH, BALL_HEIGHT, Color.WHITE); setTranslateX(startX - BALL_WIDTH/2); setTranslateY(startY - BALL_HEIGHT/2); getChildren().add(ball); } @Override public void update() { calculateDirection(); if(isUp){ setTranslateY(getTranslateY() - ySpeed); } else{ setTranslateY(getTranslateY() + ySpeed); } if(isRight){ setTranslateX(getTranslateX() + xSpeed); } else{ setTranslateX(getTranslateX() - xSpeed); } } private void calculateDirection(){ if(getTranslateY() > Pong.HEIGHT - BALL_HEIGHT){ isUp = true; } if(getTranslateY() < 0){ isUp = false; } } public void setDirectionX(boolean direction){ isRight = direction; } }
24.15942
79
0.592681
b0fb8fde7a399ee476548dae86efdf6641fb4f68
8,581
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.mailbox.maildir; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.commons.io.FileUtils; import org.apache.james.mailbox.AbstractMailboxManagerTest; import org.apache.james.mailbox.acl.GroupMembershipResolver; import org.apache.james.mailbox.acl.MailboxACLResolver; import org.apache.james.mailbox.acl.SimpleGroupMembershipResolver; import org.apache.james.mailbox.acl.UnionMailboxACLResolver; import org.apache.james.mailbox.exception.BadCredentialsException; import org.apache.james.mailbox.exception.MailboxException; import org.apache.james.mailbox.exception.MailboxExistsException; import org.apache.james.mailbox.store.JVMMailboxPathLocker; import org.apache.james.mailbox.store.StoreMailboxManager; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * MaildirMailboxManagerTest that extends the StoreMailboxManagerTest. */ public class MaildirMailboxManagerTest extends AbstractMailboxManagerTest { private static final String MAILDIR_HOME = "target/Maildir"; /** * Setup the mailboxManager. * * @throws Exception */ @Before public void setup() throws Exception { if (OsDetector.isWindows()) { System.out.println("Maildir tests work only on non-windows systems. So skip the test"); } else { deleteMaildirTestDirectory(); } } /** * Delete Maildir directory after test. * * @throws IOException */ @After public void tearDown() throws IOException { if (OsDetector.isWindows()) { System.out.println("Maildir tests work only on non-windows systems. So skip the test"); } else { deleteMaildirTestDirectory(); } } /** * @see org.apache.james.mailbox.AbstractMailboxManagerTest#testList() */ @Test @Override public void testList() throws MailboxException, UnsupportedEncodingException { if (OsDetector.isWindows()) { System.out.println("Maildir tests work only on non-windows systems. So skip the test"); } else { doTestListWithMaildirStoreConfiguration("/%domain/%user"); // TODO Tests fail with /%user configuration try { doTestListWithMaildirStoreConfiguration("/%user"); fail(); } catch (MailboxExistsException e) { // This is expected as the there are many users which have the same localpart } // TODO Tests fail with /%fulluser configuration doTestListWithMaildirStoreConfiguration("/%fulluser"); } } /** * @see org.apache.james.mailbox.AbstractMailboxManagerTest#testBasicOperations() */ @Test @Override public void testBasicOperations() throws BadCredentialsException, MailboxException, UnsupportedEncodingException { if (OsDetector.isWindows()) { System.out.println("Maildir tests work only on non-windows systems. So skip the test"); } else { MaildirStore store = new MaildirStore(MAILDIR_HOME + "/%domain/%user", new JVMMailboxPathLocker()); MaildirMailboxSessionMapperFactory mf = new MaildirMailboxSessionMapperFactory(store); MailboxACLResolver aclResolver = new UnionMailboxACLResolver(); GroupMembershipResolver groupMembershipResolver = new SimpleGroupMembershipResolver(); StoreMailboxManager<Integer> manager = new StoreMailboxManager<Integer>(mf, null, new JVMMailboxPathLocker(), aclResolver, groupMembershipResolver); manager.init(); setMailboxManager(manager); try { super.testBasicOperations(); } finally { try { deleteMaildirTestDirectory(); } catch (IOException e) { e.printStackTrace(); } } } } /** * @see org.apache.james.mailbox.AbstractMailboxManagerTest#testCreateSubFolderDirectly() */ @Test @Override public void testCreateSubFolderDirectly() throws BadCredentialsException, MailboxException { if (OsDetector.isWindows()) { System.out.println("Maildir tests work only on non-windows systems. So skip the test"); } else { MaildirStore store = new MaildirStore(MAILDIR_HOME + "/%domain/%user", new JVMMailboxPathLocker()); MaildirMailboxSessionMapperFactory mf = new MaildirMailboxSessionMapperFactory(store); MailboxACLResolver aclResolver = new UnionMailboxACLResolver(); GroupMembershipResolver groupMembershipResolver = new SimpleGroupMembershipResolver(); StoreMailboxManager<Integer> manager = new StoreMailboxManager<Integer>(mf, null, new JVMMailboxPathLocker(), aclResolver, groupMembershipResolver); manager.init(); setMailboxManager(manager); try { super.testCreateSubFolderDirectly(); } finally { try { deleteMaildirTestDirectory(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Create the maildirStore with the provided configuration and executes the list() tests. * Cleans the generated artifacts. * * @param maildirStoreConfiguration * @throws MailboxException * @throws UnsupportedEncodingException */ private void doTestListWithMaildirStoreConfiguration(String maildirStoreConfiguration) throws MailboxException, UnsupportedEncodingException { MaildirStore store = new MaildirStore(MAILDIR_HOME + maildirStoreConfiguration, new JVMMailboxPathLocker()); MaildirMailboxSessionMapperFactory mf = new MaildirMailboxSessionMapperFactory(store); MailboxACLResolver aclResolver = new UnionMailboxACLResolver(); GroupMembershipResolver groupMembershipResolver = new SimpleGroupMembershipResolver(); StoreMailboxManager<Integer> manager = new StoreMailboxManager<Integer>(mf, null, new JVMMailboxPathLocker(), aclResolver, groupMembershipResolver); manager.init(); setMailboxManager(manager); try { super.testList(); } finally { try { deleteMaildirTestDirectory(); } catch (IOException e) { e.printStackTrace(); } } } /** * @see org.apache.james.mailbox.MailboxManagerTest#createMailboxManager() */ @Override protected void createMailboxManager() { // Do nothing, the maildir mailboxManager is created in the test method. } /** * Utility method to delete the test Maildir Directory. * * @throws IOException */ private void deleteMaildirTestDirectory() throws IOException { FileUtils.deleteDirectory(new File(MAILDIR_HOME)); } }
39.362385
161
0.619275
2b9197cd0a1f85b58b4569697db7ef6cd19fe306
1,912
package com.commercetools.history.models.common; import java.util.Arrays; import java.util.Optional; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.vrap.rmf.base.client.utils.Generated; @Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen") public interface TaxCalculationMode { TaxCalculationMode LINE_ITEM_LEVEL = TaxCalculationModeEnum.LINE_ITEM_LEVEL; TaxCalculationMode UNIT_PRICE_LEVEL = TaxCalculationModeEnum.UNIT_PRICE_LEVEL; enum TaxCalculationModeEnum implements TaxCalculationMode { LINE_ITEM_LEVEL("LineItemLevel"), UNIT_PRICE_LEVEL("UnitPriceLevel"); private final String jsonName; private TaxCalculationModeEnum(final String jsonName) { this.jsonName = jsonName; } public String getJsonName() { return jsonName; } public String toString() { return jsonName; } } @JsonValue String getJsonName(); String name(); String toString(); @JsonCreator public static TaxCalculationMode findEnum(String value) { return findEnumViaJsonName(value).orElse(new TaxCalculationMode() { @Override public String getJsonName() { return value; } @Override public String name() { return value.toUpperCase(); } public String toString() { return value; } }); } public static Optional<TaxCalculationMode> findEnumViaJsonName(String jsonName) { return Arrays.stream(values()).filter(t -> t.getJsonName().equals(jsonName)).findFirst(); } public static TaxCalculationMode[] values() { return TaxCalculationModeEnum.values(); } }
26.555556
120
0.654289
25ce1839313c2d18fe8f0eb6344dd9ae8148dbcd
4,476
package com.github.kokorin.jdbunit; import com.github.kokorin.jdbunit.table.Column; import com.github.kokorin.jdbunit.table.Row; import com.github.kokorin.jdbunit.table.Table; import java.util.*; import static org.junit.Assert.*; public class JdbUnitAssert { private JdbUnitAssert() {} public static void assertTableEquals(List<Table> expectedTables, List<Table> actualTables) { assertNotNull("No expected table", expectedTables); assertNotNull("No actual table", actualTables); assertEquals(expectedTables.size(), actualTables.size()); Map<String, Table> actualMap = new HashMap<>(); for (Table actual : actualTables) { actualMap.put(actual.getName(), actual); } Map<String, Object> variables = new HashMap<>(); for (Table expected : expectedTables) { Table actual = actualMap.get(expected.getName()); assertNotNull("No table among actual: " + expected.getName(), actual); assertColumnsEqual(expected.getColumns(), actual.getColumns()); assertContentsEqual(expected.getRows(), actual.getRows(), variables); } } public static void assertColumnsEqual(List<Column> expected, List<Column> actual) { assertEquals("Column counts must be equal", expected.size(), actual.size()); for (int i = 0; i < expected.size(); ++i) { Column expColumn = expected.get(i); Column actColumn = actual.get(i); assertEquals("Column not found: " + expColumn.getName(), expColumn.getName(), actColumn.getName()); assertEquals("Column has wrong type: " + actColumn.getName(), expColumn.getType(), actColumn.getType()); } } public static void assertContentsEqual(List<Row> expected, List<Row> actual, Map<String, Object> variables) { List<Row> notFound = new ArrayList<>(expected); List<Row> notExpected = new ArrayList<>(actual); for (Iterator<Row> expRowIt = notFound.iterator(); expRowIt.hasNext(); ) { Row expRow = expRowIt.next(); for (Iterator<Row> actRowIt = notExpected.iterator(); actRowIt.hasNext(); ) { Row actRow = actRowIt.next(); boolean equal = true; Map<String, Object> captures = new HashMap<>(); for (int i = 0; i < expRow.getValues().size(); ++i) { Object expValue = expRow.getValues().get(i); Object actValue = actRow.getValues().get(i); if (expValue instanceof Row.ValueCaptor) { Row.ValueCaptor captor = (Row.ValueCaptor) expValue; captures.put(captor.getName(), actValue); continue; } if (expValue == Row.ANY_VALUE) { continue; } if (expValue instanceof Row.ValueReference) { Row.ValueReference reference = (Row.ValueReference) expValue; expValue = variables.get(reference.getName()); } if (!Objects.equals(expValue, actValue)) { equal = false; break; } } if (equal) { actRowIt.remove(); expRowIt.remove(); variables.putAll(captures); break; } } } if (!notFound.isEmpty() || !notExpected.isEmpty()) { StringBuilder message = new StringBuilder(); if (!notFound.isEmpty()) { message.append("Not found rows: \n"); printRows(message, notFound); } if (!notExpected.isEmpty()) { message.append("Not expected rows: \n"); printRows(message, notExpected); } fail(message.toString()); } } public static void printRows(StringBuilder result, List<Row> rows) { for (Row row : rows) { for (int i = 0; i < row.getValues().size(); ++i) { if (i != 0) { result.append("|"); } Object value = row.getValues().get(i); result.append(value); } result.append("\n"); } result.append("\n"); } }
36.688525
116
0.531948
2e0ac3abda46bf9e98c0b42f0258108a586de3dd
8,297
/* * 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.apisupport.project.queries; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.netbeans.api.java.queries.SourceForBinaryQuery; import org.netbeans.modules.apisupport.project.TestBase; import org.netbeans.modules.apisupport.project.universe.NbPlatform; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.filesystems.URLMapper; import org.openide.filesystems.test.TestFileUtils; /** * Test functionality of GlobalSourceForBinaryImpl. * * @author Martin Krauskopf */ public class GlobalSourceForBinaryImplTest extends TestBase { // Doesn't need to be precise and/or valid. Should show what actual // GlobalSourceForBinaryImpl works with. private static final String LOADERS_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<project xmlns=\"http://www.netbeans.org/ns/project/1\">\n" + "<type>org.netbeans.modules.apisupport.project</type>\n" + "<configuration>\n" + "<data xmlns=\"http://www.netbeans.org/ns/nb-module-project/3\">\n" + "<code-name-base>org.openide.loaders</code-name-base>\n" + "</data>\n" + "</configuration>\n" + "</project>\n"; public GlobalSourceForBinaryImplTest(String name) { super(name); } public void testFindSourceRootForZipWithFirstLevelDepthNbBuild() throws Exception { File nbSrcZip = generateNbSrcZip(""); NbPlatform.getDefaultPlatform().addSourceRoot(FileUtil.urlForArchiveOrDir(nbSrcZip)); URL loadersURL = FileUtil.urlForArchiveOrDir(file("nbbuild/netbeans/" + TestBase.CLUSTER_PLATFORM + "/modules/org-openide-loaders.jar")); URL loadersSrcURL = new URL(FileUtil.urlForArchiveOrDir(nbSrcZip), "openide/loaders/src/"); assertRoot(loadersURL, URLMapper.findFileObject(loadersSrcURL)); } public void testFindSourceRootForZipWithSecondLevelDepthNbBuild() throws Exception { File nbSrcZip = generateNbSrcZip("netbeans-src/"); NbPlatform.getDefaultPlatform().addSourceRoot(FileUtil.urlForArchiveOrDir(nbSrcZip)); URL loadersURL = FileUtil.urlForArchiveOrDir(file("nbbuild/netbeans/" + TestBase.CLUSTER_PLATFORM + "/modules/org-openide-loaders.jar")); URL loadersSrcURL = new URL(FileUtil.urlForArchiveOrDir(nbSrcZip), "netbeans-src/openide/loaders/src/"); assertRoot(loadersURL, URLMapper.findFileObject(loadersSrcURL)); } // just sanity check that exception is not thrown public void testBehaviourWithNonZipFile() throws Exception { GlobalSourceForBinaryImpl.quiet = true; File nbSrcZip = new File(getWorkDir(), "wrong-nbsrc.zip"); nbSrcZip.createNewFile(); NbPlatform.getDefaultPlatform().addSourceRoot(FileUtil.urlForArchiveOrDir(nbSrcZip)); URL loadersURL = FileUtil.urlForArchiveOrDir(file("nbbuild/netbeans/" + TestBase.CLUSTER_PLATFORM + "/modules/org-openide-loaders.jar")); SourceForBinaryQuery.findSourceRoots(loadersURL).getRoots(); } public void testListeningToNbPlatform() throws Exception { NbPlatform.getDefaultPlatform(); // initBuildProperties File nbSrcZip = generateNbSrcZip(""); URL loadersURL = FileUtil.urlForArchiveOrDir(file("nbbuild/netbeans/" + TestBase.CLUSTER_PLATFORM + "/modules/org-openide-loaders.jar")); SourceForBinaryQuery.Result res = SourceForBinaryQuery.findSourceRoots(loadersURL); assertNotNull("got result", res); ResultChangeListener resultCL = new ResultChangeListener(); res.addChangeListener(resultCL); assertFalse("not changed yet", resultCL.changed); assertEquals("non source root", 0, res.getRoots().length); NbPlatform.getDefaultPlatform().addSourceRoot(FileUtil.urlForArchiveOrDir(nbSrcZip)); assertTrue("changed yet", resultCL.changed); assertEquals("one source root", 1, res.getRoots().length); URL loadersSrcURL = new URL(FileUtil.urlForArchiveOrDir(nbSrcZip), "openide/loaders/src/"); assertRoot(loadersURL, URLMapper.findFileObject(loadersSrcURL)); } public void testNewModuleLayout() throws Exception { File nbSrcZip = FileUtil.toFile(TestFileUtils.writeZipFile(FileUtil.toFileObject(getWorkDir()), "nbsrc.zip", "nbbuild/nbproject/project.xml:", "openide.loaders/src/dummy:", "openide.loaders/nbproject/project.xml:" + LOADERS_XML)); NbPlatform.getDefaultPlatform().addSourceRoot(FileUtil.urlForArchiveOrDir(nbSrcZip)); URL loadersURL = FileUtil.urlForArchiveOrDir(file("nbbuild/netbeans/" + TestBase.CLUSTER_PLATFORM + "/modules/org-openide-loaders.jar")); URL loadersSrcURL = new URL(FileUtil.urlForArchiveOrDir(nbSrcZip), "openide.loaders/src/"); assertRoot(loadersURL, URLMapper.findFileObject(loadersSrcURL)); } public void testOldProjectXML() throws Exception { // #136679 File nbSrcZip = FileUtil.toFile(TestFileUtils.writeZipFile(FileUtil.toFileObject(getWorkDir()), "nbsrc.zip", "nbbuild/nbproject/project.xml:", "openide.loaders/src/dummy:", "openide.loaders/nbproject/project.xml:" + LOADERS_XML.replace("/3", "/2"))); NbPlatform.getDefaultPlatform().addSourceRoot(FileUtil.urlForArchiveOrDir(nbSrcZip)); URL loadersURL = FileUtil.urlForArchiveOrDir(file("nbbuild/netbeans/" + TestBase.CLUSTER_PLATFORM + "/modules/org-openide-loaders.jar")); URL loadersSrcURL = new URL(FileUtil.urlForArchiveOrDir(nbSrcZip), "openide.loaders/src/"); assertRoot(loadersURL, URLMapper.findFileObject(loadersSrcURL)); } public void testUnrelatedJAR() throws Exception { // #201043 File plaf = getWorkDir(); org.openide.util.test.TestFileUtils.writeZipFile(new File(plaf, "platform/core/core.jar")); File mavenJar = org.openide.util.test.TestFileUtils.writeZipFile(new File(plaf, "java/maven/lib/maven-core-3.0.3.jar")); assertTrue(NbPlatform.isPlatformDirectory(plaf)); assertTrue(NbPlatform.isSupportedPlatform(plaf)); NbPlatform.addPlatform("test", plaf, "Test Plaf"); assertNull(new GlobalSourceForBinaryImpl().findSourceRoots(FileUtil.urlForArchiveOrDir(mavenJar))); } private File generateNbSrcZip(String topLevelEntry) throws IOException { return FileUtil.toFile(TestFileUtils.writeZipFile(FileUtil.toFileObject(getWorkDir()), "nbsrc.zip", topLevelEntry + "nbbuild/nbproject/project.xml:", topLevelEntry + "openide/loaders/src/dummy:", topLevelEntry + "openide/loaders/nbproject/project.xml:" + LOADERS_XML)); } private static void assertRoot(final URL loadersURL, final FileObject loadersSrcFO) { assertEquals("right results for " + loadersURL, Collections.singletonList(loadersSrcFO), Arrays.asList(SourceForBinaryQuery.findSourceRoots(loadersURL).getRoots())); } private static final class ResultChangeListener implements ChangeListener { private boolean changed; public void stateChanged(ChangeEvent e) { changed = true; } } }
51.216049
145
0.707846
b02195052289c38616533b54c92613f12ba722b2
579
package com.funix.lab04.asm21.model; import java.time.LocalDate; import javax.persistence.Entity; import javax.persistence.Id; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Data @Builder @NoArgsConstructor @AllArgsConstructor public class WeddingBlog { @Id private Integer id; private String title; private String postType; private String imgUrl; private String paragraph; private Integer likeCount; private Integer commentCount; private LocalDate publishedDate; }
19.3
36
0.775475
3d30e00f5211ee8f376ac9b20dd476abe79e608c
559
package cn.com.mfish.oauth.credentials; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.credential.SimpleCredentialsMatcher; /** * @author qiufeng * @date 2020/2/25 16:49 */ public class QRCodeCredentialsMatcher extends SimpleCredentialsMatcher { @Override public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) { return super.doCredentialsMatch(authenticationToken, authenticationInfo); } }
32.882353
119
0.808587
a996f50f526e7f50a65b5a7389ef64bd187bf596
1,045
package one.microproject.logger.dto; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; public class InsertDataRecord { private final Long timeStamp; private final String groupId; private final String name; private final JsonNode payload; @JsonCreator public InsertDataRecord(@JsonProperty("timeStamp") Long timeStamp, @JsonProperty("groupId") String groupId, @JsonProperty("name") String name, @JsonProperty("payload") JsonNode payload) { this.timeStamp = timeStamp; this.groupId = groupId; this.name = name; this.payload = payload; } public Long getTimeStamp() { return timeStamp; } public String getGroupId() { return groupId; } public String getName() { return name; } public JsonNode getPayload() { return payload; } }
24.880952
72
0.629665
0aceedf126de19f725a8ed927a3b222465465924
5,146
package liquibase.ext.vertica.snapshot; import liquibase.CatalogAndSchema; import liquibase.database.AbstractJdbcDatabase; import liquibase.database.Database; import liquibase.database.ObjectQuotingStrategy; import liquibase.database.jvm.JdbcConnection; import liquibase.diff.compare.DatabaseObjectComparatorFactory; import liquibase.exception.DatabaseException; import liquibase.ext.vertica.database.VerticaDatabase; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.InvalidExampleException; import liquibase.snapshot.SnapshotGenerator; import liquibase.snapshot.jvm.JdbcSnapshotGenerator; import liquibase.snapshot.jvm.TableSnapshotGenerator; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Catalog; import liquibase.structure.core.Schema; import liquibase.util.JdbcUtils; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by vesterma on 10/09/2014. */ public class SchemaSnapshotGenerator extends JdbcSnapshotGenerator { @Override public int getPriority(Class<? extends DatabaseObject> objectType, Database database) { if (database instanceof VerticaDatabase) return PRIORITY_DATABASE; return PRIORITY_NONE; } public SchemaSnapshotGenerator() { super(Schema.class); } @Override protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException { Database database = snapshot.getDatabase(); Schema match = null; String catalogName = ((Schema) example).getCatalogName(); String schemaName = example.getName(); if (database.supportsSchemas()) { if (catalogName == null) { catalogName = database.getDefaultCatalogName(); } if (schemaName == null) { schemaName = database.getDefaultSchemaName(); } } else { if (database.supportsCatalogs()) { if (catalogName == null && schemaName != null) { catalogName = schemaName; schemaName = null; } } else { catalogName = null; schemaName = null; } } example = new Schema(catalogName, schemaName); // use LEGACY quoting since we're dealing with system objects ObjectQuotingStrategy currentStrategy = database.getObjectQuotingStrategy(); database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY); try { if (database.supportsSchemas()) { for (String tableSchema : getDatabaseSchemaNames(database)) { CatalogAndSchema schemaFromJdbcInfo = toCatalogAndSchema(tableSchema, database); Catalog catalog = new Catalog(schemaFromJdbcInfo.getCatalogName()); Schema schema = new Schema(catalog, tableSchema); if (DatabaseObjectComparatorFactory.getInstance().isSameObject(schema, example, database)) { if (match == null) { match = schema; } else { throw new InvalidExampleException("Found multiple catalog/schemas matching " + ((Schema) example).getCatalogName() + "." + example.getName()); } } } } else { Catalog catalog = new Catalog(catalogName); match = new Schema(catalog, null); } } catch (SQLException e) { throw new DatabaseException(e); } finally { database.setObjectQuotingStrategy(currentStrategy); } if (match != null && (match.getName() == null || match.getName().equalsIgnoreCase(database.getDefaultSchemaName()))) { match.setDefault(true); } return match; } protected CatalogAndSchema toCatalogAndSchema(String tableSchema, Database database) { return ((AbstractJdbcDatabase) database).getSchemaFromJdbcInfo(null, tableSchema); } @Override protected void addTo(DatabaseObject foundObject, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException { //no other types } protected String[] getDatabaseSchemaNames(Database database) throws SQLException, DatabaseException { List<String> returnList = new ArrayList<String>(); ResultSet schemas = null; try { schemas = ((JdbcConnection) database.getConnection()).getMetaData().getSchemas(); while (schemas.next()) { returnList.add(JdbcUtils.getValueForColumn(schemas, "TABLE_SCHEM", database)); } } finally { if (schemas != null) { schemas.close(); } } return returnList.toArray(new String[returnList.size()]); } public Class<? extends SnapshotGenerator>[] replaces(){ return new Class[]{SchemaSnapshotGenerator.class}; } }
37.021583
170
0.642246
ffcb1930af9931e647d67fdfdd201a1d028e1955
797
package com.actionworks.flashsale.app.model.enums; public enum OrderTaskStatus { SUBMITTED(0, "初始提交"), SUCCESS(1, "下单成功"), FAILED(-1, "下单失败"); private final Integer status; private final String desc; OrderTaskStatus(Integer status, String desc) { this.status = status; this.desc = desc; } public static OrderTaskStatus findBy(Integer status) { if (status == null) { return null; } for (OrderTaskStatus taskStatus : OrderTaskStatus.values()) { if (taskStatus.getStatus().equals(status)) { return taskStatus; } } return null; } public Integer getStatus() { return status; } public String getDesc() { return desc; } }
22.138889
69
0.5734
3c68fbb1f26380ce0294b6f0f12eabb915bc8da4
6,904
/* * 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.aliyuncs.ecsops.model.v20160401; import java.util.List; import com.aliyuncs.AcsResponse; import com.aliyuncs.ecsops.transform.v20160401.OpsDescribeResourceActionTrailInfoResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class OpsDescribeResourceActionTrailInfoResponse extends AcsResponse { private String requestId; private List<Resource> resources; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public List<Resource> getResources() { return this.resources; } public void setResources(List<Resource> resources) { this.resources = resources; } public static class Resource { private String resourceId; private String relatedResourceId; private String relatedResourceType; private String startTime; private String endTime; private String nextToken; private List<ResourceAction> resourceActions; public String getResourceId() { return this.resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } public String getRelatedResourceId() { return this.relatedResourceId; } public void setRelatedResourceId(String relatedResourceId) { this.relatedResourceId = relatedResourceId; } public String getRelatedResourceType() { return this.relatedResourceType; } public void setRelatedResourceType(String relatedResourceType) { this.relatedResourceType = relatedResourceType; } public String getStartTime() { return this.startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return this.endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getNextToken() { return this.nextToken; } public void setNextToken(String nextToken) { this.nextToken = nextToken; } public List<ResourceAction> getResourceActions() { return this.resourceActions; } public void setResourceActions(List<ResourceAction> resourceActions) { this.resourceActions = resourceActions; } public static class ResourceAction { private String actionApiVersion; private String actionErrorMessage; private String userInfoAk; private String actionRequestId; private String actionSourceIpAddress; private String actionEventType; private String actionEventSource; private String actionEventId; private String actionErrorCode; private String actionEventTime; private Boolean actionSuccess; private String actionEventName; private List<ActionRelatedResource> actionRelatedResources; public String getActionApiVersion() { return this.actionApiVersion; } public void setActionApiVersion(String actionApiVersion) { this.actionApiVersion = actionApiVersion; } public String getActionErrorMessage() { return this.actionErrorMessage; } public void setActionErrorMessage(String actionErrorMessage) { this.actionErrorMessage = actionErrorMessage; } public String getUserInfoAk() { return this.userInfoAk; } public void setUserInfoAk(String userInfoAk) { this.userInfoAk = userInfoAk; } public String getActionRequestId() { return this.actionRequestId; } public void setActionRequestId(String actionRequestId) { this.actionRequestId = actionRequestId; } public String getActionSourceIpAddress() { return this.actionSourceIpAddress; } public void setActionSourceIpAddress(String actionSourceIpAddress) { this.actionSourceIpAddress = actionSourceIpAddress; } public String getActionEventType() { return this.actionEventType; } public void setActionEventType(String actionEventType) { this.actionEventType = actionEventType; } public String getActionEventSource() { return this.actionEventSource; } public void setActionEventSource(String actionEventSource) { this.actionEventSource = actionEventSource; } public String getActionEventId() { return this.actionEventId; } public void setActionEventId(String actionEventId) { this.actionEventId = actionEventId; } public String getActionErrorCode() { return this.actionErrorCode; } public void setActionErrorCode(String actionErrorCode) { this.actionErrorCode = actionErrorCode; } public String getActionEventTime() { return this.actionEventTime; } public void setActionEventTime(String actionEventTime) { this.actionEventTime = actionEventTime; } public Boolean getActionSuccess() { return this.actionSuccess; } public void setActionSuccess(Boolean actionSuccess) { this.actionSuccess = actionSuccess; } public String getActionEventName() { return this.actionEventName; } public void setActionEventName(String actionEventName) { this.actionEventName = actionEventName; } public List<ActionRelatedResource> getActionRelatedResources() { return this.actionRelatedResources; } public void setActionRelatedResources(List<ActionRelatedResource> actionRelatedResources) { this.actionRelatedResources = actionRelatedResources; } public static class ActionRelatedResource { private String actionResourceType; private List<String> actionResourceIds; public String getActionResourceType() { return this.actionResourceType; } public void setActionResourceType(String actionResourceType) { this.actionResourceType = actionResourceType; } public List<String> getActionResourceIds() { return this.actionResourceIds; } public void setActionResourceIds(List<String> actionResourceIds) { this.actionResourceIds = actionResourceIds; } } } } @Override public OpsDescribeResourceActionTrailInfoResponse getInstance(UnmarshallerContext context) { return OpsDescribeResourceActionTrailInfoResponseUnmarshaller.unmarshall(this, context); } }
24.48227
102
0.724218
699d762bb27c7549b2ebaf5fc5ee381da683fae1
3,438
/******************************************************************************* * Copyright (c) Dec 2, 2015 @author <a href="mailto:iffiff1@gmail.com">Tyler Chen</a>. * All rights reserved. * * Contributors: * <a href="mailto:iffiff1@gmail.com">Tyler Chen</a> - initial API and implementation ******************************************************************************/ package org.iff.infra.util.database; import java.math.BigDecimal; import org.iff.infra.util.NumberHelper; /** * @author <a href="mailto:iffiff1@gmail.com">Tyler Chen</a> * @since Dec 2, 2015 */ public class MySqlJavaTypeMapping implements JavaTypeMapping { public String getType() { return "mysql"; } public String get(String dbType, Integer length, Integer scale) { String key = dbType.toUpperCase(); length = NumberHelper.getInt(length, 0); scale = NumberHelper.getInt(scale, -1); if ("BIT".equals(key)) { if (length > 1) { return "byte[]"; } else { return "byte"; } } else if ("TINYINT".equals(key) || "BOOL".equals(key) || "BOOLEAN".equals(key)) { return "Boolean"; } else if ("SMALLINT".equals(key) || "MEDIUMINT".equals(key) || "INTEGER".equals(key) || "INT".equals(key)) { return "Integer"; } else if ("BIGINT".equals(key)) { return "Long"; } else if ("REAL".equals(key) || "DOUBLE".equals(key)) { return "Double"; } else if ("FLOAT".equals(key)) { return "Float"; } else if ("NUMERIC".equals(key) || "DECIMAL".equals(key)) { return BigDecimal.class.getName(); } else if ("DATETIME".equals(key) || "DATE".equals(key) || "TIME".equals(key) || "TIMESTAMP".equals(key)) { return java.util.Date.class.getName(); } else if ("YEAR".equals(key)) { return "Short"; } else if ("CHAR".equals(key) || "VARCHAR".equals(key) || "TINYTEXT".equals(key) || "TEXT".equals(key) || "MEDIUMTEXT".equals(key) || "LONGTEXT".equals(key) || "ENUM".equals(key) || "SET".equals(key)) { return "String"; } else if ("BINARY".equals(key) || "VARBINARY".equals(key) || "TINYBLOB".equals(key) || "BLOB".equals(key) || "MEDIUMBLOB".equals(key)) { return "String"; } return "String"; } public String getDbType(String javaType) { if (byte.class.getName().equals(javaType) || Byte.class.getName().equals(javaType) || "Byte".equals(javaType)) { return "BIT"; } else if (boolean.class.getName().equals(javaType) || Boolean.class.getName().equals(javaType) || "Boolean".equals(javaType)) { return "BOOLEAN"; } else if (short.class.getName().equals(javaType) || Short.class.getName().equals(javaType) || "Short".equals(javaType)) { return "SMALLINT"; } else if (int.class.getName().equals(javaType) || Integer.class.getName().equals(javaType) || "Integer".equals(javaType)) { return "INT"; } else if (long.class.getName().equals(javaType) || Long.class.getName().equals(javaType) || "Long".equals(javaType)) { return "BIGINT"; } else if (double.class.getName().equals(javaType) || Double.class.getName().equals(javaType) || "Double".equals(javaType)) { return "REAL"; } else if (float.class.getName().equals(javaType) || Float.class.getName().equals(javaType) || "Float".equals(javaType)) { return "FLOAT"; } else if (java.math.BigDecimal.class.getName().equals(javaType)) { return "NUMERIC"; } else if (java.util.Date.class.getName().equals(javaType)) { return "DATE"; } else { return "VARCHAR2"; } } }
37.78022
114
0.616638
0d5445f6dffd58385db467b00542d989a6da8592
2,401
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.security.zynamics.zylib.yfileswrap.gui.zygraph; import com.google.security.zynamics.zylib.gui.zygraph.IFineGrainedSloppyGraph2DView; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.realizers.ZyGroupNodeRealizer; import y.base.Edge; import y.base.Node; import y.view.Graph2D; import y.view.hierarchy.HierarchyManager; public class ZyGraphLayeredRenderer<ViewType extends IFineGrainedSloppyGraph2DView> extends ZyGraphFineGrainedRenderer<ViewType> { private Node m_node = null; public ZyGraphLayeredRenderer(final ViewType inputView) { super(inputView); setLayeredPainting(true); } /** * Determines whether any of the parent nodes of the given node is selected. */ private boolean isAnyParentNodeSelected(final Node n) { final Graph2D graph = (Graph2D) n.getGraph(); final HierarchyManager hierarchy = graph.getHierarchyManager(); if (hierarchy == null) { return false; } boolean result = false; Node parent = hierarchy.getParentNode(n); while (parent != null) { if (graph.isSelected(parent)) { result = true; break; } parent = hierarchy.getParentNode(parent); } return result; } @Override protected int getLayer(final Graph2D graph, final Edge edge) { return 2; } @Override protected int getLayer(final Graph2D graph, final Node node) { final boolean isGroupNode = graph.getRealizer(node) instanceof ZyGroupNodeRealizer<?>; if ((graph.isSelected(node) || isAnyParentNodeSelected(node)) && !isGroupNode) { return 3; } else if ((m_node == node) && !isGroupNode) { return 4; } else if (isGroupNode) { return 1; } else { return 2; } } public void bringNodeToFront(final Node node) { m_node = node; } }
29.280488
95
0.720117
8ede974f166581954f735bc3694e2318cbb46c08
3,518
/* Copyright (c) 2010, Geomatics and Cartographic Research Centre, Carleton University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Geomatics and Cartographic Research Centre, Carleton University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. $Id$ */ package ca.carleton.gcrc.AdhocQueries; import java.sql.Connection; import java.sql.PreparedStatement; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ca.carleton.gcrc.dbSec.ColumnData; import ca.carleton.gcrc.dbSec.impl.ColumnDataUtils; public class AdhocQueries { final private Logger logger = LoggerFactory.getLogger(this.getClass()); private Connection connection; public AdhocQueries(Connection c) { connection = c; } public JSONObject performAdhocQueryWithArgs(String sqlStatement, String args, int argsExpected) throws Exception { logger.info("Executing adhoc query: " + sqlStatement + " for arguments: " + args); String[] splitArgs = args.split(","); if (argsExpected == 0 && (splitArgs.length > 1 || (splitArgs.length == 1 && splitArgs[0] != ""))) { // we want 0 args but even an empty string shows as a split of 1 with the empty string throw new Exception("Expected NO arguments but received at least one non-empty arg."); } else if (argsExpected == 1 && splitArgs.length == 1 && splitArgs[0] == "") { // null args list shows up as length 1 so below (default) test won't catch that throw new Exception("Expected one arg but received empty string."); } else if (argsExpected >= 1 && splitArgs.length != argsExpected) { throw new Exception("Expected " + argsExpected + " args but got " + splitArgs.length); } PreparedStatement stmt = connection.prepareStatement(sqlStatement); int index = 1; for (int loop=0; loop<argsExpected; loop++) { ColumnDataUtils.writeToPreparedStatement(stmt, index, splitArgs[loop], ColumnData.Type.INTEGER); // always integer arg for now ++index; } JSONArray array = ColumnDataUtils.executeStatementToJson(stmt); JSONObject result = new JSONObject(); result.put("results", array); return result; } }
39.977273
129
0.756396
9f4e7134f15038b50d78ca3c9f6f2fa7cadf90f2
3,097
/* * Copyright (C) 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.syndesis.connector.mongo; import java.util.Map; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import io.syndesis.integration.component.proxy.ComponentProxyComponent; import io.syndesis.integration.component.proxy.ComponentProxyCustomizer; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; import org.apache.camel.component.mongodb3.conf.ConnectionParamsConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.camel.util.CastUtils.cast; public class MongoClientCustomizer implements ComponentProxyCustomizer, CamelContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(MongoClientCustomizer.class); private CamelContext camelContext; @Override public CamelContext getCamelContext() { return this.camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public void customize(ComponentProxyComponent component, Map<String, Object> options) { MongoCustomizersUtil.replaceAdminDBIfMissing(options); // Set connection parameter if (!options.containsKey("mongoConnection")) { if (options.containsKey("user") && options.containsKey("password") && options.containsKey("host")) { ConnectionParamsConfiguration mongoConf = new ConnectionParamsConfiguration(cast(options)); // We need to force consumption in order to perform property placeholder done by Camel consumeOption(camelContext, options, "password", String.class, mongoConf::setPassword); LOGGER.debug("Creating and registering a client connection to {}", mongoConf); MongoClientURI mongoClientURI = new MongoClientURI(mongoConf.getMongoClientURI()); MongoClient mongoClient = new MongoClient(mongoClientURI); options.put("mongoConnection", mongoClient); if (!options.containsKey("connectionBean")) { //We safely put a default name instead of leaving null options.put("connectionBean", String.format("%s-%s", mongoConf.getHost(), mongoConf.getUser())); } } else { LOGGER.warn( "Not enough information provided to set-up the MongoDB client. Required at least host, user and password."); } } } }
43.619718
128
0.70649
f9c934d354f4c55eef2e01c424e717def577b34f
2,015
package com.ericmschmidt.latinreader.datamodel; import org.junit.Before; import org.junit.Test; import static com.google.common.truth.Truth.assertThat; public class BookTest { Book testBook; String expectedLine1 = "This is line 1"; String expectedLine2 = "This is line 2"; String expectedLine3 = "This is line 3"; @Before public void setUp() { testBook = new Book(1234); testBook.addLines(expectedLine1); testBook.addLines(expectedLine2); testBook.addLines(expectedLine3); } @Test public void testGetLine() { // Verify that it gets the correct line. String actualResult1 = testBook.getLine(0); assertThat(actualResult1).contains(expectedLine1); // Verify that passing in a negative number returns the first line. String actualResult2 = testBook.getLine(-1); assertThat(actualResult2).contains(expectedLine1); // Verify that passing in a number larger than the number // of lines returns null. String actualResult3 = testBook.getLine(5); assertThat(actualResult3).isNull(); } @Test public void testGetLines() { // Verify that it gets the correct lines. String actualResult1 = testBook.getLines(0, 2); assertThat(actualResult1).contains(expectedLine1); assertThat(actualResult1).contains(expectedLine2); // Verify that passing in a negative number as the position returns // lines from the beginning of the book. String actualResult2 = testBook.getLines(-2, 2); assertThat(actualResult2).contains(expectedLine1); assertThat(actualResult2).contains(expectedLine2); // Verify that passing in a number greater than the total lines // returns the remaining lines in the book. String actualResult3 = testBook.getLines(1, 10); assertThat(actualResult3).contains(expectedLine2); assertThat(actualResult3).contains(expectedLine3); } }
32.5
75
0.678908
23ec36abf19002105b4dcbbf6917e3ee7286acf6
8,254
package uk.gov.companieshouse.ocr.api.image.extracttext; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.apache.commons.lang.time.StopWatch; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import uk.gov.companieshouse.logging.Logger; import uk.gov.companieshouse.logging.LoggerFactory; import uk.gov.companieshouse.ocr.api.OcrApiApplication; import uk.gov.companieshouse.ocr.api.ThreadConfig; import uk.gov.companieshouse.ocr.api.common.CallTypeEnum; import uk.gov.companieshouse.ocr.api.common.JsonConstants; /** * This controls the workflow of an ocr request */ @Service public class OcrRequestService { private static final Logger LOG = LoggerFactory.getLogger(OcrApiApplication.APPLICATION_NAME_SPACE); @Autowired private ImageRestClient imageRestClient; @Autowired private ImageOcrService imageOcrService; @Autowired private CallbackExtractedTextRestClient callbackExtractedTextRestClient; @Autowired private MonitoringService monitoringService; private ImageOcrTransformer transformer = new ImageOcrTransformer(); @Async(ThreadConfig.OCR_REQUEST_EXECUTOR_BEAN) public void handleAsynchronousRequest(OcrRequest ocrRequest, StopWatch ocrRequestStopWatch) { var timeOnQueue = ocrRequestStopWatch.getTime(); byte[] imageBytes = {}; ExtractTextResultDto extractTextResult = null; TextConversionResult textConversionResult = null; try { var logDataMap = createOcrRequestPostQueueLogMap(ocrRequest, timeOnQueue); LOG.infoContext(ocrRequest.getContextId(), "Orchestrating OCR Request From Asynchronous Request", logDataMap); imageBytes = imageRestClient.getImageContentsFromEndpoint(ocrRequest.getContextId(), ocrRequest.getImageEndpoint()); textConversionResult = imageOcrService.extractTextFromImageBytes(ocrRequest.getContextId(), imageBytes, ocrRequest.getResponseId(), timeOnQueue); extractTextResult = transformer.mapModelToApi(textConversionResult); extractTextResult.setTotalProcessingTimeMs(ocrRequestStopWatch.getTime()); // set the time for the client callbackExtractedTextRestClient.sendTextResult(ocrRequest.getContextId(), ocrRequest.getConvertedTextEndpoint(), extractTextResult); ocrRequestStopWatch.stop(); extractTextResult.setTotalProcessingTimeMs(ocrRequestStopWatch.getTime()); // Set the time for the monitoring field var monitoringFields = new MonitoringFields(textConversionResult, extractTextResult, CallTypeEnum.ASYNCHRONOUS); monitoringService.logSuccess(ocrRequest.getContextId(), monitoringFields); } catch(IOException | TextConversionException e) { var totalProcessingTimeMs = stopStopWatchAndReturnTime(ocrRequestStopWatch); LOG.errorContext(ocrRequest.getContextId(), "Error Converting image to text", e, null); callbackExtractedTextRestClient.sendTextResultError(ocrRequest.getContextId(), ocrRequest.getResponseId(), ocrRequest.getConvertedTextEndpoint(), OcrRequestException.ResultCode.FAIL_TO_COVERT_IMAGE_TO_TEXT, totalProcessingTimeMs); monitoringService.logFailure(ocrRequest.getContextId(), totalProcessingTimeMs, OcrRequestException.ResultCode.FAIL_TO_COVERT_IMAGE_TO_TEXT, CallTypeEnum.ASYNCHRONOUS, imageBytes.length); } catch (OcrRequestException e) { LOG.errorContext(ocrRequest.getContextId(), "Error in OCR Request", e, null); var totalProcessingTimeMs = stopStopWatchAndReturnTime(ocrRequestStopWatch); switch(e.getResultCode()) { case FAIL_TO_GET_IMAGE: callbackExtractedTextRestClient.sendTextResultError(ocrRequest.getContextId(), ocrRequest.getResponseId(), ocrRequest.getConvertedTextEndpoint(), e.getResultCode(), totalProcessingTimeMs); monitoringService.logFailure(ocrRequest.getContextId(), totalProcessingTimeMs, e.getResultCode(), CallTypeEnum.ASYNCHRONOUS, imageBytes.length); break; case FAIL_TO_SEND_RESULTS: if (extractTextResult != null && textConversionResult != null) { extractTextResult.setTotalProcessingTimeMs(totalProcessingTimeMs); extractTextResult.setResultCode(e.getResultCode().getCode()); var monitoringFields = new MonitoringFields(textConversionResult, extractTextResult, CallTypeEnum.ASYNCHRONOUS); monitoringService.logFailToSendResults(ocrRequest.getContextId(), monitoringFields); } else { monitoringService.logFailure(ocrRequest.getContextId(), totalProcessingTimeMs, e.getResultCode(), CallTypeEnum.ASYNCHRONOUS, imageBytes.length); } break; default: callbackExtractedTextRestClient.sendTextResultError(ocrRequest.getContextId(), ocrRequest.getResponseId(), ocrRequest.getConvertedTextEndpoint(), e.getResultCode(), totalProcessingTimeMs); monitoringService.logFailure(ocrRequest.getContextId(), totalProcessingTimeMs, e.getResultCode(), CallTypeEnum.ASYNCHRONOUS, imageBytes.length); } } catch (Exception e) { LOG.errorContext(ocrRequest.getContextId(), "Unexpected Error in OCR Request", e, null); var totalProcessingTimeMs = stopStopWatchAndReturnTime(ocrRequestStopWatch); OcrRequestException.ResultCode unexpectedFailureResultCode = OcrRequestException.ResultCode.UNEXPECTED_FAILURE; callbackExtractedTextRestClient.sendTextResultError(ocrRequest.getContextId(), ocrRequest.getResponseId(), ocrRequest.getConvertedTextEndpoint(), unexpectedFailureResultCode, totalProcessingTimeMs); monitoringService.logFailure(ocrRequest.getContextId(), totalProcessingTimeMs, unexpectedFailureResultCode, CallTypeEnum.ASYNCHRONOUS, imageBytes.length); } } private Map<String, Object> createOcrRequestPostQueueLogMap(OcrRequest ocrRequest, long timeOnQueue) { var logDataMap = ocrRequest.toMap(); logDataMap.put(JsonConstants.LOG_RECORD_NAME, JsonConstants.POST_QUEUE_LOG_RECORD); logDataMap.put(JsonConstants.THREAD_NAME_NAME, Thread.currentThread().getName()); logDataMap.put(JsonConstants.TIME_ON_QUEUE_MS_NAME, timeOnQueue); logDataMap.put(JsonConstants.CALL_TYPE_NAME, CallTypeEnum.ASYNCHRONOUS.getFieldValue()); return logDataMap; } @Async(ThreadConfig.OCR_REQUEST_EXECUTOR_BEAN) public CompletableFuture<TextConversionResult> handleSynchronousRequest(String contextId, byte[] imageBytes, String responseId, StopWatch timeOnQueueStopWatch) throws IOException, TextConversionException { var timeOnQueue = stopStopWatchAndReturnTime(timeOnQueueStopWatch); var logDataMap = createSyncPostQueueLogMap(timeOnQueue); LOG.infoContext(contextId, "Continuing Synchronous Request", logDataMap); var textConversionResult = imageOcrService.extractTextFromImageBytes(contextId, imageBytes, responseId, timeOnQueue); return CompletableFuture.completedFuture(textConversionResult); } private Map<String, Object> createSyncPostQueueLogMap(long timeOnQueue) { Map<String, Object> logDataMap = new LinkedHashMap<>(); logDataMap.put(JsonConstants.LOG_RECORD_NAME, JsonConstants.POST_QUEUE_LOG_RECORD); logDataMap.put(JsonConstants.THREAD_NAME_NAME, Thread.currentThread().getName()); logDataMap.put(JsonConstants.TIME_ON_QUEUE_MS_NAME, timeOnQueue); logDataMap.put(JsonConstants.CALL_TYPE_NAME, CallTypeEnum.SYNCHRONOUS.getFieldValue()); return logDataMap; } private long stopStopWatchAndReturnTime(StopWatch stopWatch) { stopWatch.stop(); return stopWatch.getTime(); } }
55.395973
242
0.739036
9892047dbdf1c854e4353ded85c67363e19d7edd
1,810
package org.o7planning.farmeggmvc.service; import java.util.List; import org.apache.log4j.Logger; import org.o7planning.farmeggmvc.database.DataFarm; import org.o7planning.farmeggmvc.model.Farmer; import org.o7planning.farmeggmvc.model.factory.EggFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class FarmerServiceImpl implements IFarmerService { private final Logger LOG = Logger.getLogger(FarmerServiceImpl.class); @Autowired private EggFactory factory; @Override public void createFarmer(String name) { LOG.info(DataFarm.farmers.size()); DataFarm.farmers.add(new Farmer(factory, name)); LOG.info(DataFarm.farmers.size()); } @Override public List<Farmer> allFarmer() { // TODO Auto-generated method stub return DataFarm.farmers; } @Override public void deleteFarmerByIndex(int index) { // TODO Auto-generated method stub DataFarm.farmers.remove(index); } @Override public Farmer updateFarmer(Farmer farmer, int index) { // TODO Auto-generated method stub Farmer oldFarmer = DataFarm.farmers.get(index); if (DataFarm.farmers.remove(oldFarmer)) { DataFarm.farmers.add(farmer); return farmer; } return null; } @Override public void deleteFarmerByName(String name) { // TODO Auto-generated method stub DataFarm.farmers.get(getFarmer(name)); } private Integer getFarmer(String name) { Integer index = null; for (int i = 0; i < DataFarm.farmers.size(); i++) { if (DataFarm.farmers.get(i).getName().equals(name)) { return i; } } return null; } @Override public Farmer getFarmer(int index) { // TODO Auto-generated method stub return DataFarm.farmers.get(index); } }
23.815789
71
0.716575
7327d4234dbf382e797b6531ff93cc5aee407edb
2,230
package com.xWash.service.Impl; import cn.hutool.http.HttpException; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.xWash.entity.MStatus; import com.xWash.entity.QueryResult; import com.xWash.service.IChecker; import org.springframework.stereotype.Service; @Service("zhuamChecker") public class ZhuamChecker implements IChecker { private final static int timeout = 5000; private final static String url = "http://zhua.myclassphp.com/index.php?m=Home&c=User&a=getIndexData"; private final JSONObject postBody; { postBody = JSONUtil.parseObj("{\"uid\":\"831342\", \"merid\":\"251181\"}"); } @Override public QueryResult checkByQrLink(String qrLink) { QueryResult qs = new QueryResult(); HttpResponse res = null; JSONObject jo = null; try { res = getResponse(qrLink); jo = JSONUtil.parseObj(res.body()); } catch (HttpException e) { // TODO log return qs; } catch (Exception e) { // TODO log return qs; } switch (res.getStatus()) { case 200: // 通过status设置 Integer status = (Integer) jo.get("status"); if (status.equals(1)) { qs.setStatus(MStatus.AVAILABLE); } else if (status == 0) { qs.setStatus(MStatus.USING); qs.setMessage("已被使用"); }else{ qs.setStatus(MStatus.UNKNOWN); } break; case 401: qs.setStatus(MStatus.UNKNOWN); qs.setMessage("权限过期,请联系管理员"); break; } return qs; } @Override public HttpResponse getResponse(String qrLink) { String body, merid = qrLink.substring(40); // api不变,这样最快 synchronized (postBody) { postBody.set("merid", merid); body = postBody.toString(); } return HttpRequest.post(url) .body(body) .timeout(timeout) .execute(); } }
30.135135
106
0.552466
a60e2ae49a90f4556fc700751a89ccc17b8a436a
1,144
package leetcode_201_250; import java.util.HashMap; /** * leetcode_201_250 * 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。 * 说明: * 你可以假设字符串只包含小写字母。 * 进阶: * 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况? * * 算法1,开辟两个26大小的数组来存计数 * 算法2,两个hashmap * * @author xin * @date 2019-02-28 */ public class ValidAnagram_242 { class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) { return false; } HashMap<Character,Integer> sMap = new HashMap<>(); HashMap<Character,Integer> tMap = new HashMap<>(); for(int i = 0;i<s.length();i++){ char sc = s.charAt(i); char tc = t.charAt(i); if(sMap.containsKey(sc)){ sMap.put(sc, 1); }else { sMap.put(sc,sMap.get(sc)+1); } if(tMap.containsKey(tc)){ tMap.put(tc, 1); }else { tMap.put(tc,sMap.get(tc)+1); } } return sMap.equals(tMap); } } }
24.869565
62
0.476399
c9dcdc1d1c5a722455300c20b329ebc9d8118ecf
2,288
package com.ninja.poohla.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Toast; import com.ninja.poohla.R; import com.ninja.poohla.models.Title; import com.squareup.picasso.Picasso; import java.util.ArrayList; /* Creates the adapter for the (nested) recyclerview */ public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> { private static final String TAG = " Loading Items : "; private ArrayList<Title> itemsList; private Context mContext; public SectionListDataAdapter(Context context, ArrayList<Title> itemsList) { this.itemsList = itemsList; this.mContext = context; } @Override public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, null); SingleItemRowHolder mh = new SingleItemRowHolder(v); return mh; } @Override public void onBindViewHolder(SingleItemRowHolder holder, int i) { Title singleItem = itemsList.get(i); Log.d(TAG , singleItem.getArtKey()); Picasso.with(mContext) .load(mContext.getString(R.string.img_url_start) + singleItem.getArtKey() + "_270.jpeg").into(holder.itemImage); } @Override public int getItemCount() { return (null != itemsList ? itemsList.size() : 0); } public class SingleItemRowHolder extends RecyclerView.ViewHolder { protected ImageView itemImage; public SingleItemRowHolder(View view) { super(view); //images this.itemImage = (ImageView) view.findViewById(R.id.itemImage); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(v.getContext(), "Clicked", Toast.LENGTH_SHORT).show(); } }); } } }
25.707865
127
0.649476
acc952a67ffeb056357f5448ec282ee6cd4ac782
214
package com.example.searchphone.mvp; /** * Created by 许东 on 2018/8/9. */ public interface MvpMainView extends MvpLoadingView{ void showToast(String msg); //显示信息 void updatView(); //更新view }
17.833333
52
0.663551
60cd5173f3c7cbf5928940dd37fab16281b088a8
3,659
/* * Copyright (c) 2005-2016 Clark & Parsia, LLC. <http://www.clarkparsia.com> * * 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.fogsy.empire.cp.common.utils.io; import java.lang.reflect.Method; import java.nio.MappedByteBuffer; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>Utility class which provides a method for attempting to directly unmap a {@link MappedByteBuffer} rather than * waiting for the JVM &amp; OS eventually unmap.</p> * * @author Evren Sirin * @author Michael Grove * @since 1.0 * @version 1.0 */ public final class MMapUtil { public static final Logger LOGGER = LoggerFactory.getLogger(MMapUtil.class); /** * No instances */ private MMapUtil() { throw new AssertionError(); } /** * http://svn.apache.org/repos/asf/lucene/dev/trunk/lucene/src/java/org/apache/lucene/store/MMapDirectory.java * <code>true</code>, if this platform supports unmapping mmapped files. */ public static final boolean UNMAP_SUPPORTED; static { boolean v; try { Class.forName("sun.misc.Cleaner"); Class.forName("java.nio.DirectByteBuffer").getMethod("cleaner"); v = true; } catch (Exception e) { v = false; } UNMAP_SUPPORTED = v; if (!UNMAP_SUPPORTED) { LOGGER.warn("JVM does not support unmapping memory-mapped files."); } } /** * Try to unmap the given {@link java.nio.MappedByteBuffer}. This method enables the workaround for unmapping the * buffers from address space after closing {@link java.nio.MappedByteBuffer}, that is mentioned in the bug report. * This hack may fail on non-Sun JVMs. It forcefully unmaps the buffer on close by using an undocumented internal * cleanup functionality. * * @return <code>true</code> if unmap was successful, <code>false</code> if unmap is not supported by the JVM or if * there was an exception while trying to unmap. */ public static final boolean unmap(final MappedByteBuffer theBuffer) { if (UNMAP_SUPPORTED) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { final Method getCleanerMethod = theBuffer.getClass().getMethod("cleaner"); getCleanerMethod.setAccessible(true); final Object cleaner = getCleanerMethod.invoke(theBuffer); if (cleaner != null) { cleaner.getClass().getMethod("clean").invoke(cleaner); } return null; } }); return true; } catch (PrivilegedActionException e) { LOGGER.warn("Cleaning memory mapped byte buffer failed", e); } } return false; } }
35.872549
119
0.63378
ec5c5640589710fbaf5101e3d40450f72e49f962
367
package br.com.database.dao.model; public class LikeFieldTO extends FieldTO{ public LikeFieldTO(String fieldName) { super(fieldName); } public LikeFieldTO(String fieldName, Object fieldValue) { super(fieldName,fieldValue); } public LikeFieldTO(String fieldName, Object fieldValue, int fieldType) { super(fieldName,fieldValue,fieldType); } }
24.466667
76
0.749319
d5e9f11c1b35af316e4161f5bd76efdca83ae010
2,576
/* * Copyright 2019. The Scouter2 Authors. * * @https://github.com/scouter-project/scouter2 * * 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 scouter2.fixture; import scouter2.proto.Metric4RepoP; import scouter2.proto.MetricTypeP; import scouter2.proto.TimeTypeP; /** * @author Gun Lee (gunlee01@gmail.com) on 2019-08-07 */ public class Metric4RepoPFixture { public static Metric4RepoP getMetric4RepoP(long objId, long timestamp, double counterValue1, double counterValue2) { return Metric4RepoP.newBuilder() .setObjId(objId) .setMetricType(MetricTypeP.MEASURE) .setTimeType(TimeTypeP.REALTIME) .setTimestamp(timestamp) .putMetrics(1L, counterValue1) .putMetrics(2L, counterValue2) .build(); } public static Metric4RepoP getCurrentAny() { return Metric4RepoP.newBuilder() .setObjId(1) .setMetricType(MetricTypeP.MEASURE) .setTimeType(TimeTypeP.REALTIME) .setTimestamp(System.currentTimeMillis()) .putMetrics(1L, 100) .putMetrics(2L, 200) .build(); } public static Metric4RepoP getAny(long objId, long timestamp) { return Metric4RepoP.newBuilder() .setObjId(objId) .setMetricType(MetricTypeP.MEASURE) .setTimeType(TimeTypeP.REALTIME) .setTimestamp(timestamp) .putMetrics(1L, 100) .putMetrics(2L, 200) .build(); } public static Metric4RepoP getAny(long objId, long timestamp, TimeTypeP timeTypeP) { return Metric4RepoP.newBuilder() .setObjId(objId) .setMetricType(MetricTypeP.MEASURE) .setTimeType(timeTypeP) .setTimestamp(timestamp) .putMetrics(1L, 100) .putMetrics(2L, 200) .build(); } }
35.287671
96
0.607919
7d6c3ef6df60a3e2ea3405ef8150070c26e33733
1,168
package com.ruoyi.wx.service; import java.util.List; import com.ruoyi.wx.domain.WxAlternative; /** * 备选老师Service接口 * * @author ruoyi * @date 2021-02-24 */ public interface IWxAlternativeService { /** * 查询备选老师 * * @param traineeId 备选老师ID * @return 备选老师 */ public WxAlternative selectWxAlternativeById(Long traineeId); /** * 查询备选老师列表 * * @param wxAlternative 备选老师 * @return 备选老师集合 */ public List<WxAlternative> selectWxAlternativeList(WxAlternative wxAlternative); /** * 新增备选老师 * * @param wxAlternative 备选老师 * @return 结果 */ public int insertWxAlternative(WxAlternative wxAlternative); /** * 修改备选老师 * * @param wxAlternative 备选老师 * @return 结果 */ public int updateWxAlternative(WxAlternative wxAlternative); /** * 批量删除备选老师 * * @param traineeIds 需要删除的备选老师ID * @return 结果 */ public int deleteWxAlternativeByIds(Long[] traineeIds); /** * 删除备选老师信息 * * @param traineeId 备选老师ID * @return 结果 */ public int deleteWxAlternativeById(WxAlternative wxAlternative); }
18.83871
84
0.61387
5d2047c352338fcc8609c75afa14c885a48cbf6e
168
package fr.masciulli.drinks.view; public interface ViewPagerScrollListener { public void onScroll(int position, float positionOffset, int positionOffsetPixels); }
28
87
0.815476
d9ced6fb5a22bd817b75bed8f6433b6fce83aff7
723
import java.util.Calendar; public class AgeCalculator { private String name; private int ageGroup; public AgeCalculator(String name, int ageGroup){ setName(name); setAgeGroup(ageGroup); } public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setAgeGroup(int ageGroup){ this.ageGroup = ageGroup; } public int getAgeGroup() { return ageGroup; } public void tellAge(){ int year = Calendar.getInstance().get(Calendar.YEAR); int yearOutput = year - ageGroup; System.out.println("Hallo "+ name + " du wirst in diesem Jahr " + yearOutput); } }
21.909091
86
0.611342
1cadc97905b5d08d8c45bdd18bea4c2e4f96ad4d
2,951
package com.hcmus.fitrss.ui.news; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.NavController; import androidx.navigation.fragment.NavHostFragment; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.hcmus.fitrss.GridSpacingItemDecoration; import com.hcmus.fitrss.R; import com.hcmus.fitrss.databinding.FragmentNewsBinding; public class FragmentNews extends Fragment implements SwipeRefreshLayout.OnRefreshListener { private AppCompatActivity activity; private FragmentNewsBinding binding; private AdapterNews adapterNews; private NewsViewModel viewModel; @Override public void onAttach(@NonNull Context context) { super.onAttach(context); if (context instanceof AppCompatActivity) { this.activity = ((AppCompatActivity) context); } } @Override public void onDetach() { super.onDetach(); this.activity = null; } public NavController getNavController() { return NavHostFragment.findNavController(this); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_news, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); binding.swipeLayout.setOnRefreshListener(this); viewModel = new ViewModelProvider(activity).get(NewsViewModel.class); int column = 1, margin = getResources().getDimensionPixelSize(R.dimen.margin_8dp); binding.rvNews.addItemDecoration(new GridSpacingItemDecoration(column, margin, true)); adapterNews = new AdapterNews(activity); adapterNews.setOnItemClickedListener(index -> { viewModel.select(index); getNavController().navigate(R.id.action_view_detail);}); viewModel.getModel().observe(getViewLifecycleOwner(), feedItems -> adapterNews.update(feedItems)); viewModel.fetch(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); binding.rvNews.setAdapter(adapterNews); } @Override public void onRefresh() { binding.swipeLayout.postDelayed(() -> { viewModel.fetch(); binding.swipeLayout.setRefreshing(false); }, 500); } }
34.313953
132
0.731955
20355ef9eed69c012dac79bb4f753665ecda3060
557
package com.hisense.hiatmp.asn.v2x.index; import com.hisense.hiatmp.asn.v2x.basic.BrakeSystemStatus; /** * {@link BrakeSystemStatus} * {@link BrakeSystemStatus.BrakePedalStatus} * {@link BrakeSystemStatus.BrakeAppliedStatus} * {@link BrakeSystemStatus.BrakeBoostApplied} * {@link BrakeSystemStatus.TractionControlStatus} * {@link BrakeSystemStatus.AntiLockBrakeStatus} * {@link BrakeSystemStatus.StabilityControlStatus} * {@link BrakeSystemStatus.AuxiliaryBrakeStatus} * @author zhangyong * @date 2020/12/23 16:01 */ public class VehBrake { }
29.315789
58
0.780969
3babe3120ace76b2c101116290e08c7f1161e90f
3,738
package com.haleywang.putty.view.side.subview; import com.haleywang.putty.dto.AccountDto; import com.haleywang.putty.util.StringUtils; import com.haleywang.putty.view.constraints.MyGridBagConstraints; import com.haleywang.putty.view.side.SideView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridBagLayout; import java.awt.Insets; /** * @author haley * @date 2020/2/2 */ public class AccountPasswordPanel extends JPanel { private static final Logger LOGGER = LoggerFactory.getLogger(AccountPasswordPanel.class); private static final String FOR_GROUP = "For group: "; private final JLabel connectGroupLabel; private final JPasswordField passwordField; private JTextField accountField; public AccountPasswordPanel() { setLayout(new BorderLayout()); JPanel updatePasswordPanel = new JPanel(); updatePasswordPanel.setBorder(new LineBorder(Color.LIGHT_GRAY)); this.setBorder(new EmptyBorder(2, 2, 2, 2)); this.add(updatePasswordPanel); MyGridBagConstraints cs = new MyGridBagConstraints(); cs.insets = new Insets(6, 6, 6, 6); updatePasswordPanel.setLayout(new GridBagLayout()); accountField = new JTextField(null, null, 20); passwordField = new JPasswordField(null, null, 20); connectGroupLabel = new JLabel(FOR_GROUP); connectGroupLabel.setSize(200, 30); cs.ofGridx(0).ofGridy(0).ofWeightx(1); updatePasswordPanel.add(connectGroupLabel, cs); cs.ofGridx(0).ofGridy(1).ofWeightx(1); updatePasswordPanel.add(connectGroupLabel, cs); cs.ofGridx(0).ofGridy(2).ofWeightx(1); updatePasswordPanel.add(new JLabel("Account:"), cs); cs.ofGridx(0).ofGridy(3).ofWeightx(1); updatePasswordPanel.add(accountField, cs); cs.ofGridx(0).ofGridy(4).ofWeightx(1); updatePasswordPanel.add(new JLabel("Password:"), cs); cs.ofGridx(0).ofGridy(5).ofWeightx(1); updatePasswordPanel.add(passwordField, cs); JButton updatePasswordBtn = new JButton("OK"); cs.ofGridx(0).ofGridy(6).ofWeightx(1); updatePasswordPanel.add(updatePasswordBtn, cs); updatePasswordBtn.addActionListener(e -> { LOGGER.info("saveConnectionPassword"); SideView.getInstance().saveConnectionPassword(); }); } public void changePasswordToConnectGroupLabel(DefaultMutableTreeNode node) { if (connectGroupLabel != null) { TreeNode groupNode = node.isLeaf() ? node.getParent() : node; AccountDto dto = SideView.getInstance().getConnectionAccountByNodeName(groupNode.toString()); if (dto != null) { passwordField.setText(dto.getPassword()); accountField.setText(dto.getName()); } else { accountField.setText(""); passwordField.setText(""); } String nodeName = groupNode.toString(); connectGroupLabel.setText(FOR_GROUP + StringUtils.ifBlank(nodeName, "")); } } public JPasswordField getPasswordField() { return passwordField; } public String getNodeName() { return connectGroupLabel.getText().split(FOR_GROUP)[1]; } public JTextField getAccountField() { return accountField; } }
32.789474
105
0.680578
b245581d0323efbaf87cd86fd0092d565bef14cb
5,142
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|index operator|. name|solr operator|. name|util package|; end_package begin_import import|import name|java operator|. name|io operator|. name|File import|; end_import begin_import import|import name|java operator|. name|io operator|. name|FileOutputStream import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|StringWriter import|; end_import begin_import import|import name|javax operator|. name|jcr operator|. name|Session import|; end_import begin_import import|import name|javax operator|. name|jcr operator|. name|nodetype operator|. name|NodeType import|; end_import begin_import import|import name|javax operator|. name|jcr operator|. name|nodetype operator|. name|NodeTypeIterator import|; end_import begin_comment comment|/** * Utility class for generating a Solr synonyms file for expanding {@link javax.jcr.nodetype.NodeType}s */ end_comment begin_class specifier|public class|class name|NodeTypeIndexingUtils block|{ specifier|public specifier|static name|File name|createPrimaryTypeSynonymsFile parameter_list|( name|String name|path parameter_list|, name|Session name|session parameter_list|) throws|throws name|Exception block|{ name|File name|file init|= operator|new name|File argument_list|( name|path argument_list|) decl_stmt|; name|StringWriter name|stringWriter init|= operator|new name|StringWriter argument_list|() decl_stmt|; name|NodeTypeIterator name|allNodeTypes init|= name|session operator|. name|getWorkspace argument_list|() operator|. name|getNodeTypeManager argument_list|() operator|. name|getAllNodeTypes argument_list|() decl_stmt|; while|while condition|( name|allNodeTypes operator|. name|hasNext argument_list|() condition|) block|{ name|NodeType name|nodeType init|= name|allNodeTypes operator|. name|nextNodeType argument_list|() decl_stmt|; name|NodeType index|[] name|superTypes init|= name|nodeType operator|. name|getSupertypes argument_list|() decl_stmt|; if|if condition|( name|superTypes operator|!= literal|null operator|&& name|superTypes operator|. name|length operator|> literal|0 condition|) block|{ name|stringWriter operator|. name|append argument_list|( name|nodeType operator|. name|getName argument_list|() argument_list|) operator|. name|append argument_list|( literal|" => " argument_list|) expr_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|superTypes operator|. name|length condition|; name|i operator|++ control|) block|{ name|stringWriter operator|. name|append argument_list|( name|superTypes index|[ name|i index|] operator|. name|getName argument_list|() argument_list|) expr_stmt|; if|if condition|( name|i operator|< name|superTypes operator|. name|length operator|- literal|1 condition|) block|{ name|stringWriter operator|. name|append argument_list|( literal|',' argument_list|) expr_stmt|; block|} name|stringWriter operator|. name|append argument_list|( literal|' ' argument_list|) expr_stmt|; block|} name|stringWriter operator|. name|append argument_list|( literal|'\n' argument_list|) expr_stmt|; block|} block|} name|FileOutputStream name|fileOutputStream init|= operator|new name|FileOutputStream argument_list|( name|file argument_list|) decl_stmt|; name|fileOutputStream operator|. name|write argument_list|( name|stringWriter operator|. name|toString argument_list|() operator|. name|getBytes argument_list|( literal|"UTF-8" argument_list|) argument_list|) expr_stmt|; name|fileOutputStream operator|. name|flush argument_list|() expr_stmt|; name|fileOutputStream operator|. name|close argument_list|() expr_stmt|; if|if condition|( name|file operator|. name|exists argument_list|() operator||| name|file operator|. name|createNewFile argument_list|() condition|) block|{ return|return name|file return|; block|} else|else block|{ throw|throw operator|new name|IOException argument_list|( literal|"primary types synonyms file could not be created" argument_list|) throw|; block|} block|} block|} end_class end_unit
15.168142
809
0.790937
c569788fad3e752dfe1fd998ca4c8a9e44afdc4d
1,520
package name.aliaksandrch.px.beans; import java.io.Serializable; import com.google.gson.annotations.SerializedName; /** * The short format of a User object. * * @author Aliaksandr_Chaiko * @version 0.1 */ public class User implements Serializable{ private static final long serialVersionUID = -6617481034264379462L; private int id; private String username; private String firstName; private String lastName; private String city; private String country; @SerializedName("upgrade_status") private String upgradeStatus; public User(){ } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getUpgradeStatus() { return upgradeStatus; } public void setUpgradeStatus(String upgradeStatus) { this.upgradeStatus = upgradeStatus; } public static long getSerialversionuid() { return serialVersionUID; } }
16.344086
68
0.719737
5725c9dda980190f3349b2c61a691f18c39a5bd3
3,874
package com.tcc.sospets.controllers; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.tcc.sospets.business.models.dto.FBRequest; import com.tcc.sospets.business.models.dto.GoogleAuthRequest; import com.tcc.sospets.business.models.dto.TokenResponse; import com.tcc.sospets.business.models.entities.User; import com.tcc.sospets.business.repositories.IUserRepositorio; import com.tcc.sospets.services.classes.JwtUserDetailsService; import com.tcc.sospets.services.interfaces.IFirebaseService; import com.tcc.sospets.utils.JwtTokenUtil; import org.apache.http.HttpException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.List; @RestController @RequestMapping("/auth") public class AuthControler { @Autowired IFirebaseService firebaseService; @Autowired JwtTokenUtil jwtTokenUtil; @Autowired JwtUserDetailsService jwtUserDetailsService; @Autowired IUserRepositorio userRepositorio; @PostMapping("/register") public void registraUsuarioFirebase(@RequestBody FBRequest fbRequest) throws Exception { firebaseService.register(fbRequest); String email = fbRequest.getEmail(); User user = new User(); user.setEmail(email); userRepositorio.save(user); } @PostMapping("/login") public TokenResponse autenticaUsuarioFirebase(@RequestBody FBRequest fbRequest) throws Exception { firebaseService.login(fbRequest); UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(fbRequest.getEmail()); String token = jwtTokenUtil.generateToken(userDetails); return new TokenResponse(token); } @PostMapping("/loginWithGoogle") public TokenResponse autenticaUsuariocomGoogle(@RequestBody GoogleAuthRequest googleAuthRequest) throws Exception { HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new GsonFactory(); String clientId = "182449133691-9jihapbpjtec5tqfkirakua2vqs3r1vb.apps.googleusercontent.com"; GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(httpTransport, jsonFactory) .setAudience(Collections.singletonList(clientId)) .build(); GoogleIdToken idToken = verifier.verify(googleAuthRequest.getGoogleToken()); if (idToken != null) { GoogleIdToken.Payload payload = idToken.getPayload(); String userId = payload.getSubject(); System.out.println("User ID: " + userId); String email = payload.getEmail(); String name = (String) payload.get("name"); String pictureUrl = (String) payload.get("picture"); UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(email); String token = jwtTokenUtil.generateToken(userDetails); return new TokenResponse(token); } throw new HttpException(); } @PostMapping("/logout") public void logout (String token, List < String > tokens){ tokens.remove(token); } }
39.530612
123
0.715539
422084aa656aaeffb6c93f6109057c761d0280b7
1,592
package com.well.swipe.preference; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; import android.widget.TextView; import com.well.swipe.R; /** * Created by mingwei on 3/31/16. * * * 微博: 明伟小学生(http://weibo.com/u/2382477985) * Github: https://github.com/gumingwei * CSDN: http://blog.csdn.net/u013045971 * QQ&WX: 721881283 * * */ public class PreferenceTitle extends SwipePreference { private TextView mTitle; private ImageView mIcon; private ImageView mArrow; public PreferenceTitle(Context context) { this(context, null); } public PreferenceTitle(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PreferenceTitle(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onFinishInflate() { super.onFinishInflate(); mTitle = (TextView) findViewById(R.id.preference_title); mIcon = (ImageView) findViewById(R.id.preference_icon); mArrow = (ImageView) findViewById(R.id.preference_arraw); } public void setTitle(int title) { setTitle(getResources().getString(title)); } public void setTitle(String title) { mTitle.setText(title); } public void setIcon(Drawable drawable) { mIcon.setVisibility(VISIBLE); mIcon.setImageDrawable(drawable); } public void showArrow() { mArrow.setVisibility(VISIBLE); } }
23.411765
83
0.676508
9a19c67819dd113d1be044fd26effad518ed11b4
1,676
package com.skytala.eCommerce.domain.accounting.relations.payment.command.gatewaySagePay; import org.apache.ofbiz.entity.Delegator; import org.apache.ofbiz.entity.DelegatorFactory; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; import com.skytala.eCommerce.domain.accounting.relations.payment.event.gatewaySagePay.PaymentGatewaySagePayAdded; import com.skytala.eCommerce.domain.accounting.relations.payment.mapper.gatewaySagePay.PaymentGatewaySagePayMapper; import com.skytala.eCommerce.domain.accounting.relations.payment.model.gatewaySagePay.PaymentGatewaySagePay; import com.skytala.eCommerce.framework.pubsub.Broker; import com.skytala.eCommerce.framework.pubsub.Command; import com.skytala.eCommerce.framework.pubsub.Event; import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit; public class AddPaymentGatewaySagePay extends Command { private PaymentGatewaySagePay elementToBeAdded; public AddPaymentGatewaySagePay(PaymentGatewaySagePay elementToBeAdded){ this.elementToBeAdded = elementToBeAdded; } @Override public Event execute(){ Delegator delegator = DelegatorFactory.getDelegator("default"); PaymentGatewaySagePay addedElement = null; boolean success = false; try { GenericValue newValue = delegator.makeValue("PaymentGatewaySagePay", elementToBeAdded.mapAttributeField()); addedElement = PaymentGatewaySagePayMapper.map(delegator.create(newValue)); success = true; } catch(GenericEntityException e) { e.printStackTrace(); addedElement = null; } Event resultingEvent = new PaymentGatewaySagePayAdded(addedElement, success); Broker.instance().publish(resultingEvent); return resultingEvent; } }
38.976744
115
0.847852
09077976d5e33d96ff9b7669cf9fa9e421607607
1,003
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.oastem.frc.pid; import edu.wpi.first.wpilibj.PIDSource; /** * * @author KTOmega */ public class TargetSource { private double[] vals; public TargetSource(double[] params) { vals = new double[params.length]; update(params); } public TargetSource(int i) { vals = new double[i]; } public void update(double[] params) { if (params.length != vals.length) { throw new ArrayIndexOutOfBoundsException("Parameter array length does not match internal array length"); } vals = params; } public double get(int index) { return vals[index]; } public PIDSource getSource(final int index) { return new PIDSource() { public double pidGet() { return vals[index]; } }; } }
22.795455
117
0.555334
14f5ca50546300584a0578ff711a9c7375664bb1
385
package krjakbrjak.bazel.plugin.services; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.testFramework.IdeaTestUtil; import krjakbrjak.bazel.plugin.project.services.JdkResolver; public class JdkResolverTest implements JdkResolver { @Override public Sdk resolveJdk(String javaHome) { return IdeaTestUtil.createMockJdk("test jdk", javaHome); } }
29.615385
64
0.78961
b5ed965732d7d9f7b27778c56043f013e25e6c06
164
package com.dipanjal.batch1.generics.example1; public class NumberPrinter<T extends Number> { public void print(T t) { System.out.println(t); } }
18.222222
46
0.682927
20e622994cffae6260fe953b1d5275aa6328f507
196
package aa.sw.command.run; import aa.sw.command.CommandResult; @FunctionalInterface public interface RunnableEntryExecutionStrategy { CommandResult execute(CommandRunnerContext context); }
19.6
56
0.826531
7c05e7f477c61fd70a224ebaf173ea479a817601
17,737
/* Copyright 2017 Alfa Financial Software * * 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.alfasoftware.morf.upgrade; import static org.alfasoftware.morf.metadata.SchemaUtils.column; import java.util.HashSet; import java.util.List; import java.util.Set; import org.alfasoftware.morf.metadata.Column; import org.alfasoftware.morf.metadata.Index; import org.alfasoftware.morf.metadata.Schema; import org.alfasoftware.morf.metadata.SchemaUtils.ColumnBuilder; import org.alfasoftware.morf.metadata.Table; import org.alfasoftware.morf.sql.SelectStatement; import org.alfasoftware.morf.sql.Statement; import org.alfasoftware.morf.sql.element.FieldLiteral; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; /** * Tracks a sequence of {@link SchemaChange}s as various {@link SchemaEditor} * methods are called to specify the database schema changes required for an * upgrade. * * @author Copyright (c) Alfa Financial Software 2010 */ public class SchemaChangeSequence { private final List<UpgradeStep> upgradeSteps; private final Set<String> tableAdditions = new HashSet<>(); private final List<UpgradeStepWithChanges> allChanges = Lists.newArrayList(); private final UpgradeTableResolution upgradeTableResolution = new UpgradeTableResolution(); /** * Create an instance of {@link SchemaChangeSequence}. * * @param steps the upgrade steps */ public SchemaChangeSequence(List<UpgradeStep> steps) { upgradeSteps = steps; for (UpgradeStep step : steps) { InternalVisitor internalVisitor = new InternalVisitor(); UpgradeTableResolutionVisitor resolvedTablesVisitor = new UpgradeTableResolutionVisitor(); Editor editor = new Editor(internalVisitor, resolvedTablesVisitor); // For historical reasons, we need to pass the editor in twice step.execute(editor, editor); allChanges.add(new UpgradeStepWithChanges(step, internalVisitor.getChanges())); upgradeTableResolution.addDiscoveredTables(step.getClass().getName(), resolvedTablesVisitor.getResolvedTables()); } } /** * Applies the changes to the given schema. * * @param initialSchema The schema to apply changes to. * @return the resulting schema after applying changes in this sequence */ public Schema applyToSchema(Schema initialSchema) { Schema currentSchema = initialSchema; for (UpgradeStepWithChanges changesForStep : allChanges) { for (SchemaChange change : changesForStep.getChanges()) { try { currentSchema = change.apply(currentSchema); } catch (RuntimeException rte) { throw new RuntimeException("Failed to apply change [" + change + "] from upgrade step " + changesForStep.getUpgradeClass(), rte); } } } return currentSchema; } /** * Applies the change reversals to the given schema. * * @param initialSchema The schema to apply changes to. * @return the resulting schema after applying reverse changes in this sequence */ public Schema applyInReverseToSchema(Schema initialSchema) { Schema currentSchema = initialSchema; // we need to reverse the order of the changes inside the step before we try to reverse-execute them for (UpgradeStepWithChanges changesForStep : Lists.reverse(allChanges)) { for (SchemaChange change : Lists.reverse(changesForStep.getChanges())) { try { currentSchema = change.reverse(currentSchema); } catch (RuntimeException rte) { throw new RuntimeException("Failed to reverse-apply change [" + change + "] from upgrade step " + changesForStep.getUpgradeClass(), rte); } } } return currentSchema; } /** * @return the upgradeSteps */ public List<UpgradeStep> getUpgradeSteps() { return ImmutableList.copyOf(upgradeSteps); } /** * @return {@link UpgradeTableResolution} for this upgrade */ public UpgradeTableResolution getUpgradeTableResolution() { return upgradeTableResolution; } /** * @param visitor The schema change visitor against which to write the changes. */ public void applyTo(SchemaChangeVisitor visitor) { for (UpgradeStepWithChanges changesForStep : allChanges) { try { visitor.startStep(changesForStep.getUpgradeClass()); for (SchemaChange change : changesForStep.getChanges()) { change.accept(visitor); } visitor.addAuditRecord(changesForStep.getUUID(), changesForStep.getDescription()); } catch (Exception e) { throw new RuntimeException("Failed to apply step: [" + changesForStep.getUpgradeClass() + "]", e); } } } /** * @return The set of all table which are added by this sequence. */ public Set<String> tableAdditions() { return tableAdditions; } /** * The editor implementation which is used by upgrade steps */ private class Editor implements SchemaEditor, DataEditor { private final SchemaChangeVisitor visitor; private final SchemaAndDataChangeVisitor schemaAndDataChangeVisitor; /** * @param visitor The visitor to pass the changes to. */ Editor(SchemaChangeVisitor visitor, SchemaAndDataChangeVisitor schemaAndDataChangeVisitor) { super(); this.visitor = visitor; this.schemaAndDataChangeVisitor = schemaAndDataChangeVisitor; } /** * @see org.alfasoftware.morf.upgrade.DataEditor#executeStatement(org.alfasoftware.morf.sql.Statement) */ @Override public void executeStatement(Statement statement) { visitor.visit(new ExecuteStatement(statement)); statement.accept(schemaAndDataChangeVisitor); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#addColumn(java.lang.String, org.alfasoftware.morf.metadata.Column) */ @Override public void addColumn(String tableName, Column definition, FieldLiteral defaultValue) { // create a new Column with the default and add this first ColumnBuilder temporaryDefinitionWithDefault = column(definition.getName(), definition.getType(), definition.getWidth(), definition.getScale()).defaultValue(defaultValue.getValue()); temporaryDefinitionWithDefault = definition.isNullable() ? temporaryDefinitionWithDefault.nullable() : temporaryDefinitionWithDefault; temporaryDefinitionWithDefault = definition.isPrimaryKey() ? temporaryDefinitionWithDefault.primaryKey() : temporaryDefinitionWithDefault; addColumn(tableName, temporaryDefinitionWithDefault); // now move to the final column definition, which may not have the default value. changeColumn(tableName, temporaryDefinitionWithDefault, definition); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#addColumn(java.lang.String, org.alfasoftware.morf.metadata.Column) */ @Override public void addColumn(String tableName, Column definition) { AddColumn addColumn = new AddColumn(tableName, definition); visitor.visit(addColumn); schemaAndDataChangeVisitor.visit(addColumn); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#addTable(org.alfasoftware.morf.metadata.Table) */ @Override public void addTable(Table definition) { // track added tables... tableAdditions.add(definition.getName()); AddTable addTable = new AddTable(definition); visitor.visit(addTable); schemaAndDataChangeVisitor.visit(addTable); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#removeTable(org.alfasoftware.morf.metadata.Table) */ @Override public void removeTable(Table table) { RemoveTable removeTable = new RemoveTable(table); visitor.visit(removeTable); schemaAndDataChangeVisitor.visit(removeTable); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#changeColumn(java.lang.String, org.alfasoftware.morf.metadata.Column, org.alfasoftware.morf.metadata.Column) */ @Override public void changeColumn(String tableName, Column fromDefinition, Column toDefinition) { ChangeColumn changeColumn = new ChangeColumn(tableName, fromDefinition, toDefinition); visitor.visit(changeColumn); schemaAndDataChangeVisitor.visit(changeColumn); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#removeColumn(java.lang.String, org.alfasoftware.morf.metadata.Column) */ @Override public void removeColumn(String tableName, Column definition) { RemoveColumn removeColumn = new RemoveColumn(tableName, definition); visitor.visit(removeColumn); schemaAndDataChangeVisitor.visit(removeColumn); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#removeColumns(java.lang.String, org.alfasoftware.morf.metadata.Column[]) */ @Override public void removeColumns(String tableName, Column... definitions) { // simple redirect for now, but a future optimisation could re-implement this to be more efficient for (Column definition : definitions) { removeColumn(tableName, definition); } } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#addIndex(java.lang.String, org.alfasoftware.morf.metadata.Index) */ @Override public void addIndex(String tableName, Index index) { AddIndex addIndex = new AddIndex(tableName, index); visitor.visit(addIndex); schemaAndDataChangeVisitor.visit(addIndex); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#removeIndex(java.lang.String, org.alfasoftware.morf.metadata.Index) */ @Override public void removeIndex(String tableName, Index index) { RemoveIndex removeIndex = new RemoveIndex(tableName, index); visitor.visit(removeIndex); schemaAndDataChangeVisitor.visit(removeIndex); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#changeIndex(java.lang.String, org.alfasoftware.morf.metadata.Index, org.alfasoftware.morf.metadata.Index) */ @Override public void changeIndex(String tableName, Index fromIndex, Index toIndex) { ChangeIndex changeIndex = new ChangeIndex(tableName, fromIndex, toIndex); visitor.visit(changeIndex); schemaAndDataChangeVisitor.visit(changeIndex); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#renameIndex(java.lang.String, java.lang.String, java.lang.String) */ @Override public void renameIndex(String tableName, String fromIndexName, String toIndexName) { RenameIndex removeIndex = new RenameIndex(tableName, fromIndexName, toIndexName); visitor.visit(removeIndex); schemaAndDataChangeVisitor.visit(removeIndex); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#renameTable(java.lang.String, java.lang.String) */ @Override public void renameTable(String fromTableName, String toTableName) { tableAdditions.add(toTableName); RenameTable renameTable = new RenameTable(fromTableName, toTableName); visitor.visit(renameTable); schemaAndDataChangeVisitor.visit(renameTable); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#changePrimaryKeyColumns(java.lang.String, java.util.List, java.util.List) */ @Override public void changePrimaryKeyColumns(String tableName, List<String> oldPrimaryKeyColumns, List<String> newPrimaryKeyColumns) { ChangePrimaryKeyColumns changePrimaryKeyColumns = new ChangePrimaryKeyColumns(tableName, oldPrimaryKeyColumns, newPrimaryKeyColumns); visitor.visit(changePrimaryKeyColumns); schemaAndDataChangeVisitor.visit(changePrimaryKeyColumns); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#correctPrimaryKeyColumns(java.lang.String, java.util.List) * @deprecated This change step should never be required, use {@link #changePrimaryKeyColumns(String, List, List)} * instead. This method will be removed when upgrade steps before 5.2.14 are removed. */ @Override @Deprecated public void correctPrimaryKeyColumns(String tableName, List<String> newPrimaryKeyColumns) { CorrectPrimaryKeyColumns correctPrimaryKeyColumns = new CorrectPrimaryKeyColumns(tableName, newPrimaryKeyColumns); visitor.visit(correctPrimaryKeyColumns); schemaAndDataChangeVisitor.visit(correctPrimaryKeyColumns); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#addTableFrom(org.alfasoftware.morf.metadata.Table, org.alfasoftware.morf.sql.SelectStatement) */ @Override public void addTableFrom(Table table, SelectStatement select) { // track added tables... tableAdditions.add(table.getName()); AddTable addTable = new AddTableFrom(table, select); visitor.visit(addTable); schemaAndDataChangeVisitor.visit(addTable); select.accept(schemaAndDataChangeVisitor); } /** * @see org.alfasoftware.morf.upgrade.SchemaEditor#analyseTable(org.alfasoftware.morf.metadata.Table) */ @Override public void analyseTable(String tableName) { AnalyseTable analyseTable = new AnalyseTable(tableName); visitor.visit(analyseTable); schemaAndDataChangeVisitor.visit(analyseTable); } } /** * Encapsulates an {@link UpgradeStep} and the list of {@link SchemaChange} it generates. * * @author Copyright (c) Alfa Financial Software 2014 */ private static class UpgradeStepWithChanges { private final UpgradeStep delegate; private final List<SchemaChange> changes; /** * @param delegate * @param changes */ UpgradeStepWithChanges(UpgradeStep delegate, List<SchemaChange> changes) { super(); this.delegate = delegate; this.changes = changes; } public Class<? extends UpgradeStep> getUpgradeClass() { return delegate.getClass(); } public String getDescription() { return delegate.getDescription(); } /** * @return the changes */ public List<SchemaChange> getChanges() { return changes; } public java.util.UUID getUUID() { return java.util.UUID.fromString(delegate.getClass().getAnnotation(UUID.class).value()); } } /** * SchemaChangeVisitor which redirects the calls onto the apply() method. */ private static class InternalVisitor implements SchemaChangeVisitor { private final List<SchemaChange> changes = Lists.newArrayList(); /** * @return the changes */ public List<SchemaChange> getChanges() { return changes; } @Override public void visit(ExecuteStatement executeStatement) { changes.add(executeStatement); } @Override public void visit(ChangeIndex changeIndex) { changes.add(changeIndex); } @Override public void visit(RemoveIndex removeIndex) { changes.add(removeIndex); } @Override public void visit(RemoveColumn removeColumn) { changes.add(removeColumn); } @Override public void visit(ChangeColumn changeColumn) { changes.add(changeColumn); } @Override public void visit(AddIndex addIndex) { changes.add(addIndex); } @Override public void visit(RemoveTable removeTable) { changes.add(removeTable); } @Override public void visit(AddTable addTable) { changes.add(addTable); } @Override public void visit(AddColumn addColumn) { changes.add(addColumn); } @Override public void addAuditRecord(java.util.UUID uuid, String description) { // no-op here. We don't need to record the UUIDs until we actually apply the changes. } @Override public void startStep(Class<? extends UpgradeStep> upgradeClass) { // no-op here. We don't care what step is running } @Override public void visit(RenameTable renameTable) { changes.add(renameTable); } @Override public void visit(ChangePrimaryKeyColumns changePrimaryKeyColumns) { changes.add(changePrimaryKeyColumns); } /** * @see org.alfasoftware.morf.upgrade.SchemaChangeVisitor#visit(org.alfasoftware.morf.upgrade.RenameIndex) */ @Override public void visit(RenameIndex renameIndex) { changes.add(renameIndex); } /** * @see org.alfasoftware.morf.upgrade.SchemaChangeVisitor#visit(org.alfasoftware.morf.upgrade.AddTableFrom) */ @Override public void visit(AddTableFrom addTableFrom) { changes.add(addTableFrom); } @Override public void visit(AnalyseTable analyseTable) { changes.add(analyseTable); } } }
32.544954
189
0.689294
236d87b39c44d4ac44b570e810f1171fd1f36bf8
541
package com.chimpler.simtick.readers; import com.chimpler.simtick.writers.LongWriter; public abstract class Reader<T> { // reuse same object to avoid reinstantiation every time protected final ValueAndLength<T> valueAndLength; public final boolean fixed; public abstract ValueAndLength<T> readRaw(byte[] buffer, int offset); public abstract ValueAndLength<T> readDelta(byte[] buffer, int offset); public Reader(boolean fixed) { this.fixed = fixed; valueAndLength = new ValueAndLength(); } }
27.05
75
0.724584
2bc4d9c9ef39b2d71a1bf1be786207a529548ec5
836
package io.ayte.utility.function.kit.unary.optional; import io.ayte.utility.function.kit.AugmentedFunction; import lombok.AccessLevel; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.ToString; import java.util.Optional; import java.util.function.Function; @ToString(includeFieldNames = false) @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class Map<I, O> implements AugmentedFunction<Optional<I>, Optional<O>> { private final Function<? super I, ? extends O> transformer; @Override public Optional<O> apply(@NonNull Optional<I> subject) { return subject.map(transformer); } public static <I, O> Function<Optional<I>, Optional<O>> create( @NonNull Function<? super I, ? extends O> transformer ) { return new Map<>(transformer); } }
29.857143
79
0.729665
3faa12099bbf5534ebffe664780d7a6e238ea5b5
4,494
package org.lnu.is.extractor.person.pension; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.lnu.is.dao.dao.Dao; import org.lnu.is.domain.common.RowStatus; import org.lnu.is.domain.pension.type.PensionType; import org.lnu.is.domain.person.Person; import org.lnu.is.domain.person.pension.PersonPension; import org.lnu.is.security.service.SessionService; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class PersonPensionParametersExtractorTest { @Mock private Dao<Person, Person, Long> personDao; @Mock private Dao<PensionType, PensionType, Long> contactTypeDao; @InjectMocks private PersonPensionParametersExtractor unit; @Mock private SessionService sessionService; private Boolean active = true; private Boolean security = true; private String group1 = "developers"; private String group2 = "students"; private List<String> groups = Arrays.asList(group1, group2); @Before public void setup() { unit.setActive(active); unit.setSecurity(security); when(sessionService.getGroups()).thenReturn(groups); } @Test public void testGetParameters() throws Exception { // Given Long personId = 1L; Person person = new Person(); person.setId(personId); Long contactTypeId = 2L; PensionType contactType = new PensionType(); contactType.setId(contactTypeId); PersonPension entity = new PersonPension(); entity.setPerson(person); entity.setPensionType(contactType); Map<String, Object> expected = new HashMap<String, Object>(); expected.put("status", RowStatus.ACTIVE); expected.put("userGroups", groups); expected.put("person", person); expected.put("pensionType", contactType); // When when(personDao.getEntityById(anyLong())).thenReturn(person); when(contactTypeDao.getEntityById(anyLong())).thenReturn(contactType); Map<String, Object> actual = unit.getParameters(entity); // Then verify(personDao).getEntityById(personId); verify(contactTypeDao).getEntityById(contactTypeId); assertEquals(expected, actual); } @Test public void testGetParametersWithEmptyFields() throws Exception { // Given PersonPension entity = new PersonPension(); Map<String, Object> expected = new HashMap<String, Object>(); expected.put("status", RowStatus.ACTIVE); expected.put("userGroups", groups); // When Map<String, Object> actual = unit.getParameters(entity); // Then verify(personDao, times(0)).getEntityById(anyLong()); verify(contactTypeDao, times(0)).getEntityById(anyLong()); assertEquals(expected, actual); } @Test public void testGetParametersWithEmptyFieldsAndWithoutDefaults() throws Exception { // Given unit.setActive(false); unit.setSecurity(false); PersonPension entity = new PersonPension(); Map<String, Object> expected = new HashMap<String, Object>(); // When Map<String, Object> actual = unit.getParameters(entity); // Then verify(personDao, times(0)).getEntityById(anyLong()); verify(contactTypeDao, times(0)).getEntityById(anyLong()); assertEquals(expected, actual); } @Test public void testGetParamteresWithoutSecurity() throws Exception { // Given unit.setSecurity(false); Long personId = 1L; Person person = new Person(); person.setId(personId); Long contactTypeId = 2L; PensionType contactType = new PensionType(); contactType.setId(contactTypeId); PersonPension entity = new PersonPension(); entity.setPerson(person); entity.setPensionType(contactType); Map<String, Object> expected = new HashMap<String, Object>(); expected.put("status", RowStatus.ACTIVE); expected.put("person", person); expected.put("pensionType", contactType); // When when(personDao.getEntityById(anyLong())).thenReturn(person); when(contactTypeDao.getEntityById(anyLong())).thenReturn(contactType); Map<String, Object> actual = unit.getParameters(entity); // Then verify(personDao).getEntityById(personId); verify(contactTypeDao).getEntityById(contactTypeId); verify(sessionService, times(0)).getGroups(); assertEquals(expected.toString(), actual.toString()); } }
27.740741
72
0.754339
029fd895c017d1d837cdf2031736345542bc6bc8
1,485
package uk.gov.companieshouse.certifiedcopies.orders.api.validator; import org.springframework.stereotype.Component; import uk.gov.companieshouse.certifiedcopies.orders.api.dto.CertifiedCopyItemOptionsRequestDTO; import uk.gov.companieshouse.certifiedcopies.orders.api.dto.CertifiedCopyItemRequestDTO; import uk.gov.companieshouse.certifiedcopies.orders.api.util.FieldNameConverter; import java.util.ArrayList; import java.util.List; /** * Implements validation of the request payload specific to the the create item request only. */ @Component public class CreateCertifiedCopyItemRequestValidator extends RequestValidator { private final FieldNameConverter converter; /** * Constructor. * @param converter the converter this uses to present field names as they appear in the request JSON payload */ public CreateCertifiedCopyItemRequestValidator(FieldNameConverter converter) { this.converter = converter; } /** * Validates the item provided, returning any errors found. * @param item the item to be validated * @return the errors found, which will be empty if the item is found to be valid */ public List<String> getValidationErrors(final CertifiedCopyItemRequestDTO item) { final List<String> errors = new ArrayList<>(); final CertifiedCopyItemOptionsRequestDTO options = item.getItemOptions(); errors.addAll(getValidationErrors(options, converter)); return errors; } }
37.125
113
0.762963
3731036066c1d244e3cfb378fab40209186e6dfa
2,106
package offer; /** * @Title: Question12 * @ProjectName java-utils * @Description: TODO * @Author liunengkai * @Date: 2020-01-11 23:08 * @Description:题目:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。保证base和exponent不同时为0 */ public class Question12 { public static void main(String[] args) { System.out.println(Integer.toBinaryString(15)); System.out.println(Integer.toBinaryString(16)); System.out.println("15 & 1:"+(15 & 1)); System.out.println("15 & 1:"+Integer.toBinaryString((15 & 1))); System.out.println("16 & 1:"+(16 & 1)); System.out.println("16 & 1:"+Integer.toBinaryString((16 & 1))); } /** * @param base 底数 * @param exponent 指数 * @return */ public double Power(double base, int exponent) { /** * 可能的情形: * base == 0 && exponent > 0 ->0 * base == 0 && exponent == 0 ->未定义 * base == 0 && exponent < 0 ->异常 * base != 0 && exponent > 0 ->乘方 * base != 0 && exponent == 0 ->1 * base != 0 && exponent > 0 ->倒底数,反指数 * 当n为偶数,a^n =(a^n/2)*(a^n/2) * 当n为奇数,a^n = a^[(n-1)/2] * a^[(n-1)/2] * a */ if (base == 0) { if (exponent > 0) { return 0; } else if (exponent == 0) { return 0; } else { throw new RuntimeException(); } } else { if (exponent > 0) { return power(base, exponent); } else if (exponent == 0) { return 1; } else { return 1 / power(base, -exponent); } } } public double power(double base, int exp) { if (exp == 1) { return base; } // 利用计算机位运算判断是否为奇数 // 15 & 1 = 1 // 16 & 1 = 0 if ((exp & 1) == 0) { double tmp = power(base, exp >> 1); return tmp * tmp; } else { double tmp = power(base, (exp - 1) >> 1); return tmp * tmp * base; } } }
27.350649
94
0.456315
2750e808d3fb3412dd29e770fad3e3d06e2d96f6
38,825
/* * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.charon3.core.protocol.endpoints; import org.json.JSONObject; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.charon3.core.encoder.JSONDecoder; import org.wso2.charon3.core.encoder.JSONEncoder; import org.wso2.charon3.core.exceptions.AbstractCharonException; import org.wso2.charon3.core.exceptions.BadRequestException; import org.wso2.charon3.core.exceptions.CharonException; import org.wso2.charon3.core.exceptions.ConflictException; import org.wso2.charon3.core.exceptions.InternalErrorException; import org.wso2.charon3.core.exceptions.NotFoundException; import org.wso2.charon3.core.exceptions.NotImplementedException; import org.wso2.charon3.core.extensions.UserManager; import org.wso2.charon3.core.objects.Group; import org.wso2.charon3.core.protocol.ResponseCodeConstants; import org.wso2.charon3.core.protocol.SCIMResponse; import org.wso2.charon3.core.schema.SCIMConstants; import org.wso2.charon3.core.schema.SCIMResourceSchemaManager; import org.wso2.charon3.core.schema.SCIMResourceTypeSchema; import org.wso2.charon3.core.schema.ServerSideValidator; import org.wso2.charon3.core.utils.CopyUtil; import org.wso2.charon3.core.utils.ResourceManagerUtil; import java.util.HashMap; import java.util.Map; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; /** * Test class of GroupResourceManager. */ public class GroupResourceManagerTest { private static final String GROUP_ID = "71239"; private static final String SCIM2_GROUP_ENDPOINT = "https://localhost:9443/scim2/Groups"; private static final String NEW_GROUP_SCIM_OBJECT_STRING = "{\n" + " \"schemas\": [\n" + " \"urn:ietf:params:scim:api:messages:2.0:ListResponse\"\n" + " ],\n" + " \"displayName\": \"PRIMARY/manager\",\n" + " \"meta\": {\n" + " \"created\": \"2019-08-26T14:27:36\",\n" + " \"location\": \"https://localhost:9443/scim2/Groups/7bac6a86-1f21-4937-9fb1-5be4a93ef469\",\n" + " \"lastModified\": \"2019-08-26T14:27:36\"\n" + " },\n" + " \"members\": [\n" + " {\n" + " \"$ref\": \"https://localhost:9443/scim2/Users/3a12bae9-4386-44be-befd-caf349297f45\",\n" + " \"display\": \"kim\",\n" + " \"value\": \"008bba85-451d-414b-87de-c03b5a1f4217\"\n" + " }\n" + " ],\n" + " \"id\": \"" + GROUP_ID + "\"\n" + " }\n" + " ]\n" + "}"; private static final String NEW_GROUP_SCIM_OBJECT_STRING_UPDATED = "{\n" + " \"schemas\": [\n" + " \"urn:ietf:params:scim:api:messages:2.0:ListResponse,\"\n" + " ],\n" + " \"displayName\": \"PRIMARY/manager_sales\",\n" + " \"meta\": {\n" + " \"created\": \"2019-08-26T14:27:36\",\n" + " \"location\": \"https://localhost:9443/scim2/Groups/7bac6a86-1f21-4937-9fb1-5be4a93ef469\",\n" + " \"lastModified\": \"2019-08-26T14:28:36\"\n" + " },\n" + " \"members\": [\n" + " {\n" + " \"$ref\": \"https://localhost:9443/scim2/Users/3a12bae9-4386-44be-befd-caf349297f45\",\n" + " \"display\": \"kim\",\n" + " \"value\": \"008bba85-451d-414b-87de-c03b5a1f4217\"\n" + " }\n" + " ],\n" + " \"id\": \"" + GROUP_ID + "\"\n" + " }\n" + " ]\n" + "}"; private GroupResourceManager groupResourceManager; private UserManager userManager; private MockedStatic<AbstractResourceManager> abstractResourceManager; @BeforeMethod public void setUp() { groupResourceManager = new GroupResourceManager(); abstractResourceManager = Mockito.mockStatic(AbstractResourceManager.class); userManager = mock(UserManager.class); abstractResourceManager.when(AbstractResourceManager::getEncoder).thenReturn(new JSONEncoder()); abstractResourceManager.when(AbstractResourceManager::getDecoder).thenReturn(new JSONDecoder()); } @AfterMethod public void tearDown() { abstractResourceManager.close(); } private SCIMResponse getEncodeSCIMExceptionObject(AbstractCharonException exception) { JSONEncoder encoder = new JSONEncoder(); Map<String, String> responseHeaders = new HashMap<>(); responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON); return new SCIMResponse(exception.getStatus(), encoder.encodeSCIMException(exception), responseHeaders); } private Group getNewGroup() throws BadRequestException, CharonException, InternalErrorException { SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); JSONDecoder decoder = new JSONDecoder(); return decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING, schema, new Group()); } @DataProvider(name = "dataForGetGroupSuccess") public Object[][] dataToGetGroupSuccess() throws CharonException, InternalErrorException, BadRequestException { Group group = getNewGroup(); String id = group.getId(); return new Object[][]{ {id, null, null, group}, {id, null, "members", group}, {id, "displayName", null, group}, {id, "displayName", "members", group}, }; } @Test(dataProvider = "dataForGetGroupSuccess") public void testGetGroupSuccess(String id, String attributes, String excludeAttributes, Object objectGroup) throws CharonException { Group group = (Group) objectGroup; SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs( (SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT); abstractResourceManager.when(() -> userManager.getGroup(id, requiredAttributes)).thenReturn(group); SCIMResponse scimResponse = groupResourceManager.get(id, userManager, attributes, excludeAttributes); JSONObject obj = new JSONObject(scimResponse.getResponseMessage()); if (attributes != null) { Assert.assertTrue(obj.has(attributes)); } if (excludeAttributes != null) { Assert.assertFalse(obj.has(excludeAttributes)); } Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_OK); } @Test public void testGetGroupSuccessSpecial() throws BadRequestException, CharonException, InternalErrorException { Group group = getNewGroup(); String id = group.getId(); SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs( (SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), "", ""); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT); abstractResourceManager.when(() -> userManager.getGroup(id, requiredAttributes)).thenReturn(group); SCIMResponse scimResponse = groupResourceManager.get(id, userManager, "", ""); JSONObject obj = new JSONObject(scimResponse.getResponseMessage()); Assert.assertFalse(obj.has("displayNames")); Assert.assertFalse(obj.has("meta")); Assert.assertFalse(obj.has("members")); Assert.assertTrue(obj.has("id")); } @DataProvider(name = "dataForGetGroupExceptions") public Object[][] dataToGetGroupExceptions() { return new Object[][]{ {"123", "members", null}, {"123", "members", "meta"} }; } @Test(dataProvider = "dataForGetGroupExceptions") public void testGetGroupNotFoundException(String id, String attributes, String excludeAttributes) throws CharonException { SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs( (SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(NotFoundException.class))) .thenReturn(getEncodeSCIMExceptionObject(new NotFoundException())); abstractResourceManager.when(() -> userManager.getGroup(id, requiredAttributes)).thenReturn(null); SCIMResponse scimResponse = groupResourceManager.get(id, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_RESOURCE_NOT_FOUND); } @Test(dataProvider = "dataForGetGroupExceptions") public void testGetUserCharonException(String id, String attributes, String excludeAttributes) throws CharonException { SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs( (SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(CharonException.class))) .thenReturn(getEncodeSCIMExceptionObject(new CharonException())); abstractResourceManager.when(() -> userManager.getGroup(id, requiredAttributes)).thenThrow(CharonException.class); SCIMResponse scimResponse = groupResourceManager.get(id, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_INTERNAL_ERROR); } @DataProvider(name = "dataForTestCreateGroupSuccess") public Object[][] dataToTestCreateGroupSuccess() throws BadRequestException, CharonException, InternalErrorException { Group group = getNewGroup(); return new Object[][]{ {NEW_GROUP_SCIM_OBJECT_STRING, "id", null, group} }; } @Test(dataProvider = "dataForTestCreateGroupSuccess") public void testCreateGroupSuccess(String scimObjectString, String attributes, String excludeAttributes, Object objectGroup) { Group group = (Group) objectGroup; abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT); abstractResourceManager.when(() -> userManager.createGroup(any(Group.class), any(Map.class))).thenReturn(group); SCIMResponse scimResponse = groupResourceManager.create(scimObjectString, userManager, attributes, excludeAttributes); JSONObject obj = new JSONObject(scimResponse.getResponseMessage()); String returnedURI = scimResponse.getHeaderParamMap().get(SCIMConstants.LOCATION_HEADER); String expectedURI = "null/" + obj.getString("id"); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_CREATED); Assert.assertEquals(returnedURI, expectedURI); } @DataProvider(name = "dataForTestCreateGroupNewlyCreatedGroupResourceIsNull") public Object[][] dataToTestCreateGroupNewlyCreatedGroupResourceIsNull() { return new Object[][]{ {NEW_GROUP_SCIM_OBJECT_STRING, "id", null} }; } @Test(dataProvider = "dataForTestCreateGroupNewlyCreatedGroupResourceIsNull") public void testCreateGroupNewlyCreatedGroupResourceIsNull(String scimObjectString, String attributes, String excludeAttributes) { abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(InternalErrorException.class))) .thenReturn(getEncodeSCIMExceptionObject(new InternalErrorException())); abstractResourceManager.when(() -> userManager.createGroup(any(Group.class), any(Map.class))).thenReturn(null); SCIMResponse scimResponse = groupResourceManager.create(scimObjectString, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_INTERNAL_ERROR); } @DataProvider(name = "dataForTestCreateGroupBadRequestException") public Object[][] dataToTestCreatGroupBadRequestException() { return new Object[][]{ {NEW_GROUP_SCIM_OBJECT_STRING, "id", null} }; } @Test(dataProvider = "dataForTestCreateGroupBadRequestException") public void testCreateGroupBadRequestException(String scimObjectString, String attributes, String excludeAttributes) { abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(BadRequestException.class))) .thenReturn(getEncodeSCIMExceptionObject(new BadRequestException())); abstractResourceManager .when(() -> userManager.createGroup(any(Group.class), any(Map.class))).thenThrow(BadRequestException.class); SCIMResponse scimResponse = groupResourceManager.create(scimObjectString, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_BAD_REQUEST); } @DataProvider(name = "dataForTestCreateGroupConflictException") public Object[][] dataToTestCreatGroupConflictException() { return new Object[][]{ {NEW_GROUP_SCIM_OBJECT_STRING, "id", null} }; } @Test(dataProvider = "dataForTestCreateGroupConflictException") public void testCreateGroupConflictException(String scimObjectString, String attributes, String excludeAttributes) { abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(ConflictException.class))) .thenReturn(getEncodeSCIMExceptionObject(new ConflictException())); abstractResourceManager .when(() -> userManager.createGroup(any(Group.class), any(Map.class))).thenThrow(ConflictException.class); SCIMResponse scimResponse = groupResourceManager.create(scimObjectString, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_CONFLICT); } @DataProvider(name = "dataForTestCreateGroupCharonException") public Object[][] dataToTestCreateGroupCharonException() { return new Object[][]{ {NEW_GROUP_SCIM_OBJECT_STRING, "userName", null} }; } @Test(dataProvider = "dataForTestCreateGroupCharonException") public void testCreateGroupCharonException(String scimObjectString, String attributes, String excludeAttributes) { abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(CharonException.class))) .thenReturn(getEncodeSCIMExceptionObject(new CharonException())); abstractResourceManager .when(() -> userManager.createGroup(any(Group.class), any(Map.class))).thenThrow(CharonException.class); SCIMResponse scimResponse = groupResourceManager.create(scimObjectString, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_INTERNAL_ERROR); } @DataProvider(name = "dataForTestCreateGroupNotImplementedException") public Object[][] dataToTestCreateGroupNotImplementedException() { return new Object[][]{ {NEW_GROUP_SCIM_OBJECT_STRING, "userName", null} }; } @Test(dataProvider = "dataForTestCreateGroupNotImplementedException") public void testCreateGroupNotImplementedException(String scimObjectString, String attributes, String excludeAttributes) { abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(NotImplementedException.class))) .thenReturn(getEncodeSCIMExceptionObject(new NotImplementedException())); abstractResourceManager. when(() -> userManager.createGroup(any(Group.class), any(Map.class))).thenThrow(NotImplementedException.class); SCIMResponse scimResponse = groupResourceManager.create(scimObjectString, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_NOT_IMPLEMENTED); } @Test public void testDeleteGroupSuccess() throws NotFoundException, BadRequestException, CharonException, InternalErrorException { Group group = getNewGroup(); String id = group.getId(); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT + "/" + GROUP_ID); SCIMResponse scimResponse = groupResourceManager.delete(id, userManager); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_NO_CONTENT); } @DataProvider(name = "dataForTestDeleteGroupFails") public Object[][] dataToTestDeleteGroupFails() throws BadRequestException, CharonException, InternalErrorException { Group group = getNewGroup(); String id = group.getId(); return new Object[][]{ {id, ResponseCodeConstants.CODE_INTERNAL_ERROR}, {id, ResponseCodeConstants.CODE_RESOURCE_NOT_FOUND}, }; } @Test(dataProvider = "dataForTestDeleteGroupFails") public void testDeleteGroupFails(String id, int expectedScimResponseStatus) throws NotFoundException, NotImplementedException, BadRequestException, CharonException { abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT + "/" + GROUP_ID); if (expectedScimResponseStatus == ResponseCodeConstants.CODE_INTERNAL_ERROR) { abstractResourceManager .when(() -> AbstractResourceManager.encodeSCIMException(any(InternalErrorException.class))) .thenReturn(getEncodeSCIMExceptionObject(new InternalErrorException())); SCIMResponse scimResponse = groupResourceManager.delete(id, null); Assert.assertEquals(scimResponse.getResponseStatus(), expectedScimResponseStatus); } else { doThrow(new NotFoundException()).when(userManager).deleteGroup(id); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(NotFoundException.class))) .thenReturn(getEncodeSCIMExceptionObject(new NotFoundException())); SCIMResponse scimResponse = groupResourceManager.delete(id, userManager); Assert.assertEquals(scimResponse.getResponseStatus(), expectedScimResponseStatus); } } @Test public void testDeleteGroupCharonExceptionOnly() throws NotFoundException, NotImplementedException, BadRequestException, CharonException, InternalErrorException { Group group = getNewGroup(); String id = group.getId(); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT + "/" + GROUP_ID); doThrow(new CharonException()).when(userManager).deleteGroup(id); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(CharonException.class))) .thenReturn(getEncodeSCIMExceptionObject(new CharonException())); SCIMResponse scimResponse = groupResourceManager.delete(id, userManager); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_INTERNAL_ERROR); } @DataProvider(name = "dataForTestUpdateGroupWithPUTSuccess") public Object[][] dataToTestUpdateGroupWithPUTSuccess() throws BadRequestException, CharonException, InternalErrorException { SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); JSONDecoder decoder = new JSONDecoder(); Group groupOld = decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING, schema, new Group()); String id = groupOld.getId(); Group groupNew = decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING_UPDATED, schema, new Group()); return new Object[][]{ {id, NEW_GROUP_SCIM_OBJECT_STRING_UPDATED, "id", null, groupNew, groupOld} }; } @Test(dataProvider = "dataForTestUpdateGroupWithPUTSuccess") public void testUpdateGroupWithPUTSuccess(String id, String scimObjectString, String attributes, String excludeAttributes, Object scimNewGroupObject, Object scimOldGroupObject) throws BadRequestException, CharonException { Group groupNew = (Group) scimNewGroupObject; Group groupOld = (Group) scimOldGroupObject; SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT + "/" + GROUP_ID); abstractResourceManager.when(()-> userManager.getGroup(id, ResourceManagerUtil.getAllAttributeURIs(schema))).thenReturn(groupOld); Group validatedGroup = (Group) ServerSideValidator.validateUpdatedSCIMObject(groupOld, groupNew, schema); abstractResourceManager .when(() -> userManager.updateGroup(any(Group.class), any(Group.class), any(Map.class))) .thenReturn(validatedGroup); SCIMResponse scimResponse = groupResourceManager.updateWithPUT(id, scimObjectString, userManager, attributes, excludeAttributes); JSONObject obj = new JSONObject(scimResponse.getResponseMessage()); String returnedURI = scimResponse.getHeaderParamMap().get("Location"); String expectedURI = "null/" + obj.getString("id"); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_OK); Assert.assertEquals(returnedURI, expectedURI); } @DataProvider(name = "dataForTestUpdateGroupWithPUTProvidedUserManagerHandlerIsNull") public Object[][] dataToTestUpdateGroupWithPUTProvidedUserManagerHandlerIsNull() throws BadRequestException, CharonException, InternalErrorException { SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); JSONDecoder decoder = new JSONDecoder(); Group groupOld = decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING, schema, new Group()); String name = groupOld.getId(); Group groupNew = decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING_UPDATED, schema, new Group()); return new Object[][]{ {name, NEW_GROUP_SCIM_OBJECT_STRING_UPDATED, "id", null, groupNew, groupOld} }; } @Test(dataProvider = "dataForTestUpdateGroupWithPUTProvidedUserManagerHandlerIsNull") public void testUpdateGroupWithPUTProvidedUserManagerHandlerIsNull(String id, String scimObjectString, String attributes, String excludeAttributes, Object scimNewGroupObject, Object scimOldGroupObject) throws BadRequestException, CharonException { Group groupNew = (Group) scimNewGroupObject; Group groupOld = (Group) scimOldGroupObject; SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT + "/" + GROUP_ID); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(InternalErrorException.class))) .thenReturn(getEncodeSCIMExceptionObject(new InternalErrorException())); abstractResourceManager.when(() -> userManager.getGroup(id, ResourceManagerUtil.getAllAttributeURIs(schema))).thenReturn(groupOld); Group validatedGroup = (Group) ServerSideValidator.validateUpdatedSCIMObject(groupOld, groupNew, schema); abstractResourceManager .when(() -> userManager.updateGroup(any(Group.class), any(Group.class), any(Map.class))).thenReturn(validatedGroup); SCIMResponse scimResponse = groupResourceManager.updateWithPUT(id, scimObjectString, null, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_INTERNAL_ERROR); } @DataProvider(name = "dataForTestUpdateGroupWithPUTUpdatedGroupResourceIsNull") public Object[][] dataToTestUpdateWithGroupPUTUpdatedGroupResourceIsNull() throws BadRequestException, CharonException, InternalErrorException { SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); JSONDecoder decoder = new JSONDecoder(); Group groupOld = decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING, schema, new Group()); String name = groupOld.getId(); return new Object[][]{ {name, NEW_GROUP_SCIM_OBJECT_STRING_UPDATED, "id", null, groupOld} }; } @Test(dataProvider = "dataForTestUpdateGroupWithPUTUpdatedGroupResourceIsNull") public void testUpdateGroupWithPUTUpdatedGroupResourceIsNull(String id, String scimObjectString, String attributes, String excludeAttributes, Object scimOldGroupObject) { Group groupOld = (Group) scimOldGroupObject; SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT + "/" + GROUP_ID); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(InternalErrorException.class))) .thenReturn(getEncodeSCIMExceptionObject(new InternalErrorException())); abstractResourceManager.when(() -> userManager.getGroup(id, ResourceManagerUtil.getAllAttributeURIs(schema))).thenReturn(groupOld); abstractResourceManager.when(() -> userManager.updateGroup(any(Group.class), any(Group.class), any(Map.class))).thenReturn(null); SCIMResponse scimResponse = groupResourceManager.updateWithPUT(id, scimObjectString, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_INTERNAL_ERROR); } @DataProvider(name = "dataForTestUpdateGroupWithPUTNotFoundException") public Object[][] dataToTestUpdateGroupWithPUTNotFoundException() throws BadRequestException, CharonException, InternalErrorException { SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); JSONDecoder decoder = new JSONDecoder(); Group groupOld = decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING, schema, new Group()); String id = groupOld.getId(); Group groupNew = decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING_UPDATED, schema, new Group()); return new Object[][]{ {id, NEW_GROUP_SCIM_OBJECT_STRING_UPDATED, "id", null, groupNew, groupOld} }; } @Test(dataProvider = "dataForTestUpdateGroupWithPUTNotFoundException") public void testUpdateGroupWithPUTNoUserExistsWithTheGivenUserName(String id, String scimObjectString, String attributes, String excludeAttributes, Object scimNewGroupObject, Object scimOldGroupObject) throws BadRequestException, CharonException { Group groupNew = (Group) scimNewGroupObject; Group groupOld = (Group) scimOldGroupObject; SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT + "/" + GROUP_ID); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(NotFoundException.class))) .thenReturn(getEncodeSCIMExceptionObject(new NotFoundException())); abstractResourceManager.when(() -> userManager.getGroup(id, ResourceManagerUtil.getAllAttributeURIs(schema))).thenReturn(null); Group validatedGroup = (Group) ServerSideValidator.validateUpdatedSCIMObject(groupOld, groupNew, schema); abstractResourceManager .when(() -> userManager.updateGroup(any(Group.class), any(Group.class), any(Map.class))).thenReturn(validatedGroup); SCIMResponse scimResponse = groupResourceManager.updateWithPUT(id, scimObjectString, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_RESOURCE_NOT_FOUND); } @DataProvider(name = "dataForTestUpdateGroupWithPUTCharonException") public Object[][] dataToTestUpdateGroupWithPUTCharonException() throws BadRequestException, CharonException, InternalErrorException { SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); JSONDecoder decoder = new JSONDecoder(); Group groupOld = decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING, schema, new Group()); String id = groupOld.getId(); return new Object[][]{ {id, NEW_GROUP_SCIM_OBJECT_STRING_UPDATED, "id", null, groupOld} }; } @Test(dataProvider = "dataForTestUpdateGroupWithPUTCharonException") public void testUpdateWithPUTharonException(String id, String scimObjectString, String attributes, String excludeAttributes, Object scimOldGroupObject) { Group groupOld = (Group) scimOldGroupObject; SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT + "/" + GROUP_ID); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(CharonException.class))) .thenReturn(getEncodeSCIMExceptionObject(new CharonException())); abstractResourceManager.when(() -> userManager.getGroup(id, ResourceManagerUtil.getAllAttributeURIs(schema))).thenReturn(groupOld); abstractResourceManager .when(() -> userManager.updateGroup(any(Group.class), any(Group.class), any(Map.class))).thenThrow(CharonException.class); SCIMResponse scimResponse = groupResourceManager.updateWithPUT(id, scimObjectString, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_INTERNAL_ERROR); } @DataProvider(name = "dataForTestUpdateGroupWithPUTBadRequestException") public Object[][] dataToTestUpdateGroupWithPUTBadRequestException() throws BadRequestException, CharonException, InternalErrorException { SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); JSONDecoder decoder = new JSONDecoder(); Group groupOld = decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING, schema, new Group()); String id = groupOld.getId(); return new Object[][]{ {id, NEW_GROUP_SCIM_OBJECT_STRING_UPDATED, "id", null, groupOld} }; } @Test(dataProvider = "dataForTestUpdateGroupWithPUTBadRequestException") public void testUpdateGroupWithPUTBadRequestException(String id, String scimObjectString, String attributes, String excludeAttributes, Object scimOldGroupObject) { Group groupOld = (Group) scimOldGroupObject; SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT + "/" + GROUP_ID); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(BadRequestException.class))) .thenReturn(getEncodeSCIMExceptionObject(new BadRequestException())); abstractResourceManager.when(() -> userManager.getGroup(id, ResourceManagerUtil.getAllAttributeURIs(schema))).thenReturn(groupOld); abstractResourceManager .when(() -> userManager.updateGroup(any(Group.class), any(Group.class), any(Map.class))) .thenThrow(BadRequestException.class); SCIMResponse scimResponse = groupResourceManager.updateWithPUT(id, scimObjectString, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_BAD_REQUEST); } @DataProvider(name = "dataForTestUpdateGroupWithPUTNotImplementedException") public Object[][] dataToTestUpdateGroupWithPUTNotImplementedException() throws BadRequestException, CharonException, InternalErrorException { SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); JSONDecoder decoder = new JSONDecoder(); Group groupOld = decoder.decodeResource(NEW_GROUP_SCIM_OBJECT_STRING, schema, new Group()); String id = groupOld.getId(); return new Object[][]{ {id, NEW_GROUP_SCIM_OBJECT_STRING_UPDATED, "id", null, groupOld} }; } @Test(dataProvider = "dataForTestUpdateGroupWithPUTNotImplementedException") public void testUpdateGroupWithPUTNotImplementedException(String id, String scimObjectString, String attributes, String excludeAttributes, Object scimOldGroupObject) { Group groupOld = (Group) scimOldGroupObject; SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema(); abstractResourceManager.when(() -> AbstractResourceManager.getResourceEndpointURL(SCIMConstants.USER_ENDPOINT)) .thenReturn(SCIM2_GROUP_ENDPOINT + "/" + GROUP_ID); abstractResourceManager.when(() -> AbstractResourceManager.encodeSCIMException(any(NotImplementedException.class))) .thenReturn(getEncodeSCIMExceptionObject(new NotImplementedException())); abstractResourceManager.when(() -> userManager.getGroup(id, ResourceManagerUtil.getAllAttributeURIs(schema))).thenReturn(groupOld); abstractResourceManager.when(() -> userManager.updateGroup(any(Group.class), any(Group.class), any(Map.class))) .thenThrow(NotImplementedException.class); SCIMResponse scimResponse = groupResourceManager.updateWithPUT(id, scimObjectString, userManager, attributes, excludeAttributes); Assert.assertEquals(scimResponse.getResponseStatus(), ResponseCodeConstants.CODE_NOT_IMPLEMENTED); } }
51.152833
120
0.70537
3324293a5e18874705c276972df85b27bff22a82
225
package com.technology.oracle.scheduler.detailedlog.shared.service; import com.technology.jep.jepria.shared.service.data.JepDataServiceAsync; public interface DetailedLogServiceAsync extends JepDataServiceAsync { }
32.142857
74
0.831111
66c1eb1354132986db3d915c249fb72ea11c0cf4
1,586
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/storage/v1/storage.proto package com.google.cloud.bigquery.storage.v1; public interface SplitReadStreamRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.bigquery.storage.v1.SplitReadStreamRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * Required. Name of the stream to split. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The name. */ java.lang.String getName(); /** * <pre> * Required. Name of the stream to split. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * <pre> * A value in the range (0.0, 1.0) that specifies the fractional point at * which the original stream should be split. The actual split point is * evaluated on pre-filtered rows, so if a filter is provided, then there is * no guarantee that the division of the rows between the new child streams * will be proportional to this fractional value. Additionally, because the * server-side unit for assigning data is collections of rows, this fraction * will always map to a data storage boundary on the server side. * </pre> * * <code>double fraction = 2;</code> * @return The fraction. */ double getFraction(); }
34.478261
118
0.684741
1be50e2c13a62e5a3d22d504dbb11dcaca490379
1,104
package cn.augusto.ch1.sync; import java.util.Calendar; public class SyncClass { public static synchronized void print(){ System.out.println("print --> " + Calendar.getInstance().getTimeInMillis()/ 1000); try { Thread.sleep(1000*3); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("print --> " + Calendar.getInstance().getTimeInMillis()/ 1000); } public static void main(String[] args){ Thread th = new Thread(){ @Override public void run(){ System.out.println(getName() + " --> " + Calendar.getInstance().getTimeInMillis() / 1000); synchronized (SyncClass.class){ try { sleep(1000 * 3); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(getName() + " --> " + Calendar.getInstance().getTimeInMillis() / 1000); } }; Thread th2 = new Thread() { @Override public void run() { super.run(); SyncClass.print(); } }; th.start(); th2.start(); } }
25.090909
98
0.565217
f035794d50b96b6d3a357ecd558f448c9dd98173
569
package de.l3s.simpleml.tab2kg.model.sparql; public enum Language { DE("de"), EN("en"); private String languageTag; public static Language getLanguageByTag(String languageTag) { for (Language language : Language.values()) { if (language.getLanguageTag().equals(languageTag)) return language; } return null; // throw new IllegalArgumentException("Language tag " + languageTag + " // does not exist."); } private Language(String languageTag) { this.languageTag = languageTag; } public String getLanguageTag() { return languageTag; } }
20.321429
73
0.711775
bef67d1393ffa2542d1c8b5ab4a711f13a32bb86
5,876
package com.shortlyst.test.vendingmachine; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by zer0, the Maverick Hunter * on 22/07/19. * Class: EndToEndTestSuite.java */ public class OneCyclePurchaseTest { private App app; @Before public void setUp() throws Exception { app = new App(); } @After public void tearDown() throws Exception { app = null; } @Test public void oneCyclePurchaseTest() { String command1_1_10 = "----------------------------------\n" + "[Input Amount]\n" + "\t10 JPY\n" + "[Change]\n" + "\t100 JPY Change\n" + "\t10 JPY Change\n" + "[Return Gate]\n" + "\tEmpty\n" + "[Items for sale]\n" + "\t1. Canned coffee 120 JPY \n" + "\u001B[31m\t2. Water PET bottle 100 JPY Out of Stock\u001B[0m\n" + "\t3. Sport drinks 150 JPY \n" + "[Outlet]\n" + "\tEmpty\n" + "----------------------------------"; assertEquals(command1_1_10, app.processCommand("1 10")); String command2_1_10 = "----------------------------------\n" + "[Input Amount]\n" + "\t20 JPY\n" + "[Change]\n" + "\t100 JPY Change\n" + "\t10 JPY Change\n" + "[Return Gate]\n" + "\tEmpty\n" + "[Items for sale]\n" + "\t1. Canned coffee 120 JPY \n" + "\u001B[31m\t2. Water PET bottle 100 JPY Out of Stock\u001B[0m\n" + "\t3. Sport drinks 150 JPY \n" + "[Outlet]\n" + "\tEmpty\n" + "----------------------------------"; assertEquals(command2_1_10, app.processCommand("1 10")); String command3_1_100 = "----------------------------------\n" + "[Input Amount]\n" + "\t120 JPY\n" + "[Change]\n" + "\t100 JPY Change\n" + "\t10 JPY Change\n" + "[Return Gate]\n" + "\tEmpty\n" + "[Items for sale]\n" + "\u001B[32m\t1. Canned coffee 120 JPY Available for Purchase\u001B[0m\n" + "\u001B[31m\t2. Water PET bottle 100 JPY Out of Stock\u001B[0m\n" + "\t3. Sport drinks 150 JPY \n" + "[Outlet]\n" + "\tEmpty\n" + "----------------------------------"; assertEquals(command3_1_100, app.processCommand("1 100")); String command4_2_1 = "----------------------------------\n" + "[Input Amount]\n" + "\t0 JPY\n" + "[Change]\n" + "\t100 JPY Change\n" + "\t10 JPY Change\n" + "[Return Gate]\n" + "\tEmpty\n" + "[Items for sale]\n" + "\t1. Canned coffee 120 JPY \n" + "\u001B[31m\t2. Water PET bottle 100 JPY Out of Stock\u001B[0m\n" + "\t3. Sport drinks 150 JPY \n" + "[Outlet]\n" + "\tCanned coffee\n" + "----------------------------------"; assertEquals(command4_2_1, app.processCommand("2 1")); String command5_3 = "\u001B[32mYour change is being prepared (if any), you may now empty the Outlet\u001B[0m\n" + "----------------------------------\n" + "[Input Amount]\n" + "\t0 JPY\n" + "[Change]\n" + "\t100 JPY Change\n" + "\t10 JPY Change\n" + "[Return Gate]\n" + "\tEmpty\n" + "[Items for sale]\n" + "\t1. Canned coffee 120 JPY \n" + "\u001B[31m\t2. Water PET bottle 100 JPY Out of Stock\u001B[0m\n" + "\t3. Sport drinks 150 JPY \n" + "[Outlet]\n" + "\tCanned coffee\n" + "----------------------------------"; assertEquals(command5_3, app.processCommand("3")); String command6_4 = "\u001B[32mPlease collect your change in Return Gate\u001B[0m\n" + "----------------------------------\n" + "[Input Amount]\n" + "\t0 JPY\n" + "[Change]\n" + "\t100 JPY Change\n" + "\t10 JPY Change\n" + "[Return Gate]\n" + "\tEmpty\n" + "[Items for sale]\n" + "\t1. Canned coffee 120 JPY \n" + "\u001B[31m\t2. Water PET bottle 100 JPY Out of Stock\u001B[0m\n" + "\t3. Sport drinks 150 JPY \n" + "[Outlet]\n" + "\tCanned coffee\n" + "----------------------------------"; assertEquals(command6_4, app.processCommand("4")); String command7_5 = "\u001B[32mThank you for using our service\u001B[0m\n" + "----------------------------------\n" + "[Input Amount]\n" + "\t0 JPY\n" + "[Change]\n" + "\t100 JPY Change\n" + "\t10 JPY Change\n" + "[Return Gate]\n" + "\tEmpty\n" + "[Items for sale]\n" + "\t1. Canned coffee 120 JPY \n" + "\u001B[31m\t2. Water PET bottle 100 JPY Out of Stock\u001B[0m\n" + "\t3. Sport drinks 150 JPY \n" + "[Outlet]\n" + "\tEmpty\n" + "----------------------------------"; assertEquals(command7_5, app.processCommand("5")); } }
36.496894
121
0.394656
b04c0c7cdc12cbb5343f5d6baf545ff5d7d063d7
1,422
import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import java.util.OptionalDouble; import java.util.function.Predicate; import java.util.stream.Stream; import static oracle.jrockit.jfr.events.Bits.doubleValue; class PickShareFunctional { public static final List<String> symbols = Arrays.asList("IBM", "AAPL", "AMZN", "CSCO", "SNE", "GOOG", "MSFT", "ORCL", "FB", "VRSN"); public static void findHighPriced(Stream<String> shares) { System.out.println("High priced under $500 is "+shares.map( s -> ShareUtil.getPrice(s) ).filter( i -> ShareUtil.isPriceLessThan(500).test(i) ).reduce( (shareInfo1, shareInfo2) -> ShareUtil.pickHigh(shareInfo1, shareInfo2) )); } public static void PickShareImperative(){ ShareInfo highPriced = new ShareInfo("", BigDecimal.ZERO); final Predicate isPriceLessThan500 = ShareUtil.isPriceLessThan(500); for( String symbol :Shares.symbols) { ShareInfo shareInfo = ShareUtil.getPrice(symbol); if (isPriceLessThan500.test(shareInfo)) highPriced = ShareUtil.pickHigh(highPriced, shareInfo); } System.out.println("High priced under $500 is "+highPriced); } public static void main(String args[]){ PickShareImperative(); findHighPriced(symbols.stream()); } }
33.857143
107
0.650492
68706097c76bfd134f7911a7dca21c74bcef4dc8
3,559
package com.tracelink.prodsec.plugin.sonatype.controller; import com.tracelink.prodsec.plugin.sonatype.SonatypePlugin; import com.tracelink.prodsec.plugin.sonatype.model.SonatypeApp; import com.tracelink.prodsec.plugin.sonatype.model.SonatypeMetrics; import com.tracelink.prodsec.plugin.sonatype.service.SonatypeAppService; import com.tracelink.prodsec.synapse.products.model.ProductLineModel; import com.tracelink.prodsec.synapse.products.model.ProjectFilterModel; import com.tracelink.prodsec.synapse.products.model.ProjectModel; import com.tracelink.prodsec.synapse.products.service.ProductsService; import com.tracelink.prodsec.synapse.test.TestSynapseBootApplication; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.BDDMockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.time.LocalDate; import java.util.Collections; @RunWith(SpringRunner.class) @SpringBootTest(classes = TestSynapseBootApplication.class) @AutoConfigureMockMvc public class SonatypeDashboardControllerTest { @Autowired private MockMvc mockMvc; @MockBean private ProductsService productsService; @MockBean private SonatypeAppService appService; @Test @WithMockUser public void testGetDashboard() throws Exception { ProductLineModel productLine = new ProductLineModel(); productLine.setName("Product Line"); ProjectFilterModel projectFilter = new ProjectFilterModel(); projectFilter.setName("Project Filter"); ProjectModel project = new ProjectModel(); project.setName("Project"); SonatypeMetrics metrics = new SonatypeMetrics(); metrics.setRecordedDate(LocalDate.now()); metrics.setHighVios(4); metrics.setMedVios(3); SonatypeApp app = new SonatypeApp(); app.setName("App"); app.setSynapseProject(project); app.setMetrics(Collections.singletonList(metrics)); BDDMockito.when(appService.getMappedApps()).thenReturn(Collections.singletonList(app)); BDDMockito.when(productsService.getAllProductLines()).thenReturn(Collections.singletonList(productLine)); BDDMockito.when(productsService.getAllProjectFilters()).thenReturn(Collections.singletonList(projectFilter)); BDDMockito.when(productsService.getAllProjects()).thenReturn(Collections.singletonList(project)); mockMvc.perform(MockMvcRequestBuilders.get(SonatypePlugin.DASHBOARD_PAGE)) .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("Product Line"))) .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("Project Filter"))) .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("Project"))) .andExpect(MockMvcResultMatchers.model().attribute("coveredApps", 1)) .andExpect(MockMvcResultMatchers.model().attribute("vulnerableApps", 1L)) .andExpect(MockMvcResultMatchers.model().attribute("totalViolations", 7L)) .andExpect(MockMvcResultMatchers.model().attribute("highViolations", 4L)); } }
45.628205
111
0.824389
2477a60b094ed06705776784ce10aa944418cf27
59
package fr.eservices.drive.model; public enum Status { }
9.833333
33
0.745763
6c93b83daa16825695a370cd5256d681b56464fc
292
package com.thomrick.projects.xebia.tondeuses.interfaces.constantes; /** * OrientationConstants.java * * @author ThomRick * @date 2016-08-04 * */ public interface OrientationConstants { String NORTH = "N"; String SOUTH = "S"; String EAST = "E"; String WEST = "W"; }
18.25
69
0.65411
0d08574a7866ef24f28a2f7a2998d6f63bc30901
528
package su.svn.href.models; import lombok.*; import org.springframework.data.annotation.Id; import org.springframework.data.relational.core.mapping.Column; import org.springframework.data.relational.core.mapping.Table; import java.math.BigInteger; @Data @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode @ToString @Table("regions") public class Region { static final long serialVersionUID = -10L; @Id @Column("region_id") private Long id; @Column("region_name") private String regionName; }
19.555556
63
0.765152
1ab78eb7923a35e87282104c16baaee65fa64bdb
27,033
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraFactory; import org.openftc.easyopencv.OpenCvCameraRotation; import org.openftc.easyopencv.OpenCvPipeline; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; @Autonomous(name="Auto", group="Pushbot") public class auto extends LinearOpMode { public robotInit robot = new robotInit(); ElapsedTime runtime = new ElapsedTime(); OpenCvCamera webcam; SkystoneDeterminationPipeline pipeline; @Override public void runOpMode() { robot.init(hardwareMap); int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); webcam = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "webcam"), cameraMonitorViewId); pipeline = new SkystoneDeterminationPipeline(); webcam.setPipeline(pipeline); resetEncoder(); startEncoderMode(); webcam.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() { @Override public void onOpened() { webcam.startStreaming(320, 240, OpenCvCameraRotation.UPRIGHT); } }); // Wait for the game to start (driver presses PLAY) telemetry.addLine("Waiting for start"); telemetry.update(); waitForStart(); /* Telemetry for testing ring detection while (opModeIsActive()) { telemetry.addData("Analysis", pipeline.getAnalysis()); telemetry.addData("Position", pipeline.position); telemetry.update(); // Don't burn CPU cycles busy-looping in this sample sleep(50); } */ //pick up wobble goal pickUpWobble(); //Place wobble goal in the correct target zone if (pipeline.position == SkystoneDeterminationPipeline.RingPosition.FOUR) { telemetry.addData("Detected", "four rings!"); telemetry.update(); //clear the rings moveRight(8); //move to launch line moveForward(58); //center robot to front of goal moveLeft(10); //launch 3 preloaded rings with more time between shots robot.pitcherMotor.setVelocity(2085); //0.6257 mid, 0.65 speed when 11.8 V, 0.67 when 11.7 V, 0.69 when 10.22 V runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 2.5)) { } for (int i = 0; i < 3; i++){ //launch telemetry.addData("Launching High Ring #", i+1); telemetry.update(); //servo pushes ring forward robot.ringFlicker.setPosition(0.5); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 1)) { } //bring flicker back robot.ringFlicker.setPosition(0.25); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 1)) { } } robot.pitcherMotor.setPower(0); //power off flywheel //turn to face C box turnleft(8); //move to box moveForward(65); //Place the wobble goal dropWobbleGoal(); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 1.5)) { } //drive to parking line moveBackward(50); } else if (pipeline.position == SkystoneDeterminationPipeline.RingPosition.ONE) { telemetry.addData("Detected", "one ring"); //1 = B, middle telemetry.update(); //move to launch line moveForward(56); //launch 3 preloaded rings launchRingHigh(3); moveLeft(16); raise(20); moveForward(30); //Place the wobble goal dropWobbleGoal(); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 1.5)) { } raise(120); moveBackward(15); //angle to 2nd wobble turnleft(44); lower(120); moveForward(43); //pick up wobble without raising first robot.wobbleSnatcher.setPosition(0.3); runtime.reset(); while (opModeIsActive() && runtime.seconds() < 0.5) { } raise(150); runtime.reset(); while (opModeIsActive() && runtime.seconds() < 0.1) { } moveBackward(50); turnright(40); dropWobbleGoal(); } else if (pipeline.position == SkystoneDeterminationPipeline.RingPosition.NONE) { telemetry.addData("Detected", "no rings"); telemetry.update(); //move to launch line moveForward(56); //launch 3 preloaded rings launchRingHigh(3); turnleft(20); //90 deg, 15 before angle to ramp raise(90); moveForward(30); //Place the wobble goal dropWobbleGoal(); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 1.5)) { } raise(90); turnleft(29); // 29 before lower(120); moveForward(36); sleep(1000); //pick up wobble without raising first robot.wobbleSnatcher.setPosition(0.3); runtime.reset(); while (opModeIsActive() && runtime.seconds() < 0.5) { } raise(150); runtime.reset(); while (opModeIsActive() && runtime.seconds() < 0.1) { } telemetry.addData("The Wobble Goal", "Has Risen"); telemetry.update(); turnright(4.5); //4 before moveBackward(45); turnright(19); //90 deg //Place the wobble goal dropWobbleGoal(); } // Stop, take a well deserved breather sleep(1000); // pause for servos to move telemetry.addData("Path", "Complete"); telemetry.update(); } /* FUNCTIONS */ public void launchRingHigh(int times){ robot.pitcherMotor.setVelocity(2085); //0.6257 mid, 0.65 speed when 11.8 V, 0.67 when 11.7 V, 0.69 when 10.22 V runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 2.5)) { } for (int i = 0; i < times; i++){ //launch telemetry.addData("Launching High Ring #", i+1); telemetry.update(); //servo pushes ring forward robot.ringFlicker.setPosition(0.5); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 0.5)) { } //bring flicker back robot.ringFlicker.setPosition(0.25); runtime.reset(); while (opModeIsActive() && (runtime.seconds() < 0.5)) { } } robot.pitcherMotor.setPower(0); //power off flywheel } /* ARM MOVEMENT */ public void raise(double count) { int newElbowMotorTarget; // Determine new target position, and pass to motor controller newElbowMotorTarget = robot.elbowMotor.getCurrentPosition() + (int)(count); robot.elbowMotor.setTargetPosition(newElbowMotorTarget); // Turn On RUN_TO_POSITION robot.elbowMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.elbowMotor.setPower(0.3); runtime.reset(); while (opModeIsActive() && robot.elbowMotor.isBusy()) { // Display it for the driver. telemetry.addData("Path1", "Running to %7d", newElbowMotorTarget); telemetry.update(); } } public void lower(double count) { int newElbowMotorTarget; // Determine new target position, and pass to motor controller newElbowMotorTarget = robot.elbowMotor.getCurrentPosition() - (int) (count); robot.elbowMotor.setTargetPosition(newElbowMotorTarget); // Turn On RUN_TO_POSITION robot.elbowMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.elbowMotor.setPower(0.3); runtime.reset(); while (opModeIsActive() && robot.elbowMotor.isBusy()) { // Display it for the driver. telemetry.addData("Path1", "Running to %7d", newElbowMotorTarget); telemetry.update(); } } public void pickUpWobble() { //move into position raise(20); robot.wobbleSnatcher.setPosition(0.3); runtime.reset(); while (opModeIsActive() && runtime.seconds() < 1) { } raise(25); runtime.reset(); while (opModeIsActive() && runtime.seconds() < 1) { } telemetry.addData("The Wobble Goal", "Has Risen"); telemetry.update(); } public void dropWobbleGoal() { lower(25); robot.wobbleSnatcher.setPosition(1); // open claw } /* ENCODER FUNCTIONS */ public void resetEncoder() { robot.motorFL.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); robot.motorFR.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); robot.motorBL.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); robot.motorBR.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); robot.elbowMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); } public void startEncoderMode() { //Set Encoder Mode robot.motorFL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorFR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.elbowMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } /* MOVEMENT FUNCTIONS */ public void moveForward(int inches) { int newmotorFLTarget; int newmotorFRTarget; int newmotorBLTarget; int newmotorBRTarget; // Determine new target position, and pass to motor controller newmotorFLTarget = robot.motorFL.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); newmotorFRTarget = robot.motorFR.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); newmotorBLTarget = robot.motorBL.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); newmotorBRTarget = robot.motorBR.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); robot.motorFL.setTargetPosition(newmotorFLTarget); robot.motorFR.setTargetPosition(newmotorFRTarget); robot.motorBL.setTargetPosition(newmotorBLTarget); robot.motorBR.setTargetPosition(newmotorBRTarget); // Turn On RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorFR.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBR.setPower(Math.abs(robot.DRIVE_SPEED)); runtime.reset(); while (opModeIsActive() && (robot.motorFL.isBusy() || robot.motorFR.isBusy() || robot.motorBL.isBusy() || robot.motorBR.isBusy())) { // Display it for the driver. telemetry.addData("Path1", "Running to %7d :%7d", newmotorFLTarget, newmotorFRTarget ); telemetry.update(); } // Stop all motion; stopRobot(); // Turn off RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorFR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void moveBackward(double inches) { int newmotorFLTarget; int newmotorFRTarget; int newmotorBLTarget; int newmotorBRTarget; // Determine new target position, and pass to motor controller newmotorFLTarget = robot.motorFL.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); newmotorFRTarget = robot.motorFR.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); newmotorBLTarget = robot.motorBL.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); newmotorBRTarget = robot.motorBR.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); robot.motorFL.setTargetPosition(newmotorFLTarget); robot.motorFR.setTargetPosition(newmotorFRTarget); robot.motorBL.setTargetPosition(newmotorBLTarget); robot.motorBR.setTargetPosition(newmotorBRTarget); // Turn On RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorFR.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBR.setPower(Math.abs(robot.DRIVE_SPEED)); runtime.reset(); while (opModeIsActive() && (robot.motorFL.isBusy() || robot.motorFR.isBusy() || robot.motorBL.isBusy() || robot.motorBR.isBusy())) { // Display it for the driver. telemetry.addData("Path1", "Running to %7d :%7d", newmotorFLTarget, newmotorFRTarget ); telemetry.update(); } // Stop all motion; stopRobot(); // Turn off RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorFR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void moveRight(double inches) { int newmotorFLTarget; int newmotorFRTarget; int newmotorBLTarget; int newmotorBRTarget; // Determine new target position, and pass to motor controller newmotorFLTarget = robot.motorFL.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); newmotorFRTarget = robot.motorFR.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); newmotorBLTarget = robot.motorBL.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); newmotorBRTarget = robot.motorBR.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); robot.motorFL.setTargetPosition(newmotorFLTarget); robot.motorFR.setTargetPosition(newmotorFRTarget); robot.motorBL.setTargetPosition(newmotorBLTarget); robot.motorBR.setTargetPosition(newmotorBRTarget); // Turn On RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorFR.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBR.setPower(Math.abs(robot.DRIVE_SPEED)); runtime.reset(); while (opModeIsActive() && (robot.motorFL.isBusy() || robot.motorFR.isBusy() || robot.motorBL.isBusy() || robot.motorBR.isBusy())) { // Display it for the driver. telemetry.addData("Path1", "Running to %7d :%7d", newmotorFLTarget, newmotorFRTarget ); telemetry.update(); } // Stop all motion; stopRobot(); // Turn off RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorFR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void moveLeft(double inches) { int newmotorFLTarget; int newmotorFRTarget; int newmotorBLTarget; int newmotorBRTarget; // Determine new target position, and pass to motor controller newmotorFLTarget = robot.motorFL.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); newmotorFRTarget = robot.motorFR.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); newmotorBLTarget = robot.motorBL.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); newmotorBRTarget = robot.motorBR.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); robot.motorFL.setTargetPosition(newmotorFLTarget); robot.motorFR.setTargetPosition(newmotorFRTarget); robot.motorBL.setTargetPosition(newmotorBLTarget); robot.motorBR.setTargetPosition(newmotorBRTarget); // Turn On RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorFR.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBR.setPower(Math.abs(robot.DRIVE_SPEED)); runtime.reset(); while (opModeIsActive() && (robot.motorFL.isBusy() || robot.motorFR.isBusy() || robot.motorBL.isBusy() || robot.motorBR.isBusy())) { // Display it for the driver. telemetry.addData("Path1", "Running to %7d :%7d", newmotorFLTarget, newmotorFRTarget ); telemetry.update(); } // Stop all motion; stopRobot(); // Turn off RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorFR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void turnleft(double inches) { int newmotorFLTarget; int newmotorFRTarget; int newmotorBLTarget; int newmotorBRTarget; // Determine new target position, and pass to motor controller newmotorFLTarget = robot.motorFL.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); newmotorFRTarget = robot.motorFR.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); newmotorBLTarget = robot.motorBL.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); newmotorBRTarget = robot.motorBR.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); robot.motorFL.setTargetPosition(newmotorFLTarget); robot.motorFR.setTargetPosition(newmotorFRTarget); robot.motorBL.setTargetPosition(newmotorBLTarget); robot.motorBR.setTargetPosition(newmotorBRTarget); // Turn On RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorFR.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBR.setPower(Math.abs(robot.DRIVE_SPEED)); runtime.reset(); while (opModeIsActive() && (robot.motorFL.isBusy() || robot.motorFR.isBusy() || robot.motorBL.isBusy() || robot.motorBR.isBusy())) { // Display it for the driver. telemetry.addData("Path1", "Running to %7d :%7d", newmotorFLTarget, newmotorFRTarget ); telemetry.update(); } // Stop all motion; stopRobot(); // Turn off RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorFR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void turnright(double inches) { int newmotorFLTarget; int newmotorFRTarget; int newmotorBLTarget; int newmotorBRTarget; // Determine new target position, and pass to motor controller newmotorFLTarget = robot.motorFL.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); newmotorFRTarget = robot.motorFR.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); newmotorBLTarget = robot.motorBL.getCurrentPosition() - (int)(inches * robot.COUNTS_PER_INCH); newmotorBRTarget = robot.motorBR.getCurrentPosition() + (int)(inches * robot.COUNTS_PER_INCH); robot.motorFL.setTargetPosition(newmotorFLTarget); robot.motorFR.setTargetPosition(newmotorFRTarget); robot.motorBL.setTargetPosition(newmotorBLTarget); robot.motorBR.setTargetPosition(newmotorBRTarget); // Turn On RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBL.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorBR.setMode(DcMotor.RunMode.RUN_TO_POSITION); robot.motorFL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorFR.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBL.setPower(Math.abs(robot.DRIVE_SPEED)); robot.motorBR.setPower(Math.abs(robot.DRIVE_SPEED)); runtime.reset(); while (opModeIsActive() && (robot.motorFL.isBusy() || robot.motorFR.isBusy() || robot.motorBL.isBusy() || robot.motorBR.isBusy())) { // Display it for the driver. telemetry.addData("Path1", "Running to %7d :%7d", newmotorFLTarget, newmotorFRTarget ); telemetry.update(); } // Stop all motion; stopRobot(); // Turn off RUN_TO_POSITION robot.motorFL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorFR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBL.setMode(DcMotor.RunMode.RUN_USING_ENCODER); robot.motorBR.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void stopRobot() { robot.motorFL.setPower(0); robot.motorFR.setPower(0); robot.motorBL.setPower(0); robot.motorBR.setPower(0); } public void stopRobot(int seconds) { //delay runtime.reset(); while (opModeIsActive() && (runtime.seconds() < seconds)) { stopRobot(); telemetry.addData("Motor", "Stopped"); // telemetry.update(); } } /* VUFORIA RING DETECTION */ public static class SkystoneDeterminationPipeline extends OpenCvPipeline { /* * An enum to define the skystone position */ public enum RingPosition { FOUR, ONE, NONE } /* * Some color constants */ static final Scalar BLUE = new Scalar(0, 0, 255); static final Scalar GREEN = new Scalar(0, 255, 0); /* * The core values which define the location and size of the sample regions */ static final Point REGION1_TOPLEFT_ANCHOR_POINT = new Point(85,183); static final int REGION_WIDTH = 50; static final int REGION_HEIGHT = 50; final int FOUR_RING_THRESHOLD = 135; //143-148 final int ONE_RING_THRESHOLD = 125; //119-131 Point region1_pointA = new Point( REGION1_TOPLEFT_ANCHOR_POINT.x, REGION1_TOPLEFT_ANCHOR_POINT.y); Point region1_pointB = new Point( REGION1_TOPLEFT_ANCHOR_POINT.x + REGION_WIDTH, REGION1_TOPLEFT_ANCHOR_POINT.y + REGION_HEIGHT); /* * Working variables */ Mat region1_Cb; Mat YCrCb = new Mat(); Mat Cb = new Mat(); int avg1; // Volatile since accessed by OpMode thread w/o synchronization public volatile RingPosition position = RingPosition.FOUR; /* * This function takes the RGB frame, converts to YCrCb, * and extracts the Cb channel to the 'Cb' variable */ void inputToCb(Mat input) { Imgproc.cvtColor(input, YCrCb, Imgproc.COLOR_RGB2YCrCb); Core.extractChannel(YCrCb, Cb, 1); } @Override public void init(Mat firstFrame) { inputToCb(firstFrame); region1_Cb = Cb.submat(new Rect(region1_pointA, region1_pointB)); } @Override public Mat processFrame(Mat input) { inputToCb(input); avg1 = (int) Core.mean(region1_Cb).val[0]; Imgproc.rectangle( input, // Buffer to draw on region1_pointA, // First point which defines the rectangle region1_pointB, // Second point which defines the rectangle BLUE, // The color the rectangle is drawn in 2); // Thickness of the rectangle lines position = RingPosition.FOUR; // Record our analysis if(avg1 > FOUR_RING_THRESHOLD){ position = RingPosition.FOUR; }else if (avg1 > ONE_RING_THRESHOLD){ position = RingPosition.ONE; }else{ position = RingPosition.NONE; } Imgproc.rectangle( input, // Buffer to draw on region1_pointA, // First point which defines the rectangle region1_pointB, // Second point which defines the rectangle GREEN, // The color the rectangle is drawn in 1); // Negative thickness means solid fill return input; } public int getAnalysis() { return avg1; } } }
36.188755
203
0.627973
9dfb0000f2751c0d8ef10126611b077da119664b
483
package cc.blynk.clickhouse.http; import cc.blynk.clickhouse.settings.ClickHouseProperties; public final class DefaultConnectorFactory extends HttpConnectorFactory { @Override public HttpConnector create(ClickHouseProperties properties) { return new DefaultHttpConnector(properties); } @Override public void close() { //empty because default connection factory uses HTTPUrlConnection that //is closed within connection.close() } }
26.833333
78
0.745342
f74ca9f2af244318ea617bf18e287ceefa171772
1,959
package com.print_stack_trace.voogasalad.controller.guiElements.gameObjects; import com.print_stack_trace.voogasalad.controller.guiElements.gameAuthor.ViewObjectDelegate; import com.print_stack_trace.voogasalad.model.GoalCharacteristics; import com.print_stack_trace.voogasalad.model.SpriteCharacteristics; import com.print_stack_trace.voogasalad.model.environment.GoalFactory.GoalType; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.image.ImageView; public class GoalObject extends GameObject { private SimpleObjectProperty<GoalCharacteristics> myCharacteristics=new SimpleObjectProperty<GoalCharacteristics>(); private SimpleIntegerProperty pointsProperty=new SimpleIntegerProperty(0); public GoalObject(String imagePath, ViewObjectDelegate delegate) { super(imagePath, delegate); } public GoalObject(GoalType myType, ViewObjectDelegate delegate){ super(myType, delegate); myCharacteristics.setValue(new GoalCharacteristics(myType)); pointsProperty.setValue(myCharacteristics.getValue().getPointsTotal()); } public SimpleIntegerProperty getPointsProperty(){ return pointsProperty; } public void setPointsTotal(Integer points){ this.getCharacteristics().setPointsTotal(points); pointsProperty.setValue(points); } public GoalCharacteristics getCharacteristics(){ return myCharacteristics.getValue(); } public SimpleObjectProperty<GoalCharacteristics> characteristicsProperty(){ return myCharacteristics; } public void setCharacteristics(GoalType myType){ myCharacteristics.setValue(new GoalCharacteristics(myType)); } public void setCharacteristics(GoalCharacteristics goalCharacteristics){ myCharacteristics.setValue(goalCharacteristics); } @Override public void update() { myDelegate.update(this); } @Override public void createPane() {} @Override public void showPane() {} @Override public void setImageCharacteristics() {} }
36.962264
117
0.830526
ec62c3cefbbc9ebd7603f67fbb1644709c4ea321
658
package challengeMath; import static java.lang.Math.random; import static java.lang.Math.round; public class Jogo { public static void main(String[] args) { double[] valor = new double[6]; double aleatorio; double entero; int i = 0; while( i < 6) { aleatorio = random() * 100; entero =round(aleatorio); if(entero>=1 && entero<=60) { valor[i] = entero; i++; } } for (int j = 0; j < 6; j++) { System.out.println(valor[j]); } //convertir en metodo llamar desde principal y adicionar el numero de juegos //adicionar una impresion similar a un boleto } }
18.8
79
0.585106
819aa94fe6f67c38a8bf1abbd671a3f409f5bd60
7,614
package org.ovirt.optimizer.solver.thread; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; import org.optaplanner.core.api.solver.Solver; import org.optaplanner.core.api.solver.SolverFactory; import org.optaplanner.core.config.solver.SolverConfig; import org.optaplanner.core.config.solver.termination.TerminationConfig; import org.ovirt.engine.sdk.entities.Host; import org.ovirt.engine.sdk.entities.VM; import org.ovirt.optimizer.rest.dto.Result; import org.ovirt.optimizer.solver.factchanges.CancelVmRunningFactChange; import org.ovirt.optimizer.solver.factchanges.ClusterFactChange; import org.ovirt.optimizer.solver.factchanges.EnsureVmRunningFactChange; import org.ovirt.optimizer.solver.problemspace.ClusterSituation; import org.ovirt.optimizer.solver.problemspace.Migration; import org.ovirt.optimizer.solver.problemspace.OptimalDistributionStepsSolution; import org.ovirt.optimizer.solver.util.SolverUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class represents the task for optimization * of a single cluster. */ public class ClusterOptimizer implements Supplier<OptimalDistributionStepsSolution> { private static Logger log = LoggerFactory.getLogger(ClusterOptimizer.class); private final Solver<OptimalDistributionStepsSolution> solver; private final String clusterId; private final AtomicReference<OptimalDistributionStepsSolution> bestSolution = new AtomicReference<>(); private final List<Path> customDrlFiles; /** * Use the state in the current best solution to recompute score of * provided migrations. * * This method creates a new solver with disabled construction heuristics * and local search. * * @param oldResult * @return HardSoftScore of the migrations */ public HardSoftScore computeScore(Result oldResult) { OptimalDistributionStepsSolution sourceSolution = null; sourceSolution = bestSolution.get(); return SolverUtils.computeScore(sourceSolution, oldResult, Collections.emptySet(), customDrlFiles); } public ClusterOptimizer(final String clusterId, int maxSteps, long unimprovedMilisLimit, List<Path> customDrlFiles) { this.clusterId = clusterId; this.customDrlFiles = customDrlFiles; SolverFactory<OptimalDistributionStepsSolution> solverFactory; if (maxSteps > 0) { // Construct full optimizer solverFactory = SolverFactory.createFromXmlResource("org/ovirt/optimizer/solver/rules/solver.xml"); SolverUtils.addCustomDrlFiles(solverFactory.getSolverConfig().getScoreDirectorFactoryConfig(), this.customDrlFiles); // Suspend solver when no better solution has been found for some time SolverConfig solverConfig = solverFactory.getSolverConfig(); TerminationConfig terminationConfig = solverConfig.getTerminationConfig(); terminationConfig.setUnimprovedMillisecondsSpentLimit(unimprovedMilisLimit); } else { // No optimization requested, degrade to daemonized score only solver and // provide only simple one-by-one scheduling as a service solverFactory = SolverFactory.createFromXmlResource("org/ovirt/optimizer/solver/rules/scoreonly.xml"); // There has to be at least one empty step to trigger the final situation rules maxSteps = 1; SolverUtils.addCustomDrlFiles(solverFactory.getSolverConfig().getScoreDirectorFactoryConfig(), this.customDrlFiles); // Make sure the solver runs in daemon mode SolverConfig solverConfig = solverFactory.getSolverConfig(); solverConfig.setDaemon(true); log.warn("Optimization disabled, enabling scoring subsystem only."); } solver = solverFactory.buildSolver(); solver.addEventListener(bestSolutionChangedEvent -> { // Ignore incomplete solutions if (!solver.isEveryProblemFactChangeProcessed()) { log.debug("Ignoring incomplete solution"); return; } if(!bestSolutionChangedEvent.isNewBestSolutionInitialized()) { log.debug("Ignoring uninitialized solution"); return; } // Get new solution and set the timestamp to current time OptimalDistributionStepsSolution solution = bestSolutionChangedEvent.getNewBestSolution(); solution.setTimestamp(System.currentTimeMillis()); log.info(String.format("New solution for %s available (score %s)", clusterId, solution.getScore().toString())); bestSolution.set(solution); if (log.isDebugEnabled()) { SolverUtils.recomputeScoreUsingScoreDirector(solver, solution); } }); // Create new solution space OptimalDistributionStepsSolution solution = new OptimalDistributionStepsSolution(); solution.setClusterId(clusterId); solution.setHosts(new HashSet<>()); solution.setInstances(new HashSet<>()); solution.setOtherFacts(new HashSet<>()); solution.setFixedFacts(new HashSet<>()); solution.setVms(new HashMap<>()); // Prepare the step placeholders List<Migration> migrationSteps = new ArrayList<>(); for (int i = 0; i < maxSteps; i++) { migrationSteps.add(new Migration()); } solution.setSteps(migrationSteps); solution.establishStepOrdering(); solution.setTimestamp(System.currentTimeMillis()); ClusterSituation previous = solution; for (Migration m: migrationSteps) { m.recomputeSituationAfter(previous); previous = m; } bestSolution.set(solution); } private void solve() { log.info(String.format("Solver for %s starting", clusterId)); solver.solve(bestSolution.get()); log.info(String.format("Solver for %s finished", clusterId)); bestSolution.set(solver.getBestSolution()); } public OptimalDistributionStepsSolution getBestSolution() { return bestSolution.get(); } public void terminate() { log.info(String.format("Solver thread for %s was asked to terminate", clusterId)); solver.terminateEarly(); } @Override public OptimalDistributionStepsSolution get() { log.info(String.format("Solver thread for %s starting", clusterId)); solve(); log.info(String.format("Solver thread for %s finished", clusterId)); return bestSolution.get(); } public String getClusterId() { return clusterId; } public void ensureVmIsRunning(String uuid) { solver.addProblemFactChange(new EnsureVmRunningFactChange(uuid)); } public void cancelVmIsRunning(String uuid) { solver.addProblemFactChange(new CancelVmRunningFactChange(uuid)); } public void processUpdate(final Set<VM> vms, final Set<Host> hosts, final Set<Object> facts) { solver.addProblemFactChange(new ClusterFactChange(clusterId, vms, hosts, facts)); } }
38.649746
107
0.686367
2704406e208302dd2edf46ccaffc210fd720b2ce
1,150
package fr.femm.findyourtrashcan.controller; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; 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.RequestMapping; import org.springframework.web.bind.annotation.RestController; import fr.femm.findyourtrashcan.data.Rewards; import fr.femm.findyourtrashcan.service.RewardsService; @RestController @RequestMapping(value = "/api/rewards", produces = MediaType.APPLICATION_JSON_VALUE) public class RewardsController { public final Logger logger = Logger.getLogger(RewardsController.class); @Autowired private RewardsService rewardsService; @CrossOrigin("*") @GetMapping("/rank/{rankId}") public List<Rewards> getRewardsForRank(@PathVariable("rankId") final Integer id) { logger.info("Webservice getRewardsForRank [rank-id : " + id + "]"); return rewardsService.getByRank(id); } }
35.9375
86
0.796522
f111f6e488513d27c672a622c050f6f986da3eb6
1,070
package org.folio.circulation.infrastructure.storage; import static org.folio.circulation.support.http.ResponseMapping.forwardOnFailure; import java.util.concurrent.CompletableFuture; import org.folio.circulation.domain.CheckInRecord; import org.folio.circulation.support.Clients; import org.folio.circulation.support.CollectionResourceClient; import org.folio.circulation.support.results.Result; import org.folio.circulation.support.http.client.ResponseInterpreter; public class CheckInStorageRepository { private final CollectionResourceClient checkInStorageClient; public CheckInStorageRepository(Clients clients) { checkInStorageClient = clients.checkInStorageClient(); } public CompletableFuture<Result<Void>> createCheckInLogRecord( CheckInRecord checkInRecord) { final ResponseInterpreter<Void> interpreter = new ResponseInterpreter<Void>() .on(201, Result.succeeded(null)) .otherwise(forwardOnFailure()); return checkInStorageClient.post(checkInRecord.toJson()) .thenApply(interpreter::flatMap); } }
33.4375
82
0.802804
14743ccb39d0d864fbfef9bc6ccee54dca142706
483
package edu.utexas.tacc.tapis.shared.exceptions; public class TapisNotFoundException extends TapisException { private static final long serialVersionUID = 6546186422079053585L; // Name not found. public String missingName; public TapisNotFoundException(String message, String name) {super(message); missingName = name;} public TapisNotFoundException(String message, Throwable cause, String name) {super(message, cause); missingName = name;} }
30.1875
77
0.751553
a52ce987217722b12164074ef595c62fb534a998
5,221
package eu.supersede.mdm.storage.model.omq.relational_operators; import com.clearspring.analytics.util.Lists; import com.google.gson.Gson; import eu.supersede.mdm.storage.model.omq.wrapper_implementations.*; import eu.supersede.mdm.storage.util.RDFUtil; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; import org.bson.Document; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class Wrapper extends RelationalOperator { private String wrapper; public Wrapper(String w) { this.wrapper = w; } public String getWrapper() { return wrapper; } public void setWrapper(String wrapper) { this.wrapper = wrapper; } @Override public boolean equals(Object o) { if (o instanceof Wrapper) { final Wrapper other = (Wrapper)o; return Objects.equals(wrapper,other.wrapper); } else { return false; } } @Override public int hashCode() { return Objects.hash(wrapper); } @Override public String toString() { return "("+RDFUtil.nn(wrapper)+")"; } public String inferSchema() throws Exception { throw new Exception("Can't infer the schema of a generic wrapper, need to call an implementation subclass"); } public String preview(List<String> attributes) throws Exception { throw new Exception("Can't preview a generic wrapper, need to call an implementation subclass"); } public void populate(String table, List<String> attributes) throws Exception { throw new Exception("Can't populate a generic wrapper, need to call an implementation subclass"); } public static Wrapper specializeWrapper(Document ds, String queryParameters) { Wrapper w = null; switch (ds.getString("type")) { case "avro": w = new SparkSQL_Wrapper("preview"); ((SparkSQL_Wrapper)w).setPath(ds.getString("avro_path")); ((SparkSQL_Wrapper)w).setTableName(ds.getString("name")); ((SparkSQL_Wrapper)w).setSparksqlQuery(((JSONObject) JSONValue.parse(queryParameters)).getAsString("query")); break; case "csv": w = new CSV_Wrapper("preview"); ((CSV_Wrapper)w).setPath(ds.getString("csv_path")); ((CSV_Wrapper)w).setColumnDelimiter(((JSONObject) JSONValue.parse(queryParameters)).getAsString("csvColumnDelimiter")); ((CSV_Wrapper)w).setRowDelimiter(((JSONObject) JSONValue.parse(queryParameters)).getAsString("csvRowDelimiter")); ((CSV_Wrapper)w).setHeaderInFirstRow( Boolean.parseBoolean(((JSONObject) JSONValue.parse(queryParameters)).getAsString("headersInFirstRow"))); break; case "mongodb": w = new MongoDB_Wrapper("preview"); ((MongoDB_Wrapper)w).setConnectionString(ds.getString("mongodb_connectionString")); ((MongoDB_Wrapper)w).setDatabase(ds.getString("mongodb_database")); ((MongoDB_Wrapper)w).setMongodbQuery(((JSONObject) JSONValue.parse(queryParameters)).getAsString("query")); break; case "neo4j": w = new Neo4j_Wrapper("preview"); break; case "plaintext": w = new PlainText_Wrapper("preview"); ((PlainText_Wrapper)w).setPath(ds.getString("plaintext_path")); break; case "parquet": w = new SparkSQL_Wrapper("preview"); ((SparkSQL_Wrapper)w).setPath(ds.getString("parquet_path")); ((SparkSQL_Wrapper)w).setTableName(ds.getString("name")); ((SparkSQL_Wrapper)w).setSparksqlQuery(((JSONObject) JSONValue.parse(queryParameters)).getAsString("query")); break; case "restapi": w = new REST_API_Wrapper("preview"); ((REST_API_Wrapper)w).setUrl(ds.getString("restapi_url")); break; case "sql": w = new SQL_Wrapper("preview"); ((SQL_Wrapper)w).setURL_JDBC(ds.getString("sql_jdbc")); JSONObject jsonObject = (JSONObject) JSONValue.parse(queryParameters); ((SQL_Wrapper)w).setQuery(jsonObject.getAsString("query")); break; case "json": w = new JSON_Wrapper("preview"); ((JSON_Wrapper)w).setPath(ds.getString("json_path")); //((JSON_Wrapper)w).setExplodeLevels( // ((JSONArray)((JSONObject) JSONValue.parse(queryParameters)).get("explodeLevels")).stream().map(a -> (String)a).collect(Collectors.toList()) //); //((JSON_Wrapper)w).setArrayOfValues(ds.getString("array")); //((JSON_Wrapper)w).setAttributeForSchema(ds.getString("key")); //((JSON_Wrapper)w).setValueForAttribute(ds.getString("values")); //((JSON_Wrapper)w).setCopyToParent(ds.getString("copyToParent")); } return w; } }
40.789063
161
0.608504
40f80f76b6baabc96b237ad01c950940af1d6b07
1,382
package it.uniparthenope.fairwind.data.nmea0183.mapper; import net.sf.marineapi.nmea.event.SentenceEvent; import net.sf.marineapi.nmea.sentence.VTGSentence; import it.uniparthenope.fairwind.data.nmea0183.SentenceSignalKAbstractMapper; import nz.co.fortytwo.signalk.util.SignalKConstants; import static nz.co.fortytwo.signalk.util.SignalKConstants.nav_courseOverGroundMagnetic; import static nz.co.fortytwo.signalk.util.SignalKConstants.nav_courseOverGroundTrue; import static nz.co.fortytwo.signalk.util.SignalKConstants.nav_speedOverGround; /** * Created by raffaelemontella on 29/09/16. */ public class VTGMapper extends SentenceSignalKAbstractMapper { public VTGMapper(SentenceEvent evt) { super(evt); } public static boolean is(SentenceEvent evt) { return (evt.getSentence() instanceof VTGSentence); } @Override public void map() { VTGSentence sen=(VTGSentence) evt.getSentence(); double cogMagnetic=Math.toRadians(sen.getMagneticCourse()); double cogTrue=Math.toRadians(sen.getTrueCourse()); double sog=sen.getSpeedKnots()*0.51; put(SignalKConstants.vessels_dot_self_dot +nav_courseOverGroundMagnetic,cogMagnetic); put(SignalKConstants.vessels_dot_self_dot +nav_courseOverGroundTrue,cogTrue); put(SignalKConstants.vessels_dot_self_dot +nav_speedOverGround,sog); } }
35.435897
93
0.772069
681df634fac7ee2051e42a186560567c0993e503
8,566
package net.minecraft.client.gui.fonts; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.stream.Stream; import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.fonts.providers.DefaultGlyphProvider; import net.minecraft.client.gui.fonts.providers.GlyphProviderTypes; import net.minecraft.client.gui.fonts.providers.IGlyphProvider; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.resources.ReloadListener; import net.minecraft.profiler.EmptyProfiler; import net.minecraft.profiler.IProfiler; import net.minecraft.resources.IFutureReloadListener; import net.minecraft.resources.IResource; import net.minecraft.resources.IResourceManager; import net.minecraft.util.JSONUtils; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @OnlyIn(Dist.CLIENT) public class FontResourceManager implements AutoCloseable { private static final Logger LOGGER = LogManager.getLogger(); private final Map<ResourceLocation, FontRenderer> fontRenderers = Maps.newHashMap(); private final TextureManager textureManager; private boolean forceUnicodeFont; private final IFutureReloadListener reloadListener = new ReloadListener<Map<ResourceLocation, List<IGlyphProvider>>>() { /** * Performs any reloading that can be done off-thread, such as file IO */ protected Map<ResourceLocation, List<IGlyphProvider>> prepare(IResourceManager resourceManagerIn, IProfiler profilerIn) { profilerIn.startTick(); Gson gson = (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().create(); Map<ResourceLocation, List<IGlyphProvider>> map = Maps.newHashMap(); for(ResourceLocation resourcelocation : resourceManagerIn.getAllResourceLocations("font", (p_215274_0_) -> { return p_215274_0_.endsWith(".json"); })) { String s = resourcelocation.getPath(); ResourceLocation resourcelocation1 = new ResourceLocation(resourcelocation.getNamespace(), s.substring("font/".length(), s.length() - ".json".length())); List<IGlyphProvider> list = map.computeIfAbsent(resourcelocation1, (p_215272_0_) -> { return Lists.newArrayList(new DefaultGlyphProvider()); }); profilerIn.startSection(resourcelocation1::toString); try { for(IResource iresource : resourceManagerIn.getAllResources(resourcelocation)) { profilerIn.startSection(iresource::getPackName); try ( InputStream inputstream = iresource.getInputStream(); Reader reader = new BufferedReader(new InputStreamReader(inputstream, StandardCharsets.UTF_8)); ) { profilerIn.startSection("reading"); JsonArray jsonarray = JSONUtils.getJsonArray(JSONUtils.fromJson(gson, reader, JsonObject.class), "providers"); profilerIn.endStartSection("parsing"); for(int i = jsonarray.size() - 1; i >= 0; --i) { JsonObject jsonobject = JSONUtils.getJsonObject(jsonarray.get(i), "providers[" + i + "]"); try { String s1 = JSONUtils.getString(jsonobject, "type"); GlyphProviderTypes glyphprovidertypes = GlyphProviderTypes.byName(s1); if (!FontResourceManager.this.forceUnicodeFont || glyphprovidertypes == GlyphProviderTypes.LEGACY_UNICODE || !resourcelocation1.equals(Minecraft.DEFAULT_FONT_RENDERER_NAME)) { profilerIn.startSection(s1); list.add(glyphprovidertypes.getFactory(jsonobject).create(resourceManagerIn)); profilerIn.endSection(); } } catch (RuntimeException runtimeexception) { FontResourceManager.LOGGER.warn("Unable to read definition '{}' in fonts.json in resourcepack: '{}': {}", resourcelocation1, iresource.getPackName(), runtimeexception.getMessage()); } } profilerIn.endSection(); } catch (RuntimeException runtimeexception1) { FontResourceManager.LOGGER.warn("Unable to load font '{}' in fonts.json in resourcepack: '{}': {}", resourcelocation1, iresource.getPackName(), runtimeexception1.getMessage()); } profilerIn.endSection(); } } catch (IOException ioexception) { FontResourceManager.LOGGER.warn("Unable to load font '{}' in fonts.json: {}", resourcelocation1, ioexception.getMessage()); } profilerIn.startSection("caching"); for(char c0 = 0; c0 < '\uffff'; ++c0) { if (c0 != ' ') { for(IGlyphProvider iglyphprovider : Lists.reverse(list)) { if (iglyphprovider.getGlyphInfo(c0) != null) { break; } } } } profilerIn.endSection(); profilerIn.endSection(); } profilerIn.endTick(); return map; } protected void apply(Map<ResourceLocation, List<IGlyphProvider>> objectIn, IResourceManager resourceManagerIn, IProfiler profilerIn) { profilerIn.startTick(); profilerIn.startSection("reloading"); Stream.concat(FontResourceManager.this.fontRenderers.keySet().stream(), objectIn.keySet().stream()).distinct().forEach((p_215271_2_) -> { List<IGlyphProvider> list = objectIn.getOrDefault(p_215271_2_, Collections.emptyList()); Collections.reverse(list); FontResourceManager.this.fontRenderers.computeIfAbsent(p_215271_2_, (p_215273_1_) -> { return new FontRenderer(FontResourceManager.this.textureManager, new Font(FontResourceManager.this.textureManager, p_215273_1_)); }).setGlyphProviders(list); }); profilerIn.endSection(); profilerIn.endTick(); } public String func_225594_i_() { return "FontManager"; } }; public FontResourceManager(TextureManager textureManagerIn, boolean forceUnicodeFontIn) { this.textureManager = textureManagerIn; this.forceUnicodeFont = forceUnicodeFontIn; } @Nullable public FontRenderer getFontRenderer(ResourceLocation id) { return this.fontRenderers.computeIfAbsent(id, (p_212318_1_) -> { FontRenderer fontrenderer = new FontRenderer(this.textureManager, new Font(this.textureManager, p_212318_1_)); fontrenderer.setGlyphProviders(Lists.newArrayList(new DefaultGlyphProvider())); return fontrenderer; }); } public void setForceUnicodeFont(boolean p_216883_1_, Executor p_216883_2_, Executor p_216883_3_) { if (p_216883_1_ != this.forceUnicodeFont) { this.forceUnicodeFont = p_216883_1_; IResourceManager iresourcemanager = Minecraft.getInstance().getResourceManager(); IFutureReloadListener.IStage ifuturereloadlistener$istage = new IFutureReloadListener.IStage() { public <T> CompletableFuture<T> markCompleteAwaitingOthers(T backgroundResult) { return CompletableFuture.completedFuture(backgroundResult); } }; this.reloadListener.reload(ifuturereloadlistener$istage, iresourcemanager, EmptyProfiler.INSTANCE, EmptyProfiler.INSTANCE, p_216883_2_, p_216883_3_); } } public IFutureReloadListener getReloadListener() { return this.reloadListener; } public void close() { this.fontRenderers.values().forEach(FontRenderer::close); } }
48.123596
208
0.670675
06b9d522e73e702d5750164d756657cd128638a4
11,271
/* * This file is part of TechReborn, licensed under the MIT License (MIT). * * Copyright (c) 2018 TechReborn * * 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 techreborn.init; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.oredict.OreDictionary; import reborncore.api.recipe.RecipeHandler; import reborncore.common.registration.RebornRegistry; import reborncore.common.util.ItemUtils; import reborncore.common.util.OreUtil; import reborncore.common.util.RebornCraftingHelper; import techreborn.Core; import techreborn.api.recipe.machines.GrinderRecipe; import techreborn.api.recipe.machines.VacuumFreezerRecipe; import techreborn.compat.CompatManager; import techreborn.config.ConfigTechReborn; import techreborn.init.recipes.*; import techreborn.items.*; import techreborn.items.ingredients.ItemDusts; import techreborn.items.ingredients.ItemIngots; import techreborn.lib.ModInfo; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import static techreborn.utils.OreDictUtils.getDictData; import static techreborn.utils.OreDictUtils.getDictOreOrEmpty; import static techreborn.utils.OreDictUtils.isDictPrefixed; import static techreborn.utils.OreDictUtils.joinDictName; @RebornRegistry(modID = ModInfo.MOD_ID) public class ModRecipes { public static void init() { //Gonna rescan to make sure we have an uptodate list OreUtil.scanForOres(); //Done again incase we loaded before QuantumStorage CompatManager.isQuantumStorageLoaded = Loader.isModLoaded("quantumstorage"); CraftingTableRecipes.init(); SmeltingRecipes.init(); ExtractorRecipes.init(); RollingMachineRecipes.init(); FluidGeneratorRecipes.init(); IndustrialGrinderRecipes.init(); IndustrialCentrifugeRecipes.init(); IndustrialElectrolyzerRecipes.init(); ImplosionCompressorRecipes.init(); ScrapboxRecipes.init(); ChemicalReactorRecipes.init(); FusionReactorRecipes.init(); DistillationTowerRecipes.init(); AlloySmelterRecipes.init(); FluidReplicatorRecipes.init(); BlastFurnaceRecipes.init(); CompressorRecipes.init(); addVacuumFreezerRecipes(); addIc2Recipes(); addGrinderRecipes(); } public static void postInit() { if (ConfigTechReborn.disableRailcraftSteelNuggetRecipe) { Iterator<Entry<ItemStack, ItemStack>> iterator = FurnaceRecipes.instance().getSmeltingList().entrySet().iterator(); Map.Entry<ItemStack, ItemStack> entry; while (iterator.hasNext()) { entry = iterator.next(); if (entry.getValue() instanceof ItemStack && entry.getKey() instanceof ItemStack) { ItemStack input = (ItemStack) entry.getKey(); ItemStack output = (ItemStack) entry.getValue(); if (ItemUtils.isInputEqual("nuggetSteel", output, true, true, false) && ItemUtils.isInputEqual("nuggetIron", input, true, true, false)) { Core.logHelper.info("Removing a steelnugget smelting recipe"); iterator.remove(); } } } } IndustrialSawmillRecipes.init(); } static void addGrinderRecipes() { // Vanilla // int eutick = 2; // int ticktime = 300; RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Items.BONE), new ItemStack(Items.DYE, 6, 15), 170, 19)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.COBBLESTONE), new ItemStack(Blocks.SAND), 230, 23)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.GRAVEL), new ItemStack(Items.FLINT), 200, 20)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Items.COAL), ItemDusts.getDustByName("coal"), 230, 27)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Items.COAL, 1, 1), ItemDusts.getDustByName("charcoal"), 230, 27)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(net.minecraft.init.Items.CLAY_BALL), ItemDusts.getDustByName("clay"), 200, 18)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.GLOWSTONE), ItemDusts.getDustByName("glowstone", 4), 220, 21)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.NETHERRACK), ItemDusts.getDustByName("netherrack"), 300, 27)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.END_STONE), ItemDusts.getDustByName("endstone"), 300, 16)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Items.ENDER_EYE), ItemDusts.getDustByName("ender_eye", 2), 200, 22)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Items.ENDER_PEARL), ItemDusts.getDustByName("ender_pearl", 2), 200, 22)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.LAPIS_ORE), new ItemStack(Items.DYE, 10, 4), 170, 19)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.OBSIDIAN), ItemDusts.getDustByName("obsidian", 4), 170, 19)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Items.BLAZE_ROD), new ItemStack(Items.BLAZE_POWDER, 4), 170, 19)); if (OreUtil.doesOreExistAndValid("stoneMarble")) { ItemStack marbleStack = getOre("stoneMarble"); marbleStack.setCount(1); RecipeHandler.addRecipe(new GrinderRecipe( marbleStack, ItemDusts.getDustByName("marble"), 120, 10)); } if (OreUtil.doesOreExistAndValid("stoneBasalt")) { ItemStack marbleStack = getOre("stoneBasalt"); marbleStack.setCount(1); RecipeHandler.addRecipe(new GrinderRecipe( marbleStack, ItemDusts.getDustByName("basalt"), 120, 10)); } //See comments bellow, this allows the ore to go to the product when it sometimes goes straight to dust. RecipeHandler.addRecipe(new GrinderRecipe( "oreCoal", new ItemStack(Items.COAL, 2), 270, 31)); RecipeHandler.addRecipe(new GrinderRecipe( "oreDiamond", new ItemStack(Items.DIAMOND, 1), 270, 31)); RecipeHandler.addRecipe(new GrinderRecipe( "oreEmerald", new ItemStack(Items.EMERALD, 1), 270, 31)); RecipeHandler.addRecipe(new GrinderRecipe( "oreRedstone", new ItemStack(Items.REDSTONE, 8), 270, 31)); RecipeHandler.addRecipe(new GrinderRecipe( "oreQuartz", new ItemStack(Items.QUARTZ, 2), 270, 31)); for (String oreDictionaryName : OreDictionary.getOreNames()) { if (isDictPrefixed(oreDictionaryName, "ore", "gem", "ingot")) { ItemStack oreStack = getDictOreOrEmpty(oreDictionaryName, 1); String[] data = getDictData(oreDictionaryName); //High-level ores shouldn't grind here if (data[0].equals("ore") && ( data[1].equals("tungsten") || data[1].equals("titanium") || data[1].equals("aluminium") || data[1].equals("iridium") || data[1].equals("saltpeter")|| data[1].equals("coal") || //Done here to skip going to dust so it can go to the output data[1].equals("diamond") || //For example diamond ore should go to diamonds not the diamond dust data[1].equals("emerald") || //TODO possibly remove this and make it a bit more dyamic? (Check for furnace recipes? and then the block drop?) data[1].equals("redstone") || data[1].equals("quartz") ) || oreStack.isEmpty()) continue; boolean ore = data[0].equals("ore"); Core.logHelper.debug("Ore: " + data[1]); ItemStack dust = getDictOreOrEmpty(joinDictName("dust", data[1]), ore ? 2 : 1); if (dust.isEmpty() || dust.getItem() == null) { continue; } dust = dust.copy(); if (ore) { dust.setCount(2); } boolean useOreDict = true; //Disables the ore dict for lapis, this is becuase it is oredict with dye. This may cause some other lapis ores to not be grindable, but we can fix that when that arrises. if(data[1].equalsIgnoreCase("lapis")){ useOreDict = false; } RecipeHandler.addRecipe(new GrinderRecipe(oreStack, dust, ore ? 270 : 200, ore ? 31 : 22, useOreDict)); } } } static void addVacuumFreezerRecipes() { RecipeHandler.addRecipe(new VacuumFreezerRecipe( new ItemStack(Blocks.ICE, 2), new ItemStack(Blocks.PACKED_ICE), 60, 64 )); RecipeHandler.addRecipe(new VacuumFreezerRecipe( ItemIngots.getIngotByName("hot_tungstensteel"), ItemIngots.getIngotByName("tungstensteel"), 440, 64)); RecipeHandler.addRecipe(new VacuumFreezerRecipe( ItemCells.getCellByName("heliumplasma"), ItemCells.getCellByName("helium"), 440, 64)); RecipeHandler.addRecipe( new VacuumFreezerRecipe( ItemCells.getCellByName("water"), ItemCells.getCellByName("cell"), 60, 64)); } static void addIc2Recipes() { RebornCraftingHelper.addShapelessOreRecipe(new ItemStack(ModItems.MANUAL), "ingotRefinedIron", Items.BOOK); // RebornCraftingHelper // .addShapedOreRecipe(ItemParts.getPartByName("machineParts", 16), "CSC", "SCS", "CSC", 'S', "ingotSteel", // 'C', "circuitBasic"); // // RebornCraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.magicalAbsorber), // "CSC", "IBI", "CAC", // 'C', "circuitMaster", // 'S', "craftingSuperconductor", // 'B', Blocks.beacon, // 'A', ModBlocks.magicEnergeyConverter, // 'I', "plateIridium"); // // RebornCraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.magicEnergeyConverter), // "CTC", "PBP", "CLC", // 'C', "circuitAdvanced", // 'P', "platePlatinum", // 'B', Blocks.beacon, // 'L', "lapotronCrystal", // 'T', TechRebornAPI.recipeCompact.getItem("teleporter")); // RebornCraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.chunkLoader), // "SCS", "CMC", "SCS", // 'S', "plateSteel", // 'C', "circuitMaster", // 'M', new ItemStack(ModItems.parts, 1, 39)); } public static ItemStack getBucketWithFluid(Fluid fluid) { return FluidUtil.getFilledBucket(new FluidStack(fluid, Fluid.BUCKET_VOLUME)); } public static ItemStack getOre(String name) { if (OreDictionary.getOres(name).isEmpty()) { return new ItemStack(ModItems.MISSING_RECIPE_PLACEHOLDER); } return OreDictionary.getOres(name).get(0).copy(); } }
33.247788
175
0.722119
740750898d661fb4433550ccc4f2adfbaef542ef
3,655
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <h1></h1> * Created by hanqf on 2021/9/6 14:38. */ @RestController public class DemoController { @Autowired CountryJpaRepository countryJpaRepository; @Autowired DemoEntityJpaRepository demoEntityJpaRepository; @GetMapping("/") public Map index() { Map<String, Object> map = new HashMap<>(); final BigInteger size = countryJpaRepository.findBySqlFirst("SELECT count(*) as count FROM ad_country", BigInteger.class, true); map.put("size", size); //分页 Pageable pageable = PageRequest.of(1, 20, Sort.by(Sort.Direction.DESC, "id").and(Sort.by(Sort.Direction.ASC, "name_zh"))); final Page<Country> pages = countryJpaRepository.findPageBySql("SELECT id,name_zh as nameZh ,name_en as nameEn FROM ad_country", pageable, Country.class, false); map.put("pages", pages); //批量新增 List<DemoEntity> entityList = new ArrayList<>(); for (int i = 0; i < 1000; i++) { DemoEntity demoEntity = new DemoEntity(); demoEntity.setName("测试" + i); demoEntity.initInsert(); entityList.add(demoEntity); } demoEntityJpaRepository.batchSave(entityList); final Page<DemoEntity> demoEntities = demoEntityJpaRepository.findAll(PageRequest.of(1, 100, Sort.by(Sort.Direction.DESC, "name"))); //批量删除 demoEntityJpaRepository.deleteAllInBatch(demoEntities.getContent()); return map; } @GetMapping("/query") public Map query() { final Country country = countryJpaRepository.findCountrySqlByName("中国"); final Country country2 = countryJpaRepository.findCountryHqlByName("中国"); final CountryDto country3 = countryJpaRepository.findCountryDtoNewHqlByName("中国"); final CountryDto countryDtoSql = countryJpaRepository.findCountryDtoSqlByName("中国"); final CountryDto countryDtoHql = countryJpaRepository.findCountryDtoHqlByName("中国"); Pageable pageable = PageRequest.of(0, 20, Sort.by(Sort.Direction.DESC, "id")); final Page<Country> countryPage = countryJpaRepository.findByIdAfter(45L, pageable); final Page<CountryDto> countryPojoPage = countryJpaRepository.findByIdAfterDto(45L, pageable); Map<String, Object> map = new HashMap<>(); return map; } @GetMapping("/query2") public Map query2() { final List<Country> countries = countryJpaRepository.nameHqlFindAll(); final List<Country> countries1 = countryJpaRepository.nameSqlFindAll(); final List<Country> countries2 = countryJpaRepository.nameSqlFindAll2(); final List<Country> countries3 = countryJpaRepository.nameSqlFindSomeField(); List<Country> list = countryJpaRepository.getEntityManager().createNamedQuery("SQL_FIND_ALL_COUNTRY").getResultList(); List<Country> list2 = countryJpaRepository.getEntityManager().createNativeQuery("select id,name_zh as nameZh,name_en as nameEn from tbl_country","SQL_RESULT_COUNTRY_SOME_FIELD").getResultList(); Map<String, Object> map = new HashMap<>(); return map; } }
36.55
202
0.709439
816e7e682d13c2a7846e2e580ea5fb9867e55b4c
2,218
/** * This software is released as part of the Pumpernickel project. * * All com.pump resources in the Pumpernickel project are distributed under the * MIT License: * https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt * * More information about the Pumpernickel project is available here: * https://mickleness.github.io/pumpernickel/ */ package com.pump.data; import java.beans.PropertyChangeListener; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; /** * This is a minimal implementation of the AttributeData interface that is * backed with a HashMap. */ public class AttributeDataImpl extends AbstractAttributeDataImpl implements AttributeData { private static final long serialVersionUID = 1L; @Override public ReadWriteLock getAttributeLock() { return super.getAttributeLock(); } @Override public <T> T setAttribute(Key<T> key, T value) { return super.setAttribute(key, value); } @Override public void handleUncaughtListenerException(Exception e, String propertyName, Object oldValue, Object newValue) { super.handleUncaughtListenerException(e, propertyName, oldValue, newValue); } @Override public void putAllAttributes(Map<String, Object> incomingData, boolean completeReplace) { super.putAllAttributes(incomingData, completeReplace); } @Override public <T> T getAttribute(Key<T> key) { return super.getAttribute(key); } @Override public void clearAttributes() { super.clearAttributes(); } @Override public int getAttributeCount() { return super.getAttributeCount(); } @Override public String[] getAttributes() { return super.getAttributes(); } @Override public Map<String, Object> getAttributeMap() { return super.getAttributeMap(); } @Override public void addAttributePropertyChangeListener(String propertyName, PropertyChangeListener pcl) { super.addPropertyChangeListener(propertyName, pcl); } @Override public void addAttributePropertyChangeListener(PropertyChangeListener pcl) { super.addPropertyChangeListener(pcl); } @Override public void removeAttributePropertyChangeListener(PropertyChangeListener pcl) { super.removePropertyChangeListener(pcl); } }
25.204545
80
0.772317
df3de42818ad2f095ebbc58ec6a5e1fe4a169893
11,669
package de.azrael.listeners; import java.awt.Color; import java.sql.Timestamp; import java.util.EnumSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.azrael.constructors.Bancollect; import de.azrael.constructors.Channels; import de.azrael.core.Hashes; import de.azrael.enums.Channel; import de.azrael.enums.GoogleEvent; import de.azrael.enums.Translation; import de.azrael.fileManagement.GuildIni; import de.azrael.fileManagement.IniFileReader; import de.azrael.google.GoogleSheets; import de.azrael.sql.Azrael; import de.azrael.util.STATIC; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.audit.ActionType; import net.dv8tion.jda.api.audit.AuditLogEntry; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.events.guild.GuildBanEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.requests.restaction.pagination.AuditLogPaginationAction; /** * This class gets launched when a user in the guild gets banned. * * The banned user will be marked as banned on the database and will * print a message into the log channel, that a user has been banned. * @author xHelixStorm * */ public class BanListener extends ListenerAdapter { private final static Logger logger = LoggerFactory.getLogger(BanListener.class); @Override public void onGuildBan(GuildBanEvent e) { long user_id = e.getUser().getIdLong(); long guild_id = e.getGuild().getIdLong(); var user = Azrael.SQLgetData(user_id, guild_id); var log_channel = Azrael.SQLgetChannels(e.getGuild().getIdLong()).parallelStream().filter(f -> f.getChannel_Type() != null && f.getChannel_Type().equals(Channel.LOG.getType())).findAny().orElse(null); //either update user as banned or if not available, insert directly as banned if(user.getBanID() == 1 && user.getWarningID() > 0) { if(Azrael.SQLUpdateBan(user_id, guild_id, 2) > 0) { //terminate mute timer for the banned user if it's running STATIC.killThread("mute_gu"+e.getGuild().getId()+"us"+e.getUser().getId()); } else { STATIC.writeToRemoteChannel(e.getGuild(), new EmbedBuilder().setColor(Color.RED).setTitle(STATIC.getTranslation2(e.getGuild(), Translation.EMBED_TITLE_ERROR)), STATIC.getTranslation2(e.getGuild(), Translation.BAN_ERR), Channel.LOG.getType()); logger.error("The banned user {} couldn't be labeled as banned in guild {}", e.getUser().getId(), e.getGuild().getId()); } } else{ Timestamp timestamp = new Timestamp(System.currentTimeMillis()); if(Azrael.SQLInsertData(user_id, guild_id, 0, 2, timestamp, timestamp, true, false) > 0) { //terminate mute timer for the banned user if it's running STATIC.killThread("mute_gu"+e.getGuild().getId()+"us"+e.getUser().getId()); } else { STATIC.writeToRemoteChannel(e.getGuild(), new EmbedBuilder().setColor(Color.RED).setTitle(STATIC.getTranslation2(e.getGuild(), Translation.EMBED_TITLE_ERROR)), STATIC.getTranslation2(e.getGuild(), Translation.BAN_ERR), Channel.LOG.getType()); logger.error("The banned user {} couldn't be labeled as banned in guild {}", e.getUser().getId(), e.getGuild().getId()); } } new Thread(() -> { //Unwatch the banned user, if he's being watched STATIC.handleUnwatch(e, null, (short)1); logger.info("User {} has been banned in guild {}", e.getUser().getId(), e.getGuild().getId()); Azrael.SQLInsertActionLog("MEMBER_BAN_ADD", user_id, guild_id, "User Banned"); if(log_channel != null) { final TextChannel textChannel = e.getGuild().getTextChannelById(log_channel.getChannel_ID()); if(textChannel != null && (e.getGuild().getSelfMember().hasPermission(textChannel, Permission.VIEW_CHANNEL, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.MESSAGE_EMBED_LINKS) || STATIC.setPermissions(e.getGuild(), textChannel, EnumSet.of(Permission.VIEW_CHANNEL, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.MESSAGE_EMBED_LINKS)))) { //retrieve reason and applier if it has been cached, else retrieve the user from the audit log var cache = Hashes.getTempCache("ban_gu"+e.getGuild().getId()+"us"+e.getUser().getId()); if(cache != null) { //apply stored reason and ban applier to variable Member member = e.getGuild().getMemberById(cache.getAdditionalInfo()); var ban_issuer = member.getAsMention(); var ban_reason = cache.getAdditionalInfo2(); EmbedBuilder ban = new EmbedBuilder().setColor(Color.RED).setThumbnail(IniFileReader.getKickThumbnail()).setTitle(STATIC.getTranslation2(e.getGuild(), Translation.BAN_TITLE)); //retrieve max allowed warnings per guild and print a message depending on the applied warnings before ban int max_warning_id = Azrael.SQLgetMaxWarning(guild_id); if(user.getWarningID() == 0) { textChannel.sendMessage(ban.setDescription(STATIC.getTranslation2(e.getGuild(), Translation.BAN_MESSAGE_1).replaceFirst("\\{\\}", e.getUser().getName()+"#"+e.getUser().getDiscriminator()).replaceFirst("\\{\\}", ""+user_id).replace("{}", ban_issuer)+ban_reason).build()).queue(); } else if(user.getWarningID() < max_warning_id) { textChannel.sendMessage(ban.setDescription(STATIC.getTranslation2(e.getGuild(), Translation.BAN_MESSAGE_2).replaceFirst("\\{\\}", e.getUser().getName()+"#"+e.getUser().getDiscriminator()).replaceFirst("\\{\\}", ""+user_id).replaceFirst("\\{\\}", ""+user.getWarningID()).replace("{}", ban_issuer)+ban_reason).build()).queue(); } else if(user.getWarningID() == max_warning_id) { textChannel.sendMessage(ban.setDescription(STATIC.getTranslation2(e.getGuild(), Translation.BAN_MESSAGE_3).replaceFirst("\\{\\}", e.getUser().getName()+"#"+e.getUser().getDiscriminator()).replaceFirst("\\{\\}", ""+user_id).replace("{}", ban_issuer)+ban_reason).build()).queue(); } //clear cache afterwards Hashes.clearTempCache("ban_gu"+e.getGuild().getId()+"us"+e.getUser().getId()); //Run google service, if enabled if(GuildIni.getGoogleFunctionalitiesEnabled(guild_id) && GuildIni.getGoogleSpreadsheetsEnabled(guild_id)) { GoogleSheets.spreadsheetBanRequest(Azrael.SQLgetGoogleFilesAndEvent(guild_id, 2, GoogleEvent.BAN.id, ""), e.getGuild(), "", ""+user_id, new Timestamp(System.currentTimeMillis()), e.getUser().getName()+"#"+e.getUser().getDiscriminator(), e.getUser().getName(), member.getUser().getName()+"#"+member.getUser().getDiscriminator(), member.getEffectiveName(), ban_reason, ""+user.getWarningID()); } } else { //check if the bot has permission to read the audit logs if(e.getGuild().getSelfMember().hasPermission(Permission.VIEW_AUDIT_LOGS)) { getBanAuditLog(e, user_id, guild_id, log_channel, user); } else { EmbedBuilder ban = new EmbedBuilder().setColor(Color.RED).setThumbnail(IniFileReader.getKickThumbnail()).setTitle(STATIC.getTranslation2(e.getGuild(), Translation.BAN_TITLE)); textChannel.sendMessage(ban.setDescription(STATIC.getTranslation2(e.getGuild(), Translation.BAN_MESSAGE_4).replaceFirst("\\{\\}", e.getUser().getName()+"#"+e.getUser().getDiscriminator()).replaceFirst("\\{\\}", ""+user_id).replaceFirst("\\{\\}", STATIC.getTranslation2(e.getGuild(), Translation.NOT_AVAILABLE)).replace("{}", STATIC.getTranslation2(e.getGuild(), Translation.DEFAULT_REASON))).build()).queue(); logger.warn("VIEW AUDIT LOGS permission required in guild {}", e.getGuild().getId()); } } } } }).start(); } private static void getBanAuditLog(GuildBanEvent e, long user_id, long guild_id, Channels log_channel, Bancollect user) { //retrieve latest audit log AuditLogPaginationAction banLog = e.getGuild().retrieveAuditLogs().cache(false); banLog.limit(1); banLog.queue((entries) -> { //verify that a ban occurred if(entries.get(0).getType() == ActionType.BAN) { var ban_issuer = ""; var ban_reason = ""; //verify that the audit log is about the same user that has been banned if(!entries.isEmpty() && entries.get(0).getTargetIdLong() == user_id) { AuditLogEntry entry = entries.get(0); //retrieve all details from the audit logs ban_issuer = entry.getUser().getAsMention(); ban_reason = (entry.getReason() != null && entry.getReason().length() > 0 ? entry.getReason() : STATIC.getTranslation2(e.getGuild(), Translation.DEFAULT_REASON)); EmbedBuilder ban = new EmbedBuilder().setColor(Color.RED).setThumbnail(IniFileReader.getKickThumbnail()).setTitle(STATIC.getTranslation2(e.getGuild(), Translation.BAN_TITLE)); //retrieve max allowed warnings per guild and print a message depending on the applied warnings before ban int max_warning_id = Azrael.SQLgetMaxWarning(guild_id); if(user.getWarningID() == 0) { e.getGuild().getTextChannelById(log_channel.getChannel_ID()).sendMessage(ban.setDescription(STATIC.getTranslation2(e.getGuild(), Translation.BAN_MESSAGE_1).replaceFirst("\\{\\}", e.getUser().getName()+"#"+e.getUser().getDiscriminator()).replaceFirst("\\{\\}", ""+user_id).replace("{}", ban_issuer)+ban_reason).build()).queue(); } else if(user.getWarningID() < max_warning_id) { e.getGuild().getTextChannelById(log_channel.getChannel_ID()).sendMessage(ban.setDescription(STATIC.getTranslation2(e.getGuild(), Translation.BAN_MESSAGE_2).replaceFirst("\\{\\}", e.getUser().getName()+"#"+e.getUser().getDiscriminator()).replaceFirst("\\{\\}", ""+user_id).replaceFirst("\\{\\}", ""+user.getWarningID()).replace("{}", ban_issuer)+ban_reason).build()).queue(); } else if(user.getWarningID() == max_warning_id) { e.getGuild().getTextChannelById(log_channel.getChannel_ID()).sendMessage(ban.setDescription(STATIC.getTranslation2(e.getGuild(), Translation.BAN_MESSAGE_3).replaceFirst("\\{\\}", e.getUser().getName()+"#"+e.getUser().getDiscriminator()).replaceFirst("\\{\\}", ""+user_id).replace("{}", ban_issuer)+ban_reason).build()).queue(); } //Run google service, if enabled if(GuildIni.getGoogleFunctionalitiesEnabled(guild_id) && GuildIni.getGoogleSpreadsheetsEnabled(guild_id)) { GoogleSheets.spreadsheetBanRequest(Azrael.SQLgetGoogleFilesAndEvent(guild_id, 2, GoogleEvent.BAN.id, ""), e.getGuild(), "", ""+user_id, new Timestamp(System.currentTimeMillis()), e.getUser().getName()+"#"+e.getUser().getDiscriminator(), e.getUser().getName(), entry.getUser().getName()+"#"+entry.getUser().getDiscriminator(), e.getGuild().getMemberById(entry.getUser().getIdLong()).getEffectiveName(), ban_reason, ""+user.getWarningID()); } } else { try { //put thread to sleep and then retry Thread.sleep(100); } catch (InterruptedException e1) { logger.trace("Ban thread interrupted for user {} in guild {}", e.getUser().getId(), e.getGuild().getId(), e1); } //retrieve the log recursively until the newly banned user has been found getBanAuditLog(e, user_id, guild_id, log_channel, user); } } else { try { //put thread to sleep and then retry Thread.sleep(100); } catch (InterruptedException e1) { logger.trace("Ban thread interrupted for user {} in guild {}", e.getUser().getId(), e.getGuild().getId(), e1); } //retrieve the log recursively until the newly banned user has been found getBanAuditLog(e, user_id, guild_id, log_channel, user); } }); } }
62.736559
445
0.702202
388be3eacafd6e48e8399e51fbeb7e9e98672c8b
2,579
/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2019 Grégory Van den Borre * * More infos available: https://engine.yildiz-games.be * * 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 be.yildizgames.module.graphic.camera; import be.yildizgames.common.geometry.Point3D; /** * Define how the camera will behave when receiving position and orientation change request. */ public interface CameraBehavior { /** * The camera will look to a given target. * @param camera Camera to use. * @param target Target to look at. */ void lookAt(Camera camera, Point3D target); /** * Update the camera position. * @param camera Camera to use. * @param newPosition New position to set. */ void setPosition(Camera camera, Point3D newPosition); /** * Move the camera to a given destination. * @param camera Camera to use. * @param destination destination to go to. */ void move(Camera camera, Point3D destination); /** * Rotate on the Y axis (vertical one). * @param camera Camera to use. * @param yaw Angle to rotate on Y axis(vertical), in radians. * @param pitch Angle to rotate on X axis (vertical), in radians */ void rotate(Camera camera, float yaw, float pitch); void setRelativePosition(Camera camera, Point3D position); /** * Initialize, or reinitialize the camera. * @param camera Camera to use. */ void initialise(Camera camera); }
35.819444
93
0.706863
886cff377265c3b2913483217c1d0813d049f9f1
4,560
package com.vordel.circuit.script.context.resources; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.vordel.kps.Model; import com.vordel.kps.ObjectExists; import com.vordel.kps.ObjectNotFound; import com.vordel.kps.Store; import com.vordel.kps.Transaction; import com.vordel.kps.impl.KPS; import com.vordel.kps.query.KeyQuery; public abstract class KPSResource implements ContextResource, ViewableResource { private static final Method MODEL_METHOD; private static final Object INSTANCE; static { try { /* * reflection stuff to support from 7.5 to 7.7.0.20200530 */ Method instanceMethod = KPS.class.getMethod("getInstance"); Class<?> instanceType = instanceMethod.getReturnType(); INSTANCE = instanceMethod.invoke(null); MODEL_METHOD = instanceType.getMethod("getModel"); } catch (NoSuchMethodException e) { throw new IllegalStateException("Unable to find requested KPS methods", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Unable to invoke requested KPS methods", e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); throw new IllegalStateException("Unable to retrieve KPS instance", cause); } } public static Model getModel() { try { return (Model) MODEL_METHOD.invoke(INSTANCE); } catch (IllegalAccessException e) { throw new IllegalStateException("Unable to retrieve KPS model", e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); throw new IllegalStateException("Unable to retrieve KPS model", cause); } } public abstract Store getStore(); public String getPrimaryKey() { Store store = getStore(); return store.getPrimaryKey(); } public List<String> getReadKey() { Store store = getStore(); return store.getReadKey(); } public Map<String, Object> getCached(KeyQuery query) throws ObjectNotFound { Store store = getStore(); return store.getCached(query); } public Map<String, Object> getCached(Object id) throws ObjectNotFound { Store store = getStore(); return store.getCached(id); } public Map<String, Object> getEntry(Object key) throws ObjectNotFound { Store store = getStore(); Transaction transaction = store.beginTransaction(); Map<String, Object> entry = null; try { entry = transaction.get(key); } finally { transaction.close(); } return entry; } public Map<String, Object> createEntry(Map<String, Object> entry) throws ObjectExists { Store store = getStore(); Transaction transaction = store.beginTransaction(); try { entry = transaction.create(entry); } finally { transaction.close(); } return entry; } public Map<String, Object> createEntry(Map<String, Object> entry, int ttl) throws ObjectExists { Store store = getStore(); Transaction transaction = store.beginTransaction(); try { entry = transaction.create(entry, ttl); } finally { transaction.close(); } return entry; } public Map<String, Object> updateEntry(Map<String, Object> entry) throws ObjectNotFound, ObjectExists { Store store = getStore(); Transaction transaction = store.beginTransaction(); try { entry = transaction.update(entry); } finally { transaction.close(); } return entry; } public Map<String, Object> updateEntry(Map<String, Object> entry, int ttl) throws ObjectNotFound, ObjectExists { Store store = getStore(); Transaction transaction = store.beginTransaction(); try { entry = transaction.update(entry, ttl); } finally { transaction.close(); } return entry; } public void removeEntry(Object key) throws ObjectNotFound { Store store = getStore(); Transaction transaction = store.beginTransaction(); try { transaction.delete(key); } finally { transaction.close(); } } @Override public KPSDictionaryView getResourceView() { return new KPSDictionaryView(this); } public Map<Object, Map<String, Object>> asMap() { return new KPSMap(getStore(), null); } public Map<Object, Map<String, Object>> asMap(int ttl) { return new KPSMap(getStore(), ttl); } public static class KeyQueryBuilder { private final List<String> keys = new ArrayList<String>(); private final List<Object> values = new ArrayList<Object>(); public KeyQueryBuilder append(String key, Object value) { keys.add(key); values.add(value); return this; } public KeyQuery build() { return new KeyQuery(keys, values); } } }
24.782609
113
0.719298
916a782cfb3fad897b5554fd69d3df9f95307d5d
2,866
package com.aises.repository; import com.aises.domain.SocialLogin; import com.aises.domain.User; import com.aises.domain.enums.SocialLoginType; import com.aises.repository.interfaces.Repository; import com.aises.server.Database; import com.aises.utils.ResourceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by Brendan on 8/1/2016. * * A Repository for manipulating user tables */ public class UserRepository implements Repository { private static final Logger logger = LoggerFactory.getLogger(UserRepository.class); private static UserRepository instance; private final Database database; //private static final String DROP_USER_TABLES = ResourceLoader.loadFile("sql/user/admin/clean-user-tables.sql"); private static final String CREATE_IF_NEEDED = ResourceLoader.loadFile("sql/user/admin/create-user-tables.sql"); private static final String POPULATE_IF_NEEDED = ResourceLoader.loadFile("sql/user/admin/populate-user-tables.sql"); private static final String SOCIAL_MEDIA_ID_EXISTS = ResourceLoader.loadFile("sql/user/query/social-login-id-exists.sql"); private UserRepository(Database database) { logger.debug("Creating a repository for Users"); this.database = database; try { Connection con = this.database.getConnection(); logger.debug("Attempting to create tables"); PreparedStatement createTables = con.prepareStatement(CREATE_IF_NEEDED); createTables.execute(); PreparedStatement populateTables = con.prepareStatement(POPULATE_IF_NEEDED); populateTables.execute(); } catch (SQLException e) { logger.error("Error creating required tables for Users!", e); } } public static UserRepository getInstance() { if(instance == null) { instance = new UserRepository(null); } return instance; } public static UserRepository getInstance(@SuppressWarnings("SameParameterValue") Database database) { if(instance == null) { instance = new UserRepository(database); } return instance; } public boolean socialMediaIdExists(SocialLogin user) throws SQLException { Connection conn = database.getConnection(); PreparedStatement ps = conn.prepareStatement(SOCIAL_MEDIA_ID_EXISTS); ps.setString(1, user.getSocialMediaId()); ps.setString(2, user.getProvider().toString()); ResultSet rs = ps.executeQuery(); rs.next(); return rs.getInt("total") > 0; } public User createNewUser(User user) throws SQLException { logger.debug("Flushing new user to database"); return null; } }
35.382716
126
0.704466
b8e40f3efd90090f2c71294f44eb3662a10c0c2e
4,475
package com.codepath.assignment.mytweets.twitterusertimeline; import android.content.Context; import android.databinding.DataBindingUtil; import android.graphics.Bitmap; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.BitmapImageViewTarget; import com.codepath.assignment.mytweets.R; import com.codepath.assignment.mytweets.databinding.TweetItemLayoutBinding; import com.codepath.assignment.mytweets.data.model.Tweet; import java.util.LinkedList; import java.util.List; /** * Created by saip92 on 9/29/2017. */ public class TwitterFeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private LinkedList<Tweet> mTweets; private Context mContext; TwitterFeedAdapter(Context context, LinkedList<Tweet> tweets) { mTweets = tweets; mContext = context; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(mContext); TweetItemLayoutBinding binding = DataBindingUtil .inflate(inflater, R.layout.tweet_item_layout, parent,false); return new TwitterFeedViewHolder(binding); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((TwitterFeedViewHolder)holder).bind(mTweets.get(position)); } @Override public int getItemCount() { return mTweets.size(); } public void appendTweets(List<Tweet> tweets){ int oldSize = mTweets.size(); mTweets.addAll(tweets); notifyItemRangeChanged(oldSize, mTweets.size()); } public void addAllTweets(List<Tweet> tweets){ if(tweets.size() > 0){ mTweets.clear(); mTweets.addAll(tweets); notifyDataSetChanged(); } } public void clear(){ mTweets.clear(); notifyDataSetChanged(); } public void addAllToFirst(List<Tweet> tweets){ for(int i = tweets.size() - 1; i >=0 ; i--){ addToFirst(tweets.get(i)); } // notifyItemRangeInserted(0,tweets.size()); notifyDataSetChanged(); } public void addToFirst(Tweet tweet){ mTweets.addFirst(tweet); notifyItemInserted(0); } public Tweet getTweet(int position) { return mTweets.get(position); } private class TwitterFeedViewHolder extends RecyclerView.ViewHolder{ private final TweetItemLayoutBinding binding; public TwitterFeedViewHolder(TweetItemLayoutBinding binding) { super(binding.getRoot()); this.binding = binding; } public void bind(Tweet tweet){ if(tweet != null){ Glide.with(mContext) .load(tweet.getUser().getProfileImageUrl().replace("normal","bigger")) .asBitmap() .centerCrop() .into(new BitmapImageViewTarget(binding.ivAvatar){ @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmap = RoundedBitmapDrawableFactory.create(mContext.getResources(),resource); circularBitmap.setCircular(true); binding.ivAvatar.setImageDrawable(circularBitmap); } }); binding.tvUserName.setText(String.format("@%s", tweet.getUser().getScreenName())); binding.tvName.setText(tweet.getUser().getName()); binding.imgBtnLike.setText(String.valueOf(tweet.getFavoriteCount())); binding.imgBtnReTweet.setText(String.valueOf(tweet.getRetweetCount())); binding.tvTweetTime.setText(tweet.getRelativeTimeAgo()); //Log.d("REALTIVEDATE",tweet.getRelativeTimeAgo()); // binding.imgBtnComments.setText(tweet.getUser().getStatusesCount()); binding.tvTweetContent.setText(tweet.getText()); binding.executePendingBindings(); } } } }
33.395522
112
0.634413