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
cfc33cc44379b5bfc5f708629414738c1e9ff279
181
package de.dirkdittmar.offheapCache; import java.util.concurrent.ConcurrentMap; public interface CompactableConcurrentMap<K, V> extends ConcurrentMap<K, V> { void compact(); }
18.1
77
0.790055
b52d6308cb206d2626cc3f1f3d979ae58640dddd
493
package ua.com.fielden.platform.dao.exceptions; /** * Runtime exception that is thrown when attempting to save an entity as new, but it already exists. * * @author TG Team * */ public class EntityAlreadyExists extends EntityCompanionException { private static final long serialVersionUID = 1L; public EntityAlreadyExists(final String msg) { super(msg); } public EntityAlreadyExists(final String msg, final Throwable cause) { super(msg, cause); } }
24.65
100
0.709939
fa9eea62750a6ab0cb31f2265c94f56c4f7797f3
668
package com.dynamicintegration.Dynamic1; import com.thingmagic.ReadExceptionListener; import com.thingmagic.Reader; import com.thingmagic.ReaderException; import java.util.ArrayList; public class D1ReadExceptionListener implements ReadExceptionListener { private final ArrayList<ReaderException> exceptions = new ArrayList<>(); public D1ReadExceptionListener(){} @Override public void tagReadException(Reader reader, ReaderException e) { this.exceptions.add(e); } public ArrayList<ReaderException> getExceptions(){ return this.exceptions; } public void clearExceptions(){ this.exceptions.clear(); } }
24.740741
76
0.744012
72efa5bae06d6e82746e3bd1e222d9d7ce3d1610
4,095
package software.amazon.kendra.datasource.convert.cde; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.kendra.datasource.TestUtils.DATE_INSTANT; import static software.amazon.kendra.datasource.TestUtils.DATE_STRING; import static software.amazon.kendra.datasource.TestUtils.LONG; import static software.amazon.kendra.datasource.TestUtils.STRING; import static software.amazon.kendra.datasource.TestUtils.STRING_LIST; import org.junit.jupiter.api.Test; import software.amazon.kendra.datasource.DocumentAttributeValue; public class DocumentAttributeValueConverterTest { @Test void testToSdkAndToModelDocumentAttributeNull() { assertThat(DocumentAttributeValueConverter.toSdkDocumentAttributeValue(null)).isNull(); assertThat(DocumentAttributeValueConverter.toModelDocumentAttributeValue(null)).isNull(); } @Test void testToSdkAndToModelDocumentAttributeValueStringValue() { DocumentAttributeValue modelDocumentAttributeValue = DocumentAttributeValue.builder() .stringValue(STRING) .build(); software.amazon.awssdk.services.kendra.model.DocumentAttributeValue sdkDocumentAttributeValue = software.amazon.awssdk.services.kendra.model.DocumentAttributeValue.builder() .stringValue(STRING) .build(); assertThat(DocumentAttributeValueConverter.toSdkDocumentAttributeValue(modelDocumentAttributeValue)) .isEqualTo(sdkDocumentAttributeValue); assertThat(DocumentAttributeValueConverter.toModelDocumentAttributeValue(sdkDocumentAttributeValue)) .isEqualTo(modelDocumentAttributeValue); } @Test void testToSdkAndToModelDocumentAttributeValueStringListValue() { software.amazon.kendra.datasource.DocumentAttributeValue modelDocumentAttributeValue = DocumentAttributeValue.builder() .stringListValue(STRING_LIST) .build(); software.amazon.awssdk.services.kendra.model.DocumentAttributeValue sdkDocumentAttributeValue = software.amazon.awssdk.services.kendra.model.DocumentAttributeValue.builder() .stringListValue(STRING_LIST) .build(); assertThat(DocumentAttributeValueConverter.toSdkDocumentAttributeValue(modelDocumentAttributeValue)) .isEqualTo(sdkDocumentAttributeValue); assertThat(DocumentAttributeValueConverter.toModelDocumentAttributeValue(sdkDocumentAttributeValue)) .isEqualTo(modelDocumentAttributeValue); } @Test void testToSdkAndToModelDocumentAttributeValueLongValue() { software.amazon.kendra.datasource.DocumentAttributeValue modelDocumentAttributeValue = DocumentAttributeValue.builder() .longValue(LONG) .build(); software.amazon.awssdk.services.kendra.model.DocumentAttributeValue sdkDocumentAttributeValue = software.amazon.awssdk.services.kendra.model.DocumentAttributeValue.builder() .longValue(LONG) .build(); assertThat(DocumentAttributeValueConverter.toSdkDocumentAttributeValue(modelDocumentAttributeValue)) .isEqualTo(sdkDocumentAttributeValue); assertThat(DocumentAttributeValueConverter.toModelDocumentAttributeValue(sdkDocumentAttributeValue)) .isEqualTo(modelDocumentAttributeValue); } @Test void testToSdkAndToModelDocumentAttributeValueDateValue() { software.amazon.kendra.datasource.DocumentAttributeValue modelDocumentAttributeValue = DocumentAttributeValue.builder() .dateValue(DATE_STRING) .build(); software.amazon.awssdk.services.kendra.model.DocumentAttributeValue sdkDocumentAttributeValue = software.amazon.awssdk.services.kendra.model.DocumentAttributeValue.builder() .dateValue(DATE_INSTANT) .build(); assertThat(DocumentAttributeValueConverter.toSdkDocumentAttributeValue(modelDocumentAttributeValue)) .isEqualTo(sdkDocumentAttributeValue); assertThat(DocumentAttributeValueConverter.toModelDocumentAttributeValue(sdkDocumentAttributeValue)) .isEqualTo(modelDocumentAttributeValue); } }
46.011236
104
0.787302
1c554a862b39d6c35a75b54d6fe494344dbcfa9e
226
package strict.query; public class QueryToken { public String token; public double textRankScore=0; public double posRankScore=0; public double coreRankScore=0; public double totalScore=0; public double bordaScore=0; }
20.545455
31
0.792035
b36890e7fb4e08793d7d85af4b61191644af5067
1,039
package com.fangjc1986.ezmpro.sys.service.impl; import com.fangjc1986.ezmpro.sys.model.AccountLog; import com.fangjc1986.ezmpro.sys.model.User; import com.fangjc1986.support.service.BaseMongoService; import com.fangjc1986.support.util.IPUtils; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; /** * <p> * 账号登录登出日志 服务实现类 * </p> * * @author EricFang * @since 2020-04-10 */ @Service public class AccountLogServiceImpl extends BaseMongoService<AccountLog> { @Override public void setUpdateFields(Update update, AccountLog doc) { } /** * 根据用户和类型保存 * * @param user * @param type */ public void save(User user, Integer type) { AccountLog accountLog = new AccountLog(); accountLog.setUserId(user.getId()); accountLog.setUserName(user.getUserName()); accountLog.setType(type); accountLog.setIp(IPUtils.getRemoteIP(request)); accountLog.setSuccess(1); save(accountLog); } }
24.162791
73
0.694899
b6254bfd5c8d8152a95b38b6f0e1842dcb3253b6
3,475
package dagger.internal.codegen.collect; import dagger.internal.codegen.base.Util; import java.util.AbstractMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Set; public class ImmutableMap<X, Y> extends AbstractMap<X, Y> { private static final ImmutableMap<?, ?> EMPTY = new ImmutableMap<>(Map.of()); private final Map<X, Y> delegate; ImmutableMap(Map<X, Y> delegate) { this.delegate = delegate; } public static <K, V> ImmutableMap<K, V> copyOf(Map<K, V> map) { if (map instanceof ImmutableMap) { return (ImmutableMap<K, V>) map; } return new ImmutableMap<>(map); } public static <X, Y> Builder<X, Y> builder() { return new Builder<>(); } public static class Builder<X, Y> { private final Map<X, Y> delegate = new LinkedHashMap<>(); Map<X, Y> delegate() { return delegate; } public Builder<X, Y> put(X key, Y value) { delegate.put(key, value); return this; } public Builder<X, Y> putAll(Map<? extends X, ? extends Y> map) { map.forEach(this::put); return this; } public ImmutableMap<X, Y> build() { return new ImmutableMap<>(delegate); } } public static <K, V> ImmutableMap<K, V> of() { return (ImmutableMap<K, V>) EMPTY; } public static <K, V> ImmutableMap<K, V> of(K k1, V v1) { return new ImmutableMap<>(Map.of(k1, v1)); } public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) { LinkedHashMap<K, V> result = new LinkedHashMap<>(3); result.put(k1, v1); result.put(k2, v2); return new ImmutableMap<>(result); } public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { LinkedHashMap<K, V> result = new LinkedHashMap<>(5); result.put(k1, v1); result.put(k2, v2); result.put(k3, v3); return new ImmutableMap<>(result); } public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { LinkedHashMap<K, V> result = new LinkedHashMap<>(6); result.put(k1, v1); result.put(k2, v2); result.put(k3, v3); result.put(k4, v4); return new ImmutableMap<>(result); } public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { LinkedHashMap<K, V> result = new LinkedHashMap<>(8); result.put(k1, v1); result.put(k2, v2); result.put(k3, v3); result.put(k4, v4); result.put(k5, v5); return new ImmutableMap<>(result); } @Override public Set<Entry<X, Y>> entrySet() { return delegate.entrySet(); } final Map<X, Y> delegate() { return delegate; } public ImmutableSetMultimap<X, Y> asMultimap() { return new ImmutableSetMultimap<>(Util.transformValues(delegate, Set::of)); } @Override public final boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; ImmutableMap<?, ?> that = (ImmutableMap<?, ?>) o; return delegate.equals(that.delegate); } @Override public ImmutableSet<X> keySet() { return ImmutableSet.copyOf(super.keySet()); } @Override public ImmutableList<Y> values() { return ImmutableList.copyOf(super.values()); } @Override public final int hashCode() { return Objects.hash(delegate); } @Override public final String toString() { return delegate.toString(); } }
25.181159
94
0.621871
388123c451455d15d2e480b80b8352ba89a52698
655
package com.emc.rpsp.fal.wrappers; import com.emc.rpsp.fal.commons.SystemReportSettings; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @Data @AllArgsConstructor @NoArgsConstructor @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class SetSystemReportSettingsParams { @XmlElement(nillable = true) private SystemReportSettings systemReportSettings; private String requestedSmtpServerAddress; }
25.192308
54
0.835115
337c0a96671e3c4d96b11bf570b84711c1f699e4
2,182
/* * @(#)SpecimenPrecessionError.java created 08/10/2002 Mesiano * * Copyright (c) 2002 Luca Lutterotti All Rights Reserved. * * This software is the research result of Luca Lutterotti and it is * provided as it is as confidential and proprietary information. * You shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement you * entered into with the author. * * THE AUTHOR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT. THE AUTHOR SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING * THIS SOFTWARE OR ITS DERIVATIVES. * */ package it.unitn.ing.rista.diffr; import java.awt.*; import it.unitn.ing.rista.awt.*; import javax.swing.*; /** * The SpecimenPrecessionError is a class * * * @version $Revision: 1.3 $, $Date: 2004/08/12 09:36:05 $ * @author Luca Lutterotti * @since JDK1.1 */ public class SpecimenPrecessionError extends XRDcat { public double[] xyz = {0.0, 0.0, 0.0}; public SpecimenPrecessionError(XRDcat aobj, String alabel) { super(aobj, alabel); } public SpecimenPrecessionError(XRDcat aobj) { this(aobj, "Specimen precession model x"); } public SpecimenPrecessionError() { } public double[] getXYZForPrecession(double[] angles, double x) { return xyz; } public JOptionsDialog getOptionsDialog(Frame parent) { JOptionsDialog adialog = new JPrecessionErrorOptionsD(parent, this); return adialog; } public class JPrecessionErrorOptionsD extends JOptionsDialog { public JPrecessionErrorOptionsD(Frame parent, XRDcat obj) { super(parent, obj); principalPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 6, 6)); principalPanel.add(new JLabel("No options for this model")); setTitle("Specimen precession error options panel"); pack(); } public void initParameters() { } public void retrieveParameters() { } } }
25.97619
81
0.72044
c847a53bb969c0b1d028087cf4d5f014a7546f0a
1,117
package com.hopding.merp.android; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Used to validate IP address strings: * <p> * <a href="https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/"> * www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression * </a> */ public class IPAddressValidator { private static Pattern pattern; private static Matcher matcher; private static final String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; /** * Validate ip address with regular expression * @param ip ip address for validation * @return true valid ip address, false invalid ip address */ public static boolean validate(final String ip){ pattern = Pattern.compile(IPADDRESS_PATTERN); matcher = pattern.matcher(ip); return matcher.matches(); } }
31.914286
108
0.602507
dcf5852fa975f46cb025a4e0c62537c83193039c
2,037
package JIn.java.exam06; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; public class MyClient { private Socket socket = null; private BufferedReader br = null; private BufferedWriter bw = null; private BufferedReader keyboard = null; public MyClient() { try { socket = new Socket("localhost", 5000);// 3. 서버에 접속시도 System.out.println("서버 접속 성공~~~"); } catch (UnknownHostException ue) { System.err.println("해당 서버를 찾을 수 없음"); System.exit(0); } catch (IOException e) { System.err.println("서버접속 실패"); System.exit(0); } try { // 4. 얻어진 소켓으로부터 스트림 추출 br = new BufferedReader(new InputStreamReader(socket.getInputStream())); bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); keyboard = new BufferedReader(new InputStreamReader(System.in)); // 키보드로 부터 입력 while (true) { System.out.print("전송할 메세지 : "); String message = keyboard.readLine(); // 클라이언트 입력대기 bw.write(message + "\n"); // 5. 클라이언트가 메시지를 전송 bw.flush(); // 8. 서버가 보내온 메시지를 확인한다. String recieveMessage = br.readLine(); System.out.println("서버에게 받은 메시지 : " + recieveMessage); if (recieveMessage.equals("exit")) { System.out.println("통신을 종료합니다."); break; } } System.out.println("서버와의 연결이 끊어졌습니다."); } catch (IOException e) { e.printStackTrace(); } finally {// 9. 자원들 close() try { if (bw != null) bw.close(); } catch (IOException ioe) { } try { if (br != null) br.close(); } catch (IOException ioe) { } try { if (keyboard != null) keyboard.close(); } catch (IOException ioe) { } try { if (socket != null) socket.close(); } catch (IOException ioe) { } } } public static void main(String[] args) { new MyClient(); } }
24.841463
82
0.614138
d88fe205d72876b46fd4ff89f4d7c1d14c420cfb
2,393
/** * 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.solr.core; import monty.solr.util.MontySolrAbstractTestCase; import monty.solr.util.MontySolrSetup; import org.apache.solr.common.params.SolrParams; import org.apache.solr.handler.AdsConfigHandler; import org.junit.BeforeClass; public class TestExtendedConfig extends MontySolrAbstractTestCase { @BeforeClass public static void beforeClass() throws Exception { makeResourcesVisible(Thread.currentThread().getContextClassLoader(), new String[] { MontySolrSetup.getMontySolrHome() + "/contrib/adsabs/src/test-files/solr/collection1/conf/", MontySolrSetup.getSolrHome() + "/example/solr/collection1/conf" }); System.setProperty("solr.allow.unsafe.resourceloading", "true"); schemaString = MontySolrSetup.getMontySolrHome() + "/contrib/adsabs/src/test-files/solr/collection1/conf/" + "schema-minimal.xml"; configString = MontySolrSetup.getMontySolrHome() + "/contrib/adsabs/src/test-files/solr/collection1/conf/" + "extended-solrconfig.xml"; initCore(configString, schemaString, "./temp"); } public void testExtendedConfig() { AdsConfigHandler handler = (AdsConfigHandler) h.getCore().getRequestHandler("/ads-config"); SolrParams defaults = handler.getParams("defaults"); assertTrue(defaults.get("spellcheck.onlyMorePopular").equals("false")); SolrParams test = handler.getParams("testVal"); assertTrue(test.get("testVal").equals("testValue")); SolrParams arr = handler.getParams("query"); assertTrue(arr.get("0").equals("all")); assertTrue(arr.get("1").equals("false")); } }
39.229508
109
0.745508
59b9ca8fc696863d6e4b6e1bfbd85722990d3d91
2,305
package com.project.convertedCode.globalNamespace.namespaces.Symfony.namespaces.Component.namespaces.Console.namespaces.Formatter.classes; import java.lang.invoke.MethodHandles; import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs; import com.runtimeconverter.runtime.classes.RuntimeClassBase; import com.runtimeconverter.runtime.RuntimeEnv; import com.runtimeconverter.runtime.annotations.ConvertedMethod; import com.runtimeconverter.runtime.reflection.ReflectionClassData; import com.runtimeconverter.runtime.annotations.ConvertedParameter; import com.runtimeconverter.runtime.arrays.ZPair; /* Converted with The Runtime Converter (runtimeconverter.com) vendor/symfony/console/Formatter/OutputFormatterInterface.php */ public interface OutputFormatterInterface { public static final Object CONST_class = "Symfony\\Component\\Console\\Formatter\\OutputFormatterInterface"; @ConvertedMethod @ConvertedParameter(index = 0, name = "decorated") public Object setDecorated(RuntimeEnv env, Object... args); @ConvertedMethod public Object isDecorated(RuntimeEnv env, Object... args); @ConvertedMethod @ConvertedParameter(index = 0, name = "name") @ConvertedParameter( index = 1, name = "style", typeHint = "Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleInterface" ) public Object setStyle(RuntimeEnv env, Object... args); @ConvertedMethod @ConvertedParameter(index = 0, name = "name") public Object hasStyle(RuntimeEnv env, Object... args); @ConvertedMethod @ConvertedParameter(index = 0, name = "name") public Object getStyle(RuntimeEnv env, Object... args); @ConvertedMethod @ConvertedParameter(index = 0, name = "message") public Object format(RuntimeEnv env, Object... args); static final ReflectionClassData runtimeConverterReflectionData = ReflectionClassData.builder() .setName("Symfony\\Component\\Console\\Formatter\\OutputFormatterInterface") .setLookup(OutputFormatterInterface.class, MethodHandles.lookup()) .setLocalProperties() .setFilename("vendor/symfony/console/Formatter/OutputFormatterInterface.php") .get(); }
37.786885
138
0.735792
179b5bf0bf7f85134233b81227ad57100765d5d7
1,308
/** * https://leetcode.com/problems/odd-even-linked-list/ * Author: KKDJoseph * Method: 目标是把奇偶位置的元素分开,一开始想的是用fast和slow双指针,但是想到.next.next会有null的情况 * 所以就只用一个指针往下走,两个指针用来记录odd和even * 取巧的一点是,每次得到了当前的odd和even,你要让temp指针往下走完之后,把odd与他的next断开,因为他的next是even的节点 * 不断开就会成环,两串就会交织在一起 * * Time Complexity: O(n) * Space Complexity: O(1) */ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode oddEvenList(ListNode head) { if(head == null || head.next == null) return head; ListNode answer = new ListNode(-1); ListNode odd = answer; ListNode answer2 = new ListNode(-1); ListNode even = answer2; ListNode temp = head; while(temp != null){ odd.next = temp; odd = odd.next; temp = temp.next; odd.next = null; if(temp != null){ even.next = temp; even = even.next; temp = temp.next; even.next = null; } } odd.next = answer2.next; return answer.next; } }
27.829787
77
0.565749
a948bb4e9d8ff9e85ab702db62d77056847f1f0a
2,258
package seedu.address.model; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import seedu.address.commons.core.index.Index; import seedu.address.model.nusmodule.Grade; import seedu.address.model.nusmodule.ModuleCode; import seedu.address.model.nusmodule.ModuleTask; import seedu.address.model.nusmodule.NusModule; import seedu.address.testutil.TypicalNusModules; class ModuleBookTest { final NusModule cs2030 = TypicalNusModules.CS2030; final ModuleTask task = TypicalNusModules.TYPICAL_MODULE_TASK_1; @Test void addModule_hasModule_deleteModule() { ModuleBook moduleBook = new ModuleBook(); moduleBook.addModule(cs2030); assertTrue(moduleBook.hasModule(cs2030.getModuleCode())); assertFalse(moduleBook.hasModule(new ModuleCode("cs2040"))); moduleBook.deleteModule(cs2030.getModuleCode()); assertFalse(moduleBook.hasModule(cs2030.getModuleCode())); } @Test void getModule() { ModuleBook moduleBook = new ModuleBook(); moduleBook.addModule(cs2030); assertEquals(moduleBook.getModule(cs2030.getModuleCode()), cs2030); } @Test void gradeModule() { ModuleBook moduleBook = new ModuleBook(); moduleBook.addModule(cs2030); moduleBook.gradeModule(cs2030.getModuleCode(), Grade.S); assertEquals(cs2030.getGrade().get(), Grade.S); } @Test void addModuleTask_doneModuleTask() { ModuleBook moduleBook = new ModuleBook(); moduleBook.addModule(cs2030); moduleBook.addModuleTask(task); moduleBook.doneModuleTask(cs2030.getModuleCode(), Index.fromZeroBased(0)); assertDoesNotThrow(() -> {}); } @Test void getSizeOfModuleTaskList() { ModuleBook moduleBook = new ModuleBook(); moduleBook.addModule(cs2030); moduleBook.addModuleTask(task); assertNotEquals(moduleBook.getSizeOfModuleTaskList(cs2030.getModuleCode()), 0); } }
34.738462
87
0.726306
cafbd67c46ba8c6052acf7c3c3708a3fe3da4b19
12,792
/* * 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.artofarc.esb.json; import java.io.OutputStream; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.ArrayDeque; import java.util.Map; import java.util.regex.Pattern; import javax.json.stream.JsonGenerator; import javax.xml.XMLConstants; import javax.xml.bind.DatatypeConverter; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import com.artofarc.util.JsonFactoryHelper; import com.artofarc.util.NamespaceMap; import com.artofarc.util.PrefixHandler; import com.artofarc.util.XSOMHelper; import com.sun.xml.xsom.*; public final class Xml2JsonTransformer { /** * @see https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.7.3.1 */ public static final boolean JSON_OMIT_TZ_FROM_DATE = Boolean.parseBoolean(System.getProperty("esb0.json.omitTZfromDate", "true")); private static final Pattern whitespacePattern = Pattern.compile("\\s+"); private final XSSchemaSet _schemaSet; private final XSComplexType _complexType; private final boolean _includeRoot, _wrapperAsArrayName; private final NamespaceMap _namespaceMap; private final String attributePrefix = "@"; private final String valueWrapper = "value"; public Xml2JsonTransformer(XSSchemaSet schemaSet, String type, boolean includeRoot, boolean wrapperAsArrayName, Map<String, String> prefixMap) { _schemaSet = schemaSet != null ? schemaSet : XSOMHelper.anySchema; if (type != null) { QName _type = QName.valueOf(type); _complexType = schemaSet.getComplexType(_type.getNamespaceURI(), _type.getLocalPart()); } else { _complexType = null; } _includeRoot = includeRoot; _wrapperAsArrayName = wrapperAsArrayName; _namespaceMap = prefixMap != null ? new NamespaceMap(prefixMap) : null; } public ContentHandler createTransformerHandler(Writer writer) { return new TransformerHandler(JsonFactoryHelper.JSON_GENERATOR_FACTORY.createGenerator(writer)); } public ContentHandler createTransformerHandler(OutputStream outputStream) { return new TransformerHandler(JsonFactoryHelper.JSON_GENERATOR_FACTORY.createGenerator(outputStream)); } public ContentHandler createTransformerHandler(OutputStream outputStream, Charset charset) { return new TransformerHandler(JsonFactoryHelper.JSON_GENERATOR_FACTORY.createGenerator(outputStream, charset)); } private final class TransformerHandler extends PrefixHandler { final JsonGenerator jsonGenerator; final StringBuilder _builder = new StringBuilder(128); final ArrayDeque<Integer> ignoreLevel = new ArrayDeque<>(); XSOMHelper xsomHelper; boolean root = true, complex, simpleList; String primitiveType, openKey; int level, anyLevel = -1; TransformerHandler(JsonGenerator jsonGenerator) { this.jsonGenerator = jsonGenerator; } @Override public void startDocument() { jsonGenerator.writeStartObject(); } @Override public void endDocument() { if (_includeRoot) jsonGenerator.writeEnd(); jsonGenerator.close(); } private String getJsonType(String xsiType) throws SAXException { final int i = xsiType.indexOf(':'); final String namespace = getNamespace(i < 0 ? XMLConstants.DEFAULT_NS_PREFIX : xsiType.substring(0, i)); if (namespace == null) { throw new SAXException("Namespace not found for xsi:type " + xsiType); } final XSSchema schema = _schemaSet.getSchema(namespace); if (schema == null) { throw new SAXException("Schema not found for namespace " + namespace); } final XSType type = schema.getType(i < 0 ? xsiType : xsiType.substring(i + 1)); if (type == null) { throw new SAXException("xsi:type could not be resolved " + xsiType); } if (type.isSimpleType()) { final XSSimpleType simpleType = type.asSimpleType(); final XSSimpleType itemType = XSOMHelper.getItemType(simpleType); if (itemType != null) { return XSOMHelper.getJsonType(itemType); } else { return XSOMHelper.getJsonType(simpleType); } } else { throw new SAXException("xsi:type with complexType not supported, yet"); } } @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { _builder.setLength(0); int attsLength = atts.getLength(); if (root) { root = false; xsomHelper = new XSOMHelper(_complexType, _schemaSet.getElementDecl(uri, localName)); if (!_includeRoot) { ++level; return; } complex = true; } else { xsomHelper.matchElement(uri, localName); final String type = atts.getValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type"); if (type != null) { primitiveType = getJsonType(type); --attsLength; } else { primitiveType = null; } if (xsomHelper.isLastElementAny()) { if (anyLevel < 0) { if (!_includeRoot && level == 1) { anyLevel = 0; } else { anyLevel = level; } } } else { complex = xsomHelper.getComplexType() != null; if (primitiveType == null) { final XSSimpleType simpleType = xsomHelper.getSimpleType(); if (simpleType != null) { final XSSimpleType itemType = XSOMHelper.getItemType(simpleType); if (simpleType.isUnion()) { throw new SAXException("xs:union and no xsi:type given"); } else if (simpleList = itemType != null) { primitiveType = XSOMHelper.getJsonType(itemType); } else { primitiveType = XSOMHelper.getJsonType(simpleType); } } } } } String key = localName; if (_namespaceMap != null) { String prefix = _namespaceMap.getPrefix(uri); if (prefix != null && prefix.length() > 0) { key = prefix + '.' + localName; } } if ((anyLevel < 0 || level == anyLevel) && xsomHelper.isEndArray()) { jsonGenerator.writeEnd(); xsomHelper.endArray(); } if (anyLevel < 0 && xsomHelper.isStartArray()) { jsonGenerator.writeStartArray(openKey != null ? openKey : key); openKey = null; } else { if (openKey != null) { jsonGenerator.writeStartObject(openKey); openKey = null; } if (anyLevel >= 0 || !xsomHelper.isMiddleOfArray()) { openKey = key; } } final String nil = atts.getValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil"); if (nil != null && DatatypeConverter.parseBoolean(nil)) { primitiveType = "nil"; --attsLength; } ++level; if (attsLength > 0 || complex && anyLevel < 0) { if (openKey != null) { if (_wrapperAsArrayName && xsomHelper.getWrappedElement() != null) { ignoreLevel.push(level); } else { jsonGenerator.writeStartObject(openKey); openKey = null; } } else { jsonGenerator.writeStartObject(); } for (int i = 0; i < attsLength; ++i) { XSAttributeUse attributeUse = xsomHelper.getAttributeUse(atts.getURI(i), atts.getLocalName(i)); String type = attributeUse != null ? XSOMHelper.getJsonType(attributeUse.getDecl().getType()) : "string"; writeKeyValue(attributePrefix + atts.getLocalName(i), atts.getValue(i), type); } if (primitiveType != null) { openKey = valueWrapper; } } } @Override public void endElement(String uri, String localName, String qName) { if (openKey != null) { if (primitiveType == null) { primitiveType = "string"; } if (openKey != valueWrapper) { complex = false; } } if (primitiveType != null) { if (simpleList) { if (openKey != null) { jsonGenerator.writeStartArray(openKey); } else { jsonGenerator.writeStartArray(); } if (_builder.length() > 0) { for (String value : whitespacePattern.split(_builder)) { writeValue(value, primitiveType); } } jsonGenerator.writeEnd(); } else { if (openKey != null) { writeKeyValue(openKey, _builder.toString(), primitiveType); } else { writeValue(_builder.toString(), primitiveType); } } } else { if (anyLevel < 0) { if (xsomHelper.isInArray()) { jsonGenerator.writeEnd(); xsomHelper.endArray(); } } if (_builder.length() > 0) { if (anyLevel < 0) { final XSComplexType currentComplexType = xsomHelper.getCurrentComplexType(); if (currentComplexType != null && currentComplexType.isMixed()) { jsonGenerator.writeStartArray(valueWrapper); jsonGenerator.write(_builder.toString()); jsonGenerator.writeEnd(); } } else { if (_builder.toString().trim().length() > 0) { jsonGenerator.write(valueWrapper, _builder.toString()); } } } if (anyLevel < 0 || level == anyLevel) { xsomHelper.endComplex(); } } if (complex || primitiveType == null) { final Integer ignore = ignoreLevel.peek(); if (ignore != null && level == ignore) { ignoreLevel.pop(); } else { jsonGenerator.writeEnd(); } } if (anyLevel == level--) { anyLevel = -1; xsomHelper.endAny(); } primitiveType = null; _builder.setLength(0); openKey = null; } @Override public void characters(char[] ch, int start, int length) { _builder.append(ch, start, length); } private void writeKeyValue(String key, String s, String primitiveType) { switch (primitiveType) { case "int": // is faster jsonGenerator.write(key, DatatypeConverter.parseInt(s)); break; case "long": jsonGenerator.write(key, Long.parseLong(s)); break; case "integer": jsonGenerator.write(key, new BigInteger(s)); break; case "decimal": jsonGenerator.write(key, new BigDecimal(s)); break; case "float": case "double": // covers NaN and INF, still writing will fail jsonGenerator.write(key, DatatypeConverter.parseDouble(s)); break; case "boolean": // covers '1' and '0' jsonGenerator.write(key, DatatypeConverter.parseBoolean(s)); break; case "nil": jsonGenerator.writeNull(key); break; case "date": jsonGenerator.write(key, omitTZfromDate(s)); break; default: jsonGenerator.write(key, s); break; } } private void writeValue(String s, String primitiveType) { switch (primitiveType) { case "int": // is faster jsonGenerator.write(DatatypeConverter.parseInt(s)); break; case "long": jsonGenerator.write(Long.parseLong(s)); break; case "integer": jsonGenerator.write(new BigInteger(s)); break; case "decimal": jsonGenerator.write(new BigDecimal(s)); break; case "float": case "double": // covers NaN and INF, still writing will fail jsonGenerator.write(DatatypeConverter.parseDouble(s)); break; case "boolean": // covers '1' and '0' jsonGenerator.write(DatatypeConverter.parseBoolean(s)); break; case "nil": jsonGenerator.writeNull(); break; case "date": jsonGenerator.write(omitTZfromDate(s)); break; default: jsonGenerator.write(s); break; } } } public static String omitTZfromDate(String date) { if (JSON_OMIT_TZ_FROM_DATE) { if (date.charAt(0) == '-') { throw new IllegalArgumentException("year must not be negative " + date); } date = date.substring(0, 10); } return date; } public static void omitTZfromDate(XMLGregorianCalendar date) { if (JSON_OMIT_TZ_FROM_DATE) { date.setTimezone(DatatypeConstants.FIELD_UNDEFINED); } } }
31.663366
146
0.659162
621072cb596cfcf43113be749007f40a3a534bb5
973
package fi.nls.oskari.control.statistics.plugins; import fi.nls.oskari.annotation.Oskari; import fi.nls.oskari.worker.ScheduledJob; import java.util.Map; /** * Triggers update on plugins that support it */ @Oskari("StatisticsDatasources") public class ScheduledStatisticsDatasourceUpdate extends ScheduledJob { public void execute(Map<String, Object> params) { StatisticalDatasourcePluginManager pluginManager = StatisticalDatasourcePluginManager.getInstance(); for(StatisticalDatasourcePlugin plugin : pluginManager.getPlugins().values()) { // triggers update on plugins that support it plugin.getIndicatorSet(null); } } @Override public String getCronLine() { String line = super.getCronLine(); if(line != null) { // use property if specified return line; } // default if not specified (at 4 AM each night) return "0 0 4 * * ?"; } }
30.40625
108
0.672148
67175af90756e926b76eb909e4076f0b4ee98b82
976
package com.koushikdutta.async; import com.koushikdutta.async.a.b; public class F implements b { private StringBuilder a = new StringBuilder(); private G b; static { if (!F.class.desiredAssertionStatus()); for (boolean bool = true; ; bool = false) { c = bool; return; } } public final void a(G paramG) { this.b = paramG; } public final void a(y paramy, v paramv) { while (true) { int i; if (paramv.c() > 0) { i = paramv.h(); if (i == 10) { if ((!c) && (this.b == null)) throw new AssertionError(); this.b.a(this.a.toString()); this.a = new StringBuilder(); } } else { return; } this.a.append((char)i); } } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.koushikdutta.async.F * JD-Core Version: 0.6.0 */
18.074074
83
0.518443
94e232c0934acd076be1c9d070ccb5b0c0b20b8d
3,263
package net.gdface.facelog; import static com.google.common.base.Preconditions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; /** * 令牌状态上下文 * @author guyadong * */ public class TokenContext { public static final Logger logger = LoggerFactory.getLogger(TokenContext.class); static final ThreadLocal<TokenContext> TOKEN_CONTEXT = new ThreadLocal<TokenContext>(){ @Override protected TokenContext initialValue() { return new TokenContext(); }}; /** 是否记录详细异常信息 */ private static boolean errorDetail = false; private Token token; private TokenOp tokenOp; private boolean ok; private ServiceSecurityException error; private String methodName; private TokenContext() { reset(); } void reset(){ token = new Token(); tokenOp = TokenOp.UNINITIALIZED; ok = true; error = null; } /** 返回当前令牌 */ public Token getToken() { return token; } /** * 设置当前令牌 * @param token 不可为{@code null} * @return */ public TokenContext setToken(Token token) { this.token = checkNotNull(token); return this; } /** 返回当前令牌操作类型 */ public TokenOp getTokenOp() { return tokenOp; } /** * 设置当前令牌操作类型 * @param tokenOp 不可为{@code null} * @return */ public TokenContext setTokenOp(TokenOp tokenOp) { this.tokenOp = checkNotNull(tokenOp); return this; } /** 返回当前令牌操作{@link #tokenOp}执行状态,{@code true}表示正常 */ public boolean isOk() { return ok; } /** * 返回当前异常 * @return */ public ServiceSecurityException getError() { return error; } /** * 设置当前令牌操作{@link #tokenOp}异常,并将{@link #isOk()}置为{@code false} * @param error * @return */ public TokenContext setError(ServiceSecurityException error) { this.error = checkNotNull(error); this.ok = false; return this; } /** * 返回当前服务方法名 * @return */ public String getMethodName() { return methodName; } /** * 设置当前方法名 * @param methodName * @return * @throws IllegalStateException {@link #methodName}字段已经初始化 * @throws IllegalArgumentException {@code methodName}为空或{@code null} */ public TokenContext setMethodName(String methodName) { checkState(null == this.methodName,"methodName be initialized already"); checkArgument(!Strings.isNullOrEmpty(methodName),"methodName is null or empty"); this.methodName = methodName; return this; } /** * 上下文对象生命期结束时调用<br> * 记录令牌操作日志 */ public void contextDone() { if(TokenOp.UNINITIALIZED != tokenOp){ if(this.ok){ logger.info("PORT:{} OP:{}: FROM:{} BY:{}: OK", methodName, tokenOp.name(), ServiceUtil.clientAddressAsString(), getToken().owner()); }else{ logger.error("PORT:{} OP:{}: FROM:{} BY:{}: MESSAGE:{}", methodName, tokenOp.name(), ServiceUtil.clientAddressAsString(), getToken().owner(), error.getMessage()); if(errorDetail){ logger.error(error.getMessage(),error); } } } // 释放TLS变量 TOKEN_CONTEXT.remove(); } /** * 返回当前线程拥有的{@link TokenContext}对象 * @return */ public static TokenContext getCurrentTokenContext(){ return TOKEN_CONTEXT.get(); } public static boolean isErrorDetail() { return errorDetail; } public static void setErrorDetail(boolean errorDetail) { TokenContext.errorDetail = errorDetail; } }
22.349315
88
0.676984
5517a121381a97431158e39a234925d184cd30f2
1,137
package uk.me.richardcook.sinatra.generator.dao; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import uk.me.richardcook.sinatra.generator.model.ForOther; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; @Repository public class ForOtherDaoImpl implements ForOtherDao { @PersistenceContext private EntityManager entityManager; public List<ForOther> findAll() { return entityManager.createQuery( "SELECT e FROM ForOther e" ) .getResultList(); } public ForOther find( int id ) { return entityManager.find( ForOther.class, id ); } @Transactional public void save( ForOther forOther ) { entityManager.persist( forOther ); } @Transactional public void update( ForOther forOther ) { entityManager.merge( forOther ); } public List<ForOther> search( String query ) { return entityManager.createQuery( "SELECT e FROM ForOther e WHERE e.description LIKE :query ORDER by e.description" ) .setParameter( "query", "%" + query + "%" ) .getResultList(); } }
26.44186
119
0.747581
0fc02bb2adfa9c03348bfe9c3aedccb33e86c90a
9,944
/* * Copyright 2016-2018 Michal Harish, michal.harish@gmail.com * * 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 io.amient.affinity.core.storage; import com.typesafe.config.Config; import io.amient.affinity.core.util.TimeRange; import java.io.Closeable; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.Future; /** * LogStorage represents a partitioned key-value stream of data * It is used by State, GatewayStream, Repartitioner and a CompactRDD. * * @param <POS> Coordinate type that describes a position in the log stream */ public interface LogStorage<POS extends Comparable<POS>> extends Closeable { LogStorageConf StorageConf = new LogStorageConf() { @Override public LogStorageConf apply(Config config) { return new LogStorageConf().apply(config); } }; static LogStorage newInstance(Config config) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { return newInstance(LogStorage.StorageConf.apply(config)); } static LogStorage newInstanceEnsureExists(LogStorageConf conf) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { LogStorage instance = newInstance(conf); instance.ensureExists(); return instance; } static LogStorage newInstance(LogStorageConf conf) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<? extends LogStorage> cls = conf.Class.apply(); return cls.getConstructor(LogStorageConf.class).newInstance(conf); } /** * * @param checkpointFile - file to be used for checkpointing or null to disable checkpointing * @return Log instance that */ default Log<POS> open(Path checkpointFile) { return new Log<>(this, checkpointFile); } /** * * @return statistics about the underlying log in a human readable format, whatever is available */ String getStats(); /** * This is a general concept of topic for all storage types * @return name of this topic or channel this log is identified in the concrete implementation */ String getTopic(); /** * get number of partitions of the underlying physical log * @return number of partitions */ int getNumPartitions(); /** * resume all partitions and continue from last checkpoint if within the given time range. * the lower bound position of each partition will be the first position which appears on the time range.start or later. * the upper bound position of each partition will be the last position before the time range.end OR unbounded * @param range time range */ void resume(TimeRange range); /** * reset one of the assigned partitions to the given time range. * the lower bound position will be the first position which appears on the time range.start or later. * the upper bound position will be the last position before the time range.end OR maximum available position * @param partition partition number * @param range time range */ void reset(int partition, TimeRange range); /** * reset one of the assigned partitions to the new startPosition. * this reset call MUST als o set the upper bound position to the latest position available in the * underlying physical log, i.e. the resulting offset range should be everything from the startPosition until * the end of the log. * * @param partition partition number [0 - (numPartitions-1)] * @param startPosition position to seek or null if resetting to the beginning of the log * @return the latest position available in the underlying stream or null if nothing is available */ POS reset(int partition, POS startPosition); /** * get key subject for the schema registry * @return subject name of the log keys */ String keySubject(); /** * get value subject for the schema registry * @return subject name of the log values */ String valueSubject(); void ensureExists(); /** * ensure confiugration of the underlying physical log. This call may be called concurrently * by multiple instances so must be at minimum idempotent. * * @param ttlMs maximum time-to-live in milliseconds of each Record, e.g. record's timestamp + ttlMs is the time when the record expires * @param numPartitions - expected number of partitions of the underlying physical log * @param readonly - whether the log is only for reading, e.g. it is an externally produced topic */ void ensureCorrectConfiguration(long ttlMs, int numPartitions, boolean readonly); /** * fetch a record batch from the underlying stream. this method should block * if there are no more records available and the unbounded paramtere is set to true. * * @param unbounded if false the fetch will return null when the limit set * by the reset() method is reached. * if true the fetch will block when no more records are available * even if the upper limit set by reset is reached * * @return iterator of records which may be empty, or null if the maximum offset was reached or cancel() was called * * @throws InterruptedException if the underlying blocking operation is interrupted */ Iterator<LogEntry<POS>> fetch(boolean unbounded) throws InterruptedException; /** * Cancel any ongoing blocking operation, whether fetch or iterator.hasNext etc. */ void cancel(); /** * Commit all positions that were advanced by one of the iterators or the underlying fetch() * The implementation may be be asynchronous if it can guarantee that the records which * will have been consumed after this method was called and before the commit completed * were not included in the commit. * * The implementation must ensure that the order of commit is preserved, i.e. a successful * completion of the future returned by the last call to commit means all previous commits * also succeeded. * * @return Future with timestamp of the commit completion */ Future<Long> commit(); /** * Append a record to the end of the log * @param record record to append to the log * @return future with the new log position checkpoint */ Future<POS> append(Record<byte[], byte[]> record); /** * Append a tombstone to the end of the log for the given record key * @param key which will be marked as deleted * //TODO delete should also take a custom timestamp * @return future with the new log position checkpoint */ Future<POS> delete(byte[] key); /** * Flush all writes that were created by append() or delete(). * This should block until all calls to append() or delete() have completed successfully or * throw exception otherwise. * */ void flush(); /** * Iterator which is bounded by the previous reset() command * @return iterator of log entries */ default Iterator<LogEntry<POS>> boundedIterator() { return iterator(false); } /** * Iterator which is unbounded by the upper bounds given in the reset() command * @return iterator of log entries */ default Iterator<LogEntry<POS>> unboundedIterator() { return iterator(true); } /** * General Iterator Implementation * @param unbounded whether the iterator is unbounded or not * @return iterator of log entries */ default Iterator<LogEntry<POS>> iterator(boolean unbounded) { return new Iterator<LogEntry<POS>>() { private LogEntry<POS> record = null; private Iterator<LogEntry<POS>> i = null; @Override public boolean hasNext() { if (record == null) { while (i == null || !i.hasNext()) { try { i = fetch(unbounded); if (i == null) return false; } catch (InterruptedException e) { throw new RuntimeException(e); } } record = i.next(); } return true; } @Override public LogEntry<POS> next() { if (!hasNext()) { throw new NoSuchElementException(); } else { LogEntry<POS> result = record; record = null; return result; } } }; } }
36.558824
140
0.653761
a30881d2d67081083624975d8950ef30358c9ce2
437
package shows; import java.util.LinkedList; public class ShowList extends LinkedList<Show> { public boolean contains (Show show) { for (Show testShow : this) { if (testShow.getURL().equals(show.getURL())) { return true; } } return false; } public void print() { int counter = 0; for (Show currentShow : this) { counter = counter + 1; System.out.println(counter + ": " + currentShow.toString()); } } }
19
63
0.645309
1e31e53428f2517a7d91e89d74d31f0156c20a4e
68,119
package ij.plugin; import ij.*; import ij.process.*; import ij.gui.*; import ij.io.*; import ij.plugin.Animator; import java.awt.*; import java.awt.image.*; import java.io.*; import java.util.*; import javax.imageio.ImageIO; /** <pre> * ImageJ Plugin for reading an AVI file into an image stack * (one slice per video frame) * * * Restrictions and Notes: * - Only few formats supported: * - uncompressed 8 bit with palette (=LUT) * - uncompressed 8 & 16 bit grayscale * - uncompressed 24 & 32 bit RGB (alpha channel ignored) * - uncompressed 32 bit AYUV (alpha channel ignored) * - various YUV 4:2:2 and 4:2:0 compressed formats (i.e., formats with * full luminance resolution, but reduced chroma resolution * - png or jpeg-encoded individual frames. * Note that most MJPG (motion-JPEG) formats are not read correctly. * - Does not read avi formats with more than one frame per chunk * - Palette changes during the video not supported * - Out-of-sequence frames (sequence given by index) not supported * - Different frame sizes in one file (rcFrame) not supported * - Conversion of (A)YUV formats to grayscale is non-standard: * All 255 levels are kept as in the input (i.e. the full dynamic * range of data from a frame grabber is preserved). * For standard behavior, use "Brightness&Contrast", Press "Set", * enter "Min." 16, "Max." 235, and press "Apply". * - Restrictions for AVIs with blank frames: * Currently only supported with AVI-2 type index. * Blank frames are ignored. * Selection of start and end frames is inconsistent between normal and * virtual stacks. * Timing in slice info is incorrect unless read as virtual stack. * - Note: As a last frame, one can enter '0' (= last frame), * '-1' (last frame -1), etc. * * Version History: * 2008-04-29 * based on a plugin by Daniel Marsh and Wayne Rasband; * modifications by Michael Schmid * - Support for several other formats added, especially some YUV * (also named YCbCr) formats * - Uneven chunk sizes fixed * - Negative biHeight fixed * - Audio or second video stream don't cause a problem * - Can read part of a file (specify start & end frame numbers) * - Can convert YUV and RGB to grayscale (does not convert 8-bit with palette) * - Can flip vertically * - Can create a virtual stack * - Added slice label: time of the frame in the movie * - Added a public method 'getStack' that does not create an image window * - More compact code, especially for reading the header (rewritten) * - In the code, bitmapinfo items have their canonical names. * 2008-06-08 * - Support for png and jpeg/mjpg encoded files added * - Retrieves animation speed from image frame rate * - Exception handling without multiple error messages * 2008-07-03 * - Support for 16bit AVIs coded by MIL (Matrox Imaging Library) * 2009-03-06 * - Jesper Soendergaard Pedersen added support for extended (large) AVI files, * also known as 'AVI 2.0' or 'OpenDML 1.02 AVI file format extension' * For Virtual stacks, it reads the 'AVI 2.0' index (indx and ix00 tags). * This results in a dramatic speed increase in loading of virtual stacks. * If indx and ix00 are not found or bIndexType is unsupported, as well as for * non-virtual stacks it finds the frames 'the old way', by scanning the whole file. * - Fixes a bug where it read too many frames. * This version was published as external plugin. * 2011-12-03 * - Minor updates & cleanup for integration into ImageJ again. * - Multithread-compliant. * 2011-12-10 * - Based on a plugin by Jesper Soendergaard Pedersen, also reads the 'idx1' index of * AVI 1 files, speeding up initial reading of virtual stacks also for smaller files. * - When the first frame to read is > 1, uses the index to quickly skip the initial frames. * - Creates a unique window name. * - Opens MJPG files also if they do not contain Huffman tables * 2012-02-01 * - added support for YV12, I420, NV12, NV21 (planar formats with 2x2 U and V subsampling) * 2012-12-04 * - can read AVI-2 files with blank frames into a virtual stack * 2013-10-29 * - can read MJPG files where the frames don't have the same pixel number as the overall video * 2015-09-28 * - reads most ImageJ AVI1 files with size>4 GB (incorrectly written by ImageJ versions before 1.50b) * 2017-04-21 * - bugfix: file was not closed in case of dialog cancelled or some IO errors. * - Tries to recover data from truncated files. * * * The AVI format looks like this: * RIFF AVI RIFF HEADER, AVI CHUNK * | LIST hdrl MAIN AVI HEADER * | | avih AVI HEADER * | | LIST strl STREAM LIST(s) (One per stream) * | | | strh STREAM HEADER (Required after above; fourcc type is 'vids' for video stream) * | | | strf STREAM FORMAT (for video: BitMapInfo; may also contain palette) * | | | strd OPTIONAL -- STREAM DATA (ignored in this plugin) * | | | strn OPTIONAL -- STREAM NAME (ignored in this plugin) * | | | indx OPTIONAL -- MAIN 'AVI 2.0' INDEX * | LIST movi MOVIE DATA * | | ix00 partial video index of 'AVI 2.0', usually missing in AVI 1 (ix01 would be for audio) * | | [rec] RECORD DATA (one record per frame for interleaved video; optional, unsupported in this plugin) * | | |-dataSubchunks RAW DATA: '??wb' for audio, '??db' and '??dc' for uncompressed and * | | compressed video, respectively. "??" denotes stream number, usually "00" or "01" * | idx1 AVI 1 INDEX ('old-style'); may be missing in very old formats * RIFF AVIX 'AVI 2.0' only: further chunks * | LIST movi more movie data, as above, usually with ix00 index * Any number of further chunks (RIFF tags) may follow * * Items ('chunks') with one fourcc (four-character code such as 'strh') start with two 4-byte words: * the fourcc and the size of the data area. * Items with two fourcc (e.g. 'LIST hdrl') have three 4-byte words: the first fourcc, the size and the * second fourcc. Note that the size includes the 4 bytes needed for the second fourcc. * * Chunks with fourcc 'JUNK' can appear anywhere and should be ignored. * * </pre> */ public class AVI_Reader extends VirtualStack implements PlugIn { //four-character codes for avi chunk types //NOTE: byte sequence is reversed - ints in Intel (little endian) byte order! private final static int FOURCC_RIFF = 0x46464952; //'RIFF' private final static int FOURCC_AVI = 0x20495641; //'AVI ' private final static int FOURCC_AVIX = 0x58495641; //'AVIX' // extended AVI private final static int FOURCC_ix00 = 0x30307869; //'ix00' // index within private final static int FOURCC_indx = 0x78646e69; //'indx' // main index private final static int FOURCC_idx1 = 0x31786469; //'idx1' // index of single 'movi' block private final static int FOURCC_LIST = 0x5453494c; //'LIST' private final static int FOURCC_hdrl = 0x6c726468; //'hdrl' private final static int FOURCC_avih = 0x68697661; //'avih' private final static int FOURCC_strl = 0x6c727473; //'strl' private final static int FOURCC_strh = 0x68727473; //'strh' private final static int FOURCC_strf = 0x66727473; //'strf' private final static int FOURCC_movi = 0x69766f6d; //'movi' private final static int FOURCC_rec = 0x20636572; //'rec ' private final static int FOURCC_JUNK = 0x4b4e554a; //'JUNK' private final static int FOURCC_vids = 0x73646976; //'vids' private final static int FOURCC_00db = 0x62643030; //'00db' private final static int FOURCC_00dc = 0x63643030; //'00dc' //four-character codes for supported compression formats; see fourcc.org private final static int NO_COMPRESSION = 0; //uncompressed, also 'RGB ', 'RAW ' private final static int NO_COMPRESSION_RGB= 0x20424752; //'RGB ' -a name for uncompressed private final static int NO_COMPRESSION_RAW= 0x20574152; //'RAW ' -a name for uncompressed private final static int NO_COMPRESSION_Y800=0x30303859; //'Y800' -a name for 8-bit grayscale private final static int NO_COMPRESSION_Y8 = 0x20203859; //'Y8 ' -another name for Y800 private final static int NO_COMPRESSION_GREY=0x59455247; //'GREY' -another name for Y800 private final static int NO_COMPRESSION_Y16= 0x20363159; //'Y16 ' -a name for 16-bit uncompressed grayscale private final static int NO_COMPRESSION_MIL= 0x204c494d; //'MIL ' - Matrox Imaging Library private final static int AYUV_COMPRESSION = 0x56555941; //'AYUV' -uncompressed, but alpha, Y, U, V bytes private final static int UYVY_COMPRESSION = 0x59565955; //'UYVY' - 4:2:2 with byte order u y0 v y1 private final static int Y422_COMPRESSION = 0x564E5955; //'Y422' -another name for of UYVY private final static int UYNV_COMPRESSION = 0x32323459; //'UYNV' -another name for of UYVY private final static int CYUV_COMPRESSION = 0x76757963; //'cyuv' -as UYVY but not top-down private final static int V422_COMPRESSION = 0x32323456; //'V422' -as UYVY but not top-down private final static int YUY2_COMPRESSION = 0x32595559; //'YUY2' - 4:2:2 with byte order y0 u y1 v private final static int YUNV_COMPRESSION = 0x564E5559; //'YUNV' -another name for YUY2 private final static int YUYV_COMPRESSION = 0x56595559; //'YUYV' -another name for YUY2 private final static int YVYU_COMPRESSION = 0x55595659; //'YVYU' - 4:2:2 with byte order y0 u y1 v private final static int I420_COMPRESSION = 0x30323449; //'I420' - y plane followed by 2x2 subsampled U and V private final static int IYUV_COMPRESSION = 0x56555949; //'IYUV' - another name for I420 private final static int YV12_COMPRESSION = 0x32315659; //'YV12' - y plane followed by 2x2 subsampled V and U private final static int NV12_COMPRESSION = 0x3231564E; //'NV12' - y plane followed by 2x2 subsampled interleaved U, V private final static int NV21_COMPRESSION = 0x3132564E; //'NV21' - y plane followed by 2x2 subsampled interleaved V, U private final static int JPEG_COMPRESSION = 0x6765706a; //'jpeg' JPEG compression of individual frames private final static int JPEG_COMPRESSION2 = 0x4745504a; //'JPEG' JPEG compression of individual frames private final static int JPEG_COMPRESSION3 = 0x04; //BI_JPEG: JPEG compression of individual frames private final static int MJPG_COMPRESSION = 0x47504a4d; //'MJPG' Motion JPEG, also reads compression of individual frames private final static int PNG_COMPRESSION = 0x20676e70; //'png ' PNG compression of individual frames private final static int PNG_COMPRESSION2 = 0x20474e50; //'PNG ' PNG compression of individual frames private final static int PNG_COMPRESSION3 = 0x05; //BI_PNG PNG compression of individual frames private final static int BITMASK24 = 0x10000; //for 24-bit (in contrast to 8, 16,... not a bitmask) private final static long SIZE_MASK = 0xffffffffL; //for conversion of sizes from unsigned int to long private final static long FOUR_GB = 0x100000000L; //2^32; above this size of data AVI 1 has a problem for sure // flags from AVI chunk header private final static int AVIF_HASINDEX = 0x00000010; // Index at end of file? private final static int AVIF_MUSTUSEINDEX = 0x00000020; // ignored by this plugin private final static int AVIF_ISINTERLEAVED= 0x00000100; // ignored by this plugin // constants used to read 'AVI 2' index chunks (others than those defined here are not supported) private final static byte AVI_INDEX_OF_CHUNKS=0x01; //index of frames private final static byte AVI_INDEX_OF_INDEXES=0x00; //main indx pointing to ix00 etc subindices //static versions of dialog parameters that will be remembered private static boolean staticConvertToGray; private static boolean staticFlipVertical; private static boolean staticIsVirtual = true; //dialog parameters private int firstFrame = 1; //the first frame to read private int lastFrame = 0; //the last frame to read; 0 means 'read all' private boolean convertToGray; //whether to convert color video to grayscale private boolean flipVertical; //whether to flip image vertical private boolean isVirtual; //whether to open as virtual stack //the input file private RandomAccessFile raFile; private String raFilePath; private boolean headerOK = false; //whether header has been read //more avi file properties etc private int streamNumber; //number of the (first) video stream private int type0xdb, type0xdc; //video stream chunks must have one of these two types (e.g. '00db' for straem 0) private long fileSize; //file size private long aviSize; //size of 'AVI' chunk private long headerPositionEnd; //'movi' will start somewhere here private long indexPosition; //position of the main index (indx) private long indexPositionEnd; //indx seek end private long moviPosition; //position of 'movi' list private int paddingGranularity = 2; //tags start at even address private int frameNumber = 1; //frame currently read; global because distributed over 1st AVi and further RIFF AVIX chunks private int lastFrameToRead = Integer.MAX_VALUE; private int totalFramesFromIndex;//number of frames from 'AVI 2.0' indices private boolean indexForCountingOnly;//don't read the index, only count int totalFramesFromIndex how many entries private boolean isOversizedAvi1; //AVI-1 file > 4GB //derived from BitMapInfo private int dataCompression; //data compression type used private boolean isPlanarFormat; //I420 & YV12 formats: y frame, then u,v frames private int scanLineSize; private boolean dataTopDown; //whether data start at top of image private ColorModel cm; private boolean variableLength; //compressed (PNG, JPEG) frames have variable length //for conversion to ImageJ stack private Vector<long[]> frameInfos; //for virtual stack: long[] with frame pos&size in file, time(usec) private ImageStack stack; private ImagePlus imp; //for debug messages and error handling private boolean verbose = IJ.debugMode; private long startTime; private boolean aborting; private boolean displayDialog = true; private String errorText; //error occurred during makeStack, or null //From AVI Header Chunk private int dwMicroSecPerFrame; private int dwMaxBytesPerSec; private int dwReserved1; private int dwFlags; private int dwTotalFrames; //AVI 2.0: will be replaced by number of frames from index private int dwInitialFrames; private int dwStreams; private int dwSuggestedBufferSize; private int dwWidth; private int dwHeight; //From Stream Header Chunk private int fccStreamHandler; private int dwStreamFlags; private int dwPriorityLanguage; //actually 2 16-bit words: wPriority and wLanguage private int dwStreamInitialFrames; private int dwStreamScale; private int dwStreamRate; private int dwStreamStart; private int dwStreamLength; private int dwStreamSuggestedBufferSize; private int dwStreamQuality; private int dwStreamSampleSize; //From Stream Format Chunk: BITMAPINFO contents (40 bytes) private int biSize; // size of this header in bytes (40) private int biWidth; private int biHeight; private short biPlanes; // no. of color planes: for the formats decoded; here always 1 private short biBitCount; // Bits per Pixel private int biCompression; private int biSizeImage; // size of image in bytes (may be 0: if so, calculate) private int biXPelsPerMeter; // horizontal resolution, pixels/meter (may be 0) private int biYPelsPerMeter; // vertical resolution, pixels/meter (may be 0) private int biClrUsed; // no. of colors in palette (if 0, calculate) private int biClrImportant; // no. of important colors (appear first in palette) (0 means all are important) /** The plugin is invoked by ImageJ using this method. * @param arg String 'arg' may be used to select the path. If it is an empty string, * a file open dialog is shown, and the resulting ImagePlus is displayed thereafter. * The ImagePlus is not displayed only if 'arg' is a non-empty String; it can be * retrieved with getImagePlus(). */ public void run (String arg) { String options = IJ.isMacro()?Macro.getOptions():null; if (options!=null && options.contains("select=") && !options.contains("open=")) Macro.setOptions(options.replaceAll("select=", "open=")); OpenDialog od = new OpenDialog("Open AVI File", arg); String fileName = od.getFileName(); if (fileName == null) return; String fileDir = od.getDirectory(); String path = fileDir + fileName; try { openAndReadHeader(path); //open and read header } catch (Exception e) { error(exceptionMessage(e)); return; } finally { closeFile(raFile); } if (displayDialog && !showDialog(fileName)) //ask for parameters return; errorText = null; ImageStack stack = makeStack(path, firstFrame, lastFrame, isVirtual, convertToGray, flipVertical); //read data if (aborting) return; //error message has been shown already if (stack==null || stack.getSize() == 0 || stack.getProcessor(1)==null) { //read nothing? if (errorText != null) error(errorText); else { String rangeText = ""; if (firstFrame > 1 || (lastFrame != 0 && lastFrame != dwTotalFrames)) rangeText = "\nin Range "+firstFrame+ (lastFrame>0 ? " - "+lastFrame : " - end"); error("Error: No Frames Found"+rangeText); } return; } else if (errorText != null) IJ.showMessage("AVI Reader", errorText); //show the error, e.g. we may have an incomplete stack imp = new ImagePlus(WindowManager.makeUniqueName(fileName), stack); if (imp.getBitDepth()==16) imp.getProcessor().resetMinAndMax(); setFramesPerSecond(imp); FileInfo fi = new FileInfo(); fi.fileName = fileName; fi.directory = fileDir; imp.setFileInfo(fi); if (arg.equals("")) imp.show(); IJ.showTime(imp, startTime, "Read AVI in ", stack.getSize()); } /** Returns the ImagePlus opened by run(). */ public ImagePlus getImagePlus() { return imp; } /** Opens an AVI file as a virtual stack. The ImagePlus is not displayed. */ public static ImagePlus openVirtual(String path) { return open(path, true); } /** Opens an AVI file as a stack in memory or a virtual stack. The ImagePlus is not displayed. */ public static ImagePlus open(String path, boolean virtual) { AVI_Reader reader = new AVI_Reader(); ImageStack stack = reader.makeStack (path, 1, 0, virtual, false, false); if (stack!=null) return new ImagePlus((new File(path)).getName(), stack); else return null; } /** Create an ImageStack from an avi file with given path. * @param path Directoy+filename of the avi file * @param firstFrame Number of first frame to read (first frame of the file is 1) * @param lastFrame Number of last frame to read or 0 for reading all, -1 for all but last... * @param isVirtual Whether to return a virtual stack * @param convertToGray Whether to convert color images to grayscale * @return Returns the stack (may be incomplete on error); null on failure. * The stack returned may be non-null, but have a length of zero if no suitable frames were found. * Use <code>getErrorText</code> to determine whether there has been an error reading the file. * For virtual stacks, not that I/O errors may also occur later, when reading the frames. */ public ImageStack makeStack (String path, int firstFrame, int lastFrame, boolean isVirtual, boolean convertToGray, boolean flipVertical) { this.firstFrame = firstFrame; this.lastFrame = lastFrame; this.isVirtual = isVirtual; this.convertToGray = convertToGray; this.flipVertical = flipVertical; IJ.showProgress(.001); try { readAVI(path); } catch (OutOfMemoryError e) { stack.trim(); errorText = "Out of memory. " + stack.getSize() + " of " + dwTotalFrames + " frames will be opened."; } catch (Exception e) { errorText = exceptionMessage(e); if (isVirtual || stack==null || stack.getSize()==0) //return null only if we have really nothing return null; } finally { closeFile(raFile); if (verbose) IJ.log("File closed."); IJ.showProgress(1.0); } if (isVirtual && frameInfos != null) stack = this; if (stack!=null && cm!=null) stack.setColorModel(cm); return stack; } /** Returns a description of the error reading the file with <code>makeStack</code> or null if no error */ public String getErrorText() { return errorText; } /** Returns an ImageProcessor for the specified slice of this virtual stack (if it is one) * where 1<=n<=nslices. Returns null if no virtual stack or no slices or error reading the frame. */ public synchronized ImageProcessor getProcessor(int n) { if (frameInfos==null || frameInfos.size()==0 || raFilePath==null) return null; if (n<1 || n>frameInfos.size()) throw new IllegalArgumentException("Argument out of range: "+n); Object pixels = null; RandomAccessFile rFile = null; try { rFile = new RandomAccessFile(new File(raFilePath), "r"); long[] frameInfo = (long[])(frameInfos.get(n-1)); pixels = readFrame(rFile, frameInfo[0], (int)frameInfo[1]); } catch (Exception e) { error(exceptionMessage(e)); return null; } finally { closeFile(rFile); } if (pixels == null) return null; //failed if (pixels instanceof byte[]) return new ByteProcessor(dwWidth, biHeight, (byte[])pixels, cm); else if (pixels instanceof short[]) return new ShortProcessor(dwWidth, biHeight, (short[])pixels, cm); else return new ColorProcessor(dwWidth, biHeight, (int[])pixels); } /** Returns the image width of the virtual stack */ public int getWidth() { return dwWidth; } /** Returns the image height of the virtual stack */ public int getHeight() { return biHeight; } /** Returns the number of images in this virtual stack (if it is one) */ public int getSize() { if (frameInfos == null) return 0; else return frameInfos.size(); } /** Returns the label of the specified slice in this virtual stack (if it is one). */ public String getSliceLabel(int n) { if (frameInfos==null || n<1 || n>frameInfos.size()) throw new IllegalArgumentException("No Virtual Stack or argument out of range: "+n); return frameLabel(((long[])(frameInfos.get(n-1)))[2]); } /** Deletes the specified image from this virtual stack (if it is one), * where 1<=n<=nslices. */ public void deleteSlice(int n) { if (frameInfos==null || frameInfos.size()==0) return; if (n<1 || n>frameInfos.size()) throw new IllegalArgumentException("Argument out of range: "+n); frameInfos.removeElementAt(n-1); } /** Parameters dialog, returns false on cancel */ private boolean showDialog (String fileName) { if (lastFrame!=-1) lastFrame = dwTotalFrames; if (!IJ.isMacro()) { convertToGray = staticConvertToGray; flipVertical = staticFlipVertical; isVirtual = staticIsVirtual; } GenericDialog gd = new GenericDialog("AVI Reader"); gd.addNumericField("First Frame: ", firstFrame, 0); gd.addNumericField("Last Frame: ", lastFrame, 0, 6, ""); gd.addCheckbox("Use Virtual Stack", isVirtual); gd.addCheckbox("Convert to Grayscale", convertToGray); gd.addCheckbox("Flip Vertical", flipVertical); gd.setSmartRecording(true); gd.showDialog(); if (gd.wasCanceled()) return false; firstFrame = (int)gd.getNextNumber(); lastFrame = (int)gd.getNextNumber(); isVirtual = gd.getNextBoolean(); convertToGray = gd.getNextBoolean(); flipVertical = gd.getNextBoolean(); if (!IJ.isMacro()) { staticConvertToGray = convertToGray; staticFlipVertical = flipVertical; staticIsVirtual = isVirtual; } IJ.register(this.getClass()); return true; } /** Read into a (virtual) stack */ private void readAVI(String path) throws Exception, IOException { if (!headerOK) // we have not read the header yet? openAndReadHeader(path); else { File file = new File(path); // open if currently not open raFile = new RandomAccessFile(file, "r"); } startTime += System.currentTimeMillis();// taking previously elapsed time into account /** MOVED UP HERE BY JSP*/ if (lastFrame > 0) // last frame number to read: from Dialog lastFrameToRead = lastFrame; if (lastFrame < 0 && dwTotalFrames > 0) // negative means "end frame minus ..." lastFrameToRead = dwTotalFrames+lastFrame; if (lastFrameToRead < firstFrame) // no frames to read return; boolean hasIndex = (dwFlags & AVIF_HASINDEX) != 0; if (isVirtual || firstFrame>1) { // avoid scanning frame-by-frame where we only need the positions frameInfos = new Vector<long[]>(100); // holds frame positions, sizes and time since start long nextPosition = -1; if (indexPosition > 0) { // attempt to get AVI2.0 index instead of scanning for all frames raFile.seek(indexPosition); nextPosition = findFourccAndRead(FOURCC_indx, false, indexPositionEnd, false); } if (hasIndex && (frameInfos==null ||frameInfos.size()==0)) { // got nothing from indx, attempt to read AVI 1 index 'idx1' raFile.seek(headerPositionEnd); moviPosition = findFourccAndSkip(FOURCC_movi, true, fileSize); // go behind the 'movi' list if (moviPosition<0) throw new Exception("AVI File has no movie data"); long positionBehindMovie = raFile.getFilePointer(); while (positionBehindMovie < fileSize-8) { if (verbose) IJ.log("searching for 'idx1' at 0x"+Long.toHexString(positionBehindMovie)); raFile.seek(positionBehindMovie); if (positionBehindMovie > FOUR_GB) isOversizedAvi1 = true; nextPosition = findFourccAndRead(FOURCC_idx1, false, fileSize, false); if (nextPosition >= 0) //AVI-1 index 'idx1' found break; positionBehindMovie += FOUR_GB; //maybe position was wrong because it was a 32-bit number, but > 4GB? } } if (verbose) IJ.log("'frameInfos' has "+frameInfos.size()+" entries"); } if (isVirtual && frameInfos.size()>0) // Virtual Stack only needs reading the index return; // Read AVI (movie data) frame by frame - if no index tag is present the pointers // for the virtual AVI stack will be read here raFile.seek(headerPositionEnd); if (firstFrame>1 && frameInfos.size()>0) { long[] frameInfo = (long[])frameInfos.get(0); raFile.seek(frameInfo[0]-8); // chunk starts 8 bytes before frame data frameNumber = firstFrame; if (verbose) IJ.log("directly go to frame "+firstFrame+" @ 0x"+Long.toHexString(frameInfo[0]-8)); readMovieData(fileSize); } else { frameNumber = 1; findFourccAndRead(FOURCC_movi, true, fileSize, true); } long pos = raFile.getFilePointer(); //IJ.log("at 0x"+Long.toHexString(pos)+" filesize=0x"+Long.toHexString(fileSize)); // extended AVI: try to find further 'RIFF' chunks, where we expect AVIX tags while (pos>0 && pos<fileSize && (frameNumber<lastFrameToRead+1)) pos = findFourccAndRead(FOURCC_RIFF, false, fileSize, false); return; } /** Open the file with given path and read its header */ private void openAndReadHeader (String path) throws Exception, IOException { startTime = System.currentTimeMillis(); if (verbose) IJ.log("OPEN AND READ AVI FILE HEADER "+timeString()); File file = new File(path); // o p e n raFile = new RandomAccessFile(file, "r"); raFilePath = path; fileSize = raFile.length(); int fileType = readInt(); // f i l e h e a d e r if (verbose) IJ.log("File header: File type='"+fourccString(fileType)+"' (should be 'RIFF')"+timeString()); if (fileType != FOURCC_RIFF) throw new Exception("Not an AVI file."); aviSize = readInt() & SIZE_MASK; //size of AVI chunk int riffType = readInt(); if (verbose) IJ.log("File header: RIFF type='"+fourccString(riffType)+"' (should be 'AVI ')"); if (riffType != FOURCC_AVI) throw new Exception("Not an AVI file."); findFourccAndRead(FOURCC_hdrl, true, fileSize, true); startTime -= System.currentTimeMillis(); //becomes minus elapsed Time headerOK = true; } /** Read AVIX chunks following the first RIFF AVI for large files (sequential reading frame-by-frame beyond the first chunk) **/ private void readAVIX(long endPosition) throws Exception, IOException { if (verbose) IJ.log("Trying to read AVIX"+timeString()); int riffType = readInt(); if (verbose) IJ.log("File header: RIFF type='"+fourccString(riffType)+"' (should be 'AVIX')"); if (riffType != FOURCC_AVIX) throw new Exception("Not an AVI file."); findFourccAndRead(FOURCC_movi, true, fileSize, true); //read movie data } /** Find the next position of fourcc or LIST fourcc and read contents. * Returns next position * If not found, throws exception or returns -1 */ private long findFourccAndRead(int fourcc, boolean isList, long endPosition, boolean throwNotFoundException) throws Exception, IOException { long nextPos; boolean contentOk = false; do { int type = readType(endPosition); if (type == 0) { //reached endPosition without finding if (throwNotFoundException) throw new Exception("Required item '"+fourccString(fourcc)+"' not found"); else return -1; } long size = readInt() & SIZE_MASK; nextPos = raFile.getFilePointer() + size; if (nextPos>endPosition || nextPos>fileSize) { errorText = "AVI File Error: '"+fourccString(type)+"' @ 0x"+Long.toHexString(raFile.getFilePointer()-8)+" has invalid length. File damaged/truncated?"; IJ.log(errorText); // this text is also remembered as error message for showing in message box if (fourcc == FOURCC_movi) nextPos = fileSize; // if movie data truncated, try reading what we can get else return -1; // otherwise, nothing to be done } if (isList && type == FOURCC_LIST) type = readInt(); if (verbose) IJ.log("Search for '"+fourccString(fourcc)+"', found "+fourccString(type)+"' data "+posSizeString(nextPos-size, size)); if (type==fourcc) { contentOk = readContents(fourcc, nextPos); } else if (verbose) IJ.log("'"+fourccString(type)+"', ignored"); raFile.seek(nextPos); if (contentOk) return nextPos; //found and read, breaks the loop } while (!contentOk); return nextPos; } /** Find the next position of fourcc or LIST fourcc, but does not read it, only * returns the first position inside the fourcc chunk and puts the file pointer * behind the fourcc chunk (if successful). * If not found, returns -1 */ private long findFourccAndSkip(int fourcc, boolean isList, long endPosition) throws IOException { while (true) { int type = readType(endPosition); if (type == 0) //reached endPosition without finding return -1; long size = readInt() & SIZE_MASK; long chunkPos = raFile.getFilePointer(); long nextPos = chunkPos + size; //note that 'size' of a list includes the 'type' that follows now if (isList && type == FOURCC_LIST) type = readInt(); if (verbose) IJ.log("Searching for (to skip) '"+fourccString(fourcc)+"', found "+fourccString(type)+ "' data "+posSizeString(chunkPos, size)); raFile.seek(nextPos); if (type == fourcc) return chunkPos; //found and skipped, breaks the loop } } /** read contents defined by four-cc code; returns true if contens ok */ private boolean readContents (int fourcc, long endPosition) throws Exception, IOException { switch (fourcc) { case FOURCC_hdrl: headerPositionEnd = endPosition; findFourccAndRead(FOURCC_avih, false, endPosition, true); findFourccAndRead(FOURCC_strl, true, endPosition, true); return true; case FOURCC_avih: readAviHeader(); return true; case FOURCC_strl: long nextPosition = findFourccAndRead(FOURCC_strh, false, endPosition, false); if (nextPosition<0) return false; indexPosition = findFourccAndRead(FOURCC_strf, false, endPosition, true); indexPositionEnd= endPosition; indexForCountingOnly = true; //try reading indx for counting number of entries totalFramesFromIndex = 0; nextPosition = findFourccAndRead(FOURCC_indx, false, endPosition, false); if (nextPosition > 0 && totalFramesFromIndex > dwTotalFrames) dwTotalFrames = totalFramesFromIndex; indexForCountingOnly = false; return true; case FOURCC_strh: int streamType = readInt(); if (streamType != FOURCC_vids) { if (verbose) IJ.log("Non-video Stream '"+fourccString(streamType)+" skipped"); streamNumber++; return false; } readStreamHeader(); return true; case FOURCC_strf: readBitMapInfo(endPosition); return true; case FOURCC_indx: case FOURCC_ix00: readAvi2Index(endPosition); return true; case FOURCC_idx1: readOldFrameIndex(endPosition); return true; case FOURCC_RIFF: readAVIX(endPosition); return true; case FOURCC_movi: readMovieData(endPosition); return true; } throw new Exception("Program error, type "+fourccString(fourcc)); } void readAviHeader() throws Exception, IOException { //'avih' dwMicroSecPerFrame = readInt(); dwMaxBytesPerSec = readInt(); dwReserved1 = readInt(); //in newer avi formats, this is dwPaddingGranularity? dwFlags = readInt(); dwTotalFrames = readInt(); dwInitialFrames = readInt(); dwStreams = readInt(); dwSuggestedBufferSize = readInt(); dwWidth = readInt(); dwHeight = readInt(); // dwReserved[4] follows, ignored if (verbose) { IJ.log("AVI HEADER (avih):"+timeString()); IJ.log(" dwMicroSecPerFrame=" + dwMicroSecPerFrame); IJ.log(" dwMaxBytesPerSec=" + dwMaxBytesPerSec); IJ.log(" dwReserved1=" + dwReserved1); IJ.log(" dwFlags=" + dwFlags); IJ.log(" dwTotalFrames=" + dwTotalFrames); IJ.log(" dwInitialFrames=" + dwInitialFrames); IJ.log(" dwStreams=" + dwStreams); IJ.log(" dwSuggestedBufferSize=" + dwSuggestedBufferSize); IJ.log(" dwWidth=" + dwWidth); IJ.log(" dwHeight=" + dwHeight); } } void readStreamHeader() throws Exception, IOException { //'strh' fccStreamHandler = readInt(); dwStreamFlags = readInt(); dwPriorityLanguage = readInt(); dwStreamInitialFrames = readInt(); dwStreamScale = readInt(); dwStreamRate = readInt(); dwStreamStart = readInt(); dwStreamLength = readInt(); dwStreamSuggestedBufferSize = readInt(); dwStreamQuality = readInt(); dwStreamSampleSize = readInt(); //rcFrame rectangle follows, ignored if (verbose) { IJ.log("VIDEO STREAM HEADER (strh):"); IJ.log(" fccStreamHandler='" + fourccString(fccStreamHandler)+"'"); IJ.log(" dwStreamFlags=" + dwStreamFlags); IJ.log(" wPriority,wLanguage=" + dwPriorityLanguage); IJ.log(" dwStreamInitialFrames=" + dwStreamInitialFrames); IJ.log(" dwStreamScale=" + dwStreamScale); IJ.log(" dwStreamRate=" + dwStreamRate); IJ.log(" dwStreamStart=" + dwStreamStart); IJ.log(" dwStreamLength=" + dwStreamLength); IJ.log(" dwStreamSuggestedBufferSize=" + dwStreamSuggestedBufferSize); IJ.log(" dwStreamQuality=" + dwStreamQuality); IJ.log(" dwStreamSampleSize=" + dwStreamSampleSize); } if (dwStreamSampleSize > 1) throw new Exception("Video stream with "+dwStreamSampleSize+" (more than 1) frames/chunk not supported"); // what the chunks in that stream will be named (we have two possibilites: uncompressed & compressed) type0xdb = FOURCC_00db + (streamNumber<<8); //'01db' for stream 1, etc. (inverse byte order!) type0xdc = FOURCC_00dc + (streamNumber<<8); //'01dc' for stream 1, etc. } /** Read 'AVI 2'-type main index 'indx' or an 'ix00' index to frames * (only the types AVI_INDEX_OF_INDEXES and AVI_INDEX_OF_CHUNKS are supported) */ private void readAvi2Index(long endPosition) throws Exception, IOException { short wLongsPerEntry = readShort(); byte bIndexSubType = raFile.readByte(); byte bIndexType = raFile.readByte(); int nEntriesInUse = readInt(); int dwChunkId = readInt(); long qwBaseOffset = readLong(); readInt(); // 3rd dwReserved (first two dwreserved are qwBaseOffset!) if (verbose) { String bIndexString = bIndexType == AVI_INDEX_OF_CHUNKS ? ": AVI_INDEX_OF_CHUNKS" : bIndexType == AVI_INDEX_OF_INDEXES ? ": AVI_INDEX_OF_INDEXES" : ": UNSUPPORTED"; IJ.log("AVI 2 INDEX:"); IJ.log(" wLongsPerEntry=" + wLongsPerEntry); IJ.log(" bIndexSubType=" + bIndexSubType); IJ.log(" bIndexType=" + bIndexType + bIndexString); IJ.log(" nEntriesInUse=" + nEntriesInUse); IJ.log(" dwChunkId='" + fourccString(dwChunkId)+"'"); if (bIndexType == AVI_INDEX_OF_CHUNKS) IJ.log(" qwBaseOffset=" + "0x"+Long.toHexString(qwBaseOffset)); } if (bIndexType == AVI_INDEX_OF_INDEXES) { // 'indx' points to other indices if (wLongsPerEntry != 4) return; //badly formed index, ignore it for (int i=0;i<nEntriesInUse;i++) { //read all entries (each pointing to an ix00 index) long qwOffset = readLong(); int dwSize = readInt(); int dwDuration = readInt(); //number of frames in ix00; ignored: not always trustworthy if (verbose) IJ.log(" indx entry: '" +fourccString(dwChunkId)+"' incl header "+posSizeString(qwOffset,dwSize)+timeString()); long nextIndxEntryPointer = raFile.getFilePointer(); raFile.seek(qwOffset); //qwOffset & dwSize here include chunk header of ix00 findFourccAndRead(FOURCC_ix00, false, qwOffset+dwSize, true); raFile.seek(nextIndxEntryPointer); if (frameNumber>lastFrameToRead) break; } } else if (bIndexType == AVI_INDEX_OF_CHUNKS) { if (verbose) { IJ.log("readAvi2Index frameNumber="+frameNumber+" firstFrame="+firstFrame); if (indexForCountingOnly) IJ.log("<just counting frames, not interpreting index now>"); } if (wLongsPerEntry != 2) return; //badly formed index, ignore it if (dwChunkId != type0xdb && dwChunkId != type0xdc) { //not the stream we search for? (should not happen) if (verbose) IJ.log("INDEX ERROR: SKIPPED ix00, wrong stream number or type, should be "+ fourccString(type0xdb)+" or "+fourccString(type0xdc)); return; } if (indexForCountingOnly) { //only count number of entries, don't put into table totalFramesFromIndex += nEntriesInUse; return; } for (int i=0;i<nEntriesInUse;i++) { long dwOffset = readInt() & 0xffffffffL; long pos=qwBaseOffset+dwOffset; int dwSize = readInt(); if (isVirtual) IJ.showProgress((double)frameNumber/lastFrameToRead); if (frameNumber >= firstFrame && dwSize>0) { //only valid frames (no blank frames) frameInfos.add(new long[] {pos, dwSize, (long) frameNumber*dwMicroSecPerFrame}); if (verbose) IJ.log("movie data "+frameNumber+" '"+fourccString(dwChunkId)+"' "+posSizeString(pos,dwSize)+timeString()); } frameNumber++; if (frameNumber>lastFrameToRead) break; } if (verbose) IJ.log("Index read up to frame "+(frameNumber-1)); } } /** Read AVI 1 index 'idx1' */ private void readOldFrameIndex(long endPosition) throws Exception, IOException { //IJ.log("READ AVI 1 INDEX, isOversizedAvi1="+isOversizedAvi1); int offset = -1; //difference between absolute frame address and address given in idx1 int[] offsetsToTry = new int[] {0, (int)moviPosition}; // dwOffset may be w.r.t. file start or w.r.t. 'movi' list. long lastFramePos = 0; while (true) { if ((raFile.getFilePointer()+16) >endPosition) break; int dwChunkId = readInt(); int dwFlags = readInt(); int dwOffset = readInt(); int dwSize = readInt(); //IJ.log("idx1: dwOffset=0x"+Long.toHexString(dwOffset)); //IJ.log("moviPosition=0x"+Long.toHexString(moviPosition)); if ((dwChunkId==type0xdb || dwChunkId==type0xdc) && dwSize>0) { if (offset < 0) { // find out what the offset refers to long temp = raFile.getFilePointer(); for (int i=0; i<offsetsToTry.length; i++) { long pos = (dwOffset + offsetsToTry[i]) & SIZE_MASK; if (pos < moviPosition) continue; // frame must be in 'movi' list raFile.seek(pos); int chunkIdAtPos = readInt(); // see whether this offset points to the desired chunk //IJ.log("read@=0x"+Long.toHexString(pos)+": '"+fourccString(chunkIdAtPos)+"'"); if (chunkIdAtPos == dwChunkId) { offset = offsetsToTry[i]; break; } } if (verbose) IJ.log("idx1: dwOffsets are w.r.t. 0x"+(offset<0 ? " UNKONWN??" : Long.toHexString(offset))); raFile.seek(temp); if (offset < 0) return; // neither offset works } long framePos = (dwOffset & SIZE_MASK) + offset; if (isOversizedAvi1) while (framePos < lastFramePos) framePos += FOUR_GB; //index entries are modulo 2^32, assume frames are ascending lastFramePos = framePos; if (frameNumber >= firstFrame) { frameInfos.add(new long[]{framePos+8, dwSize, (long)frameNumber*dwMicroSecPerFrame}); if (verbose) IJ.log("idx1 movie data '"+fourccString(dwChunkId)+"' "+posSizeString(framePos,dwSize)+timeString()); } frameNumber++; if (frameNumber>lastFrameToRead) break; } //if(dwChunkId...) } //while(true) if (verbose) IJ.log("Index read up to frame "+(frameNumber-1)); } /**Read stream format chunk: starts with BitMapInfo, may contain palette */ void readBitMapInfo(long endPosition) throws Exception, IOException { biSize = readInt(); biWidth = readInt(); biHeight = readInt(); biPlanes = readShort(); biBitCount = readShort(); biCompression = readInt(); biSizeImage = readInt(); biXPelsPerMeter = readInt(); biYPelsPerMeter = readInt(); biClrUsed = readInt(); biClrImportant = readInt(); if (verbose) { IJ.log(" biSize=" + biSize); IJ.log(" biWidth=" + biWidth); IJ.log(" biHeight=" + biHeight); IJ.log(" biPlanes=" + biPlanes); IJ.log(" biBitCount=" + biBitCount); IJ.log(" biCompression=0x" + Integer.toHexString(biCompression)+" '"+fourccString(biCompression)+"'"); IJ.log(" biSizeImage=" + biSizeImage); IJ.log(" biXPelsPerMeter=" + biXPelsPerMeter); IJ.log(" biYPelsPerMeter=" + biYPelsPerMeter); IJ.log(" biClrUsed=" + biClrUsed); IJ.log(" biClrImportant=" + biClrImportant); } int allowedBitCount = 0; boolean readPalette = false; switch (biCompression) { case NO_COMPRESSION: case NO_COMPRESSION_RGB: case NO_COMPRESSION_RAW: dataCompression = NO_COMPRESSION; dataTopDown = biHeight<0; //RGB mode is usually bottom-up, negative height signals top-down allowedBitCount = 8 | BITMASK24 | 32; //we don't support 1, 2 and 4 byte data readPalette = biBitCount <= 8; break; case NO_COMPRESSION_Y8: case NO_COMPRESSION_GREY: case NO_COMPRESSION_Y800: dataTopDown = true; dataCompression = NO_COMPRESSION; allowedBitCount = 8; break; case NO_COMPRESSION_Y16: case NO_COMPRESSION_MIL: dataCompression = NO_COMPRESSION; allowedBitCount = 16; break; case AYUV_COMPRESSION: dataCompression = AYUV_COMPRESSION; allowedBitCount = 32; break; case UYVY_COMPRESSION: case UYNV_COMPRESSION: dataTopDown = true; case CYUV_COMPRESSION: //same, not top-down case V422_COMPRESSION: dataCompression = UYVY_COMPRESSION; allowedBitCount = 16; break; case YUY2_COMPRESSION: case YUNV_COMPRESSION: case YUYV_COMPRESSION: dataTopDown = true; dataCompression = YUY2_COMPRESSION; allowedBitCount = 16; break; case YVYU_COMPRESSION: dataTopDown = true; dataCompression = YVYU_COMPRESSION; allowedBitCount = 16; break; case IYUV_COMPRESSION: case I420_COMPRESSION: case YV12_COMPRESSION: case NV12_COMPRESSION: case NV21_COMPRESSION: dataCompression = (dataCompression==IYUV_COMPRESSION) ? I420_COMPRESSION : biCompression; dataTopDown = biHeight>0; isPlanarFormat = true; allowedBitCount = 12; break; case JPEG_COMPRESSION: case JPEG_COMPRESSION2: case JPEG_COMPRESSION3: case MJPG_COMPRESSION: dataCompression = JPEG_COMPRESSION; variableLength = true; break; case PNG_COMPRESSION: case PNG_COMPRESSION2: case PNG_COMPRESSION3: variableLength = true; dataCompression = PNG_COMPRESSION; break; default: throw new Exception("Unsupported compression: "+Integer.toHexString(biCompression)+ (biCompression>=0x20202020 ? " '" + fourccString(biCompression)+"'" : "")); } int bitCountTest = (biBitCount==24) ? BITMASK24 : biBitCount; //convert "24" to a flag if (allowedBitCount!=0 && (bitCountTest & allowedBitCount)==0) throw new Exception("Unsupported: "+biBitCount+" bits/pixel for compression '"+ fourccString(biCompression)+"'"); if (biHeight < 0) //negative height was for top-down data in RGB mode biHeight = -biHeight; if (isPlanarFormat && ((biWidth&1)!=0 || (biHeight&1)!=0)) throw new Exception("Odd size ("+biWidth+"x"+biHeight+") unsupported with "+fourccString(biCompression)+" compression"); // raw & interleaved YUV: scan line is padded with zeroes to be a multiple of four bytes scanLineSize = isPlanarFormat ? (biWidth * biBitCount) / 8 : ((biWidth * biBitCount + 31) / 32) * 4; // a value of biClrUsed=0 means we determine this based on the bits per pixel, if there is a palette long spaceForPalette = endPosition-raFile.getFilePointer(); if (readPalette && biClrUsed==0 && spaceForPalette!=0) biClrUsed = 1 << biBitCount; if (verbose) { IJ.log(" > data compression=0x" + Integer.toHexString(dataCompression)+" '"+fourccString(dataCompression)+"'"); IJ.log(" > palette colors=" + biClrUsed); IJ.log(" > scan line size=" + scanLineSize); IJ.log(" > data top down=" + dataTopDown); } //read color palette if (readPalette && biClrUsed > 0) { if (verbose) IJ.log(" Reading "+biClrUsed+" Palette colors: " + posSizeString(spaceForPalette)); if (spaceForPalette < biClrUsed*4) throw new Exception("Not enough data ("+spaceForPalette+") for palette of size "+(biClrUsed*4)); byte[] pr = new byte[biClrUsed]; byte[] pg = new byte[biClrUsed]; byte[] pb = new byte[biClrUsed]; for (int i = 0; i < biClrUsed; i++) { pb[i] = raFile.readByte(); pg[i] = raFile.readByte(); pr[i] = raFile.readByte(); raFile.readByte(); } cm = new IndexColorModel(biBitCount, biClrUsed, pr, pg, pb); } } /**Read from the 'movi' chunk. Skips audio ('..wb', etc.), 'LIST' 'rec' etc, only reads '..db' or '..dc'*/ void readMovieData(long endPosition) throws Exception, IOException { if (verbose) IJ.log("MOVIE DATA "+posSizeString(endPosition-raFile.getFilePointer())+timeString()+ "\nSearching for stream "+streamNumber+": '"+ fourccString(type0xdb)+"' or '"+fourccString(type0xdc)+"' chunks"); if (isVirtual) { if (frameInfos==null) // we might have it already from reading the first chunk frameInfos = new Vector<long[]>(lastFrameToRead); // holds frame positions in file (for non-constant frame sizes, should hold long[] with pos and size) } else if (stack==null) stack = new ImageStack(dwWidth, biHeight); while (true) { //loop over all chunks int type = readType(endPosition); if (type==0) break; //endPosition of 'movi' reached? long size = readInt() & SIZE_MASK; long pos = raFile.getFilePointer(); long nextPos = pos + size; if (nextPos > endPosition && nextPos < fileSize-8 && fileSize > FOUR_GB) { endPosition = fileSize; //looks like old ImageJ AVI 1.0 >4GB: wrong endPosition } if ((type==type0xdb || type==type0xdc) && size>0) { IJ.showProgress((double)frameNumber /lastFrameToRead); if (verbose) IJ.log(frameNumber+" movie data '"+fourccString(type)+"' "+posSizeString(size)+timeString()); if (frameNumber >= firstFrame) { if (isVirtual) frameInfos.add(new long[]{pos, size, frameNumber*dwMicroSecPerFrame}); else { //read the frame Object pixels = readFrame(raFile, pos, (int)size); String label = frameLabel(frameNumber*dwMicroSecPerFrame); stack.addSlice(label, pixels); } } frameNumber++; if (frameNumber>lastFrameToRead) break; } else if (verbose) IJ.log("skipped '"+fourccString(type)+"' "+posSizeString(size)); if (nextPos > endPosition) break; raFile.seek(nextPos); } } /** Reads a frame at a given position in the file, returns pixels array */ private Object readFrame (RandomAccessFile rFile, long filePos, int size) throws Exception, IOException { rFile.seek(filePos); //if (verbose) //IJ.log("virtual AVI: readFrame @"+posSizeString(filePos, size)+" varlength="+variableLength); if (variableLength) //JPEG or PNG-compressed frames return readCompressedFrame(rFile, size); else return readFixedLengthFrame(rFile, size); } /** Reads a JPEG or PNG-compressed frame from a RandomAccessFile and * returns the pixels array of the resulting image and sets the * ColorModel cm (if appropriate) */ private Object readCompressedFrame (RandomAccessFile rFile, int size) throws Exception, IOException { InputStream inputStream = new raInputStream(rFile, size, biCompression==MJPG_COMPRESSION); BufferedImage bi = ImageIO.read(inputStream); if (bi==null) throw new Exception("can't read frame, ImageIO returns null"); int type = bi.getType(); ImageProcessor ip = null; if (type==BufferedImage.TYPE_BYTE_GRAY) { ip = new ByteProcessor(bi); } else if (type==bi.TYPE_BYTE_INDEXED) { cm = bi.getColorModel(); ip = new ByteProcessor((Image)bi); } else ip = new ColorProcessor(bi); if (convertToGray) ip = ip.convertToByte(false); if (flipVertical) ip.flipVertical(); if (ip.getWidth()!=dwWidth || ip.getHeight()!=biHeight) ip = ip.resize(dwWidth, biHeight); return ip.getPixels(); } /** Read a fixed-length frame (RandomAccessFile rFile, long filePos, int size) * return the pixels array of the resulting image */ private Object readFixedLengthFrame (RandomAccessFile rFile, int size) throws Exception, IOException { if (size < scanLineSize*biHeight) //check minimum size (fixed frame length format) throw new Exception("Data chunk size "+size+" too short ("+(scanLineSize*biHeight)+" required)"); byte[] rawData = new byte[size]; int n = rFile.read(rawData, 0, size); if (n < rawData.length) throw new Exception("Frame ended prematurely after " + n + " bytes"); boolean topDown = flipVertical ? !dataTopDown : dataTopDown; Object pixels = null; byte[] bPixels = null; int[] cPixels = null; short[] sPixels = null; if (biBitCount <=8 || convertToGray) { bPixels = new byte[dwWidth * biHeight]; pixels = bPixels; } else if (biBitCount == 16 && dataCompression == NO_COMPRESSION) { sPixels = new short[dwWidth * biHeight]; pixels = sPixels; } else { cPixels = new int[dwWidth * biHeight]; pixels = cPixels; } if (isPlanarFormat && !convertToGray) unpackPlanarImage(rawData, cPixels, topDown); else { int offset = topDown ? 0 : (biHeight-1)*dwWidth; int rawOffset = 0; for (int i = biHeight - 1; i >= 0; i--) { //for all lines if (biBitCount <=8 || isPlanarFormat) unpack8bit(rawData, rawOffset, bPixels, offset, dwWidth); else if (convertToGray) unpackGray(rawData, rawOffset, bPixels, offset, dwWidth); else if (biBitCount==16 && dataCompression == NO_COMPRESSION) unpackShort(rawData, rawOffset, sPixels, offset, dwWidth); else unpack(rawData, rawOffset, cPixels, offset, dwWidth); rawOffset += isPlanarFormat ? dwWidth : scanLineSize; offset += topDown ? dwWidth : -dwWidth; } } return pixels; } /** For one line: copy byte data into the byte array for creating a ByteProcessor */ void unpack8bit(byte[] rawData, int rawOffset, byte[] pixels, int byteOffset, int w) { for (int i = 0; i < w; i++) pixels[byteOffset + i] = rawData[rawOffset + i]; } /** For one line: Unpack and convert YUV or RGB video data to grayscale (byte array for ByteProcessor) */ void unpackGray(byte[] rawData, int rawOffset, byte[] pixels, int byteOffset, int w) { int j = byteOffset; int k = rawOffset; if (dataCompression == 0) { for (int i = 0; i < w; i++) { int b0 = (((int) (rawData[k++])) & 0xff); int b1 = (((int) (rawData[k++])) & 0xff); int b2 = (((int) (rawData[k++])) & 0xff); if (biBitCount==32) k++; // ignore 4th byte (alpha value) pixels[j++] = (byte)((b0*934 + b1*4809 + b2*2449 + 4096)>>13); //0.299*R+0.587*G+0.114*B } } else { if (dataCompression==UYVY_COMPRESSION || dataCompression==AYUV_COMPRESSION) k++; //skip first byte in these formats (chroma) int step = dataCompression==AYUV_COMPRESSION ? 4 : 2; for (int i = 0; i < w; i++) { pixels[j++] = rawData[k]; //Non-standard: no scaling from 16-235 to 0-255 here k+=step; } } } /** For one line: Unpack 16bit grayscale data and convert to short array for ShortProcessor */ void unpackShort(byte[] rawData, int rawOffset, short[] pixels, int shortOffset, int w) { int j = shortOffset; int k = rawOffset; for (int i = 0; i < w; i++) { pixels[j++] = (short) ((int)(rawData[k++] & 0xFF)| (((int)(rawData[k++] & 0xFF))<<8)); } } /** For one line: Read YUV, RGB or RGB+alpha data and writes RGB int array for ColorProcessor */ void unpack(byte[] rawData, int rawOffset, int[] pixels, int intOffset, int w) { int j = intOffset; int k = rawOffset; switch (dataCompression) { case NO_COMPRESSION: for (int i = 0; i < w; i++) { int b0 = (((int) (rawData[k++])) & 0xff); int b1 = (((int) (rawData[k++])) & 0xff) << 8; int b2 = (((int) (rawData[k++])) & 0xff) << 16; if (biBitCount==32) k++; // ignore 4th byte (alpha value) pixels[j++] = 0xff000000 | b0 | b1 | b2; } break; case YUY2_COMPRESSION: for (int i = 0; i < w/2; i++) { int y0 = rawData[k++] & 0xff; int u = rawData[k++] ^ 0xffffff80; //converts byte range 0...ff to -128 ... 127 int y1 = rawData[k++] & 0xff; int v = rawData[k++] ^ 0xffffff80; writeRGBfromYUV(y0, u, v, pixels, j++); writeRGBfromYUV(y1, u, v, pixels, j++); } break; case UYVY_COMPRESSION: for (int i = 0; i < w/2; i++) { int u = rawData[k++] ^ 0xffffff80; int y0 = rawData[k++] & 0xff; int v = rawData[k++] ^ 0xffffff80; int y1 = rawData[k++] & 0xff; writeRGBfromYUV(y0, u, v, pixels, j++); writeRGBfromYUV(y1, u, v, pixels, j++); } break; case YVYU_COMPRESSION: for (int i = 0; i < w/2; i++) { int y0 = rawData[k++] & 0xff; int v = rawData[k++] ^ 0xffffff80; int y1 = rawData[k++] & 0xff; int u = rawData[k++] ^ 0xffffff80; writeRGBfromYUV(y0, u, v, pixels, j++); writeRGBfromYUV(y1, u, v, pixels, j++); } break; case AYUV_COMPRESSION: for (int i = 0; i < w; i++) { k++; //ignore alpha channel int y = rawData[k++] & 0xff; int v = rawData[k++] ^ 0xffffff80; int u = rawData[k++] ^ 0xffffff80; writeRGBfromYUV(y, u, v, pixels, j++); } break; } } /** Unpack planar YV12 or I420 format (full frame). */ void unpackPlanarImage(byte[] rawData, int[] cPixels, boolean topDown) { int w = dwWidth, h = dwHeight; int uP = w*h, vP = w*h; // pointers in U, V array int uvInc = (dataCompression==NV12_COMPRESSION || dataCompression==NV21_COMPRESSION) ? 2 : 1; // NV12, NV21 have interleaved u,v if (dataCompression == YV12_COMPRESSION) // separate planes for U and V, 2-fold subsampling in x&y uP += w*h/4; // first V, then U else if (dataCompression == I420_COMPRESSION) vP += w*h/4; // first U, then V else if (dataCompression == NV12_COMPRESSION) vP++; //interleaved U, then V else //NV21_COMPRESSION uP++; int lineOutInc = topDown ? w : -w; for (int line=0; line<h; line+=2) { int pRaw0 = line*w; int pRawEnd = pRaw0 + w; int pOut = topDown ? line*w : (h-line-1)*w; for (int pRaw = pRaw0; pRaw < pRawEnd; ) { int u = rawData[uP] ^ 0xffffff80; // u and v for 2x2-pixel block int v = rawData[vP] ^ 0xffffff80; writeRGBfromYUV(rawData[pRaw] & 0xff, u, v, cPixels, pOut); writeRGBfromYUV(rawData[pRaw+w] & 0xff, u, v, cPixels, pOut+lineOutInc); pRaw++; pOut++; writeRGBfromYUV(rawData[pRaw] & 0xff, u, v, cPixels, pOut); writeRGBfromYUV(rawData[pRaw+w] & 0xff, u, v, cPixels, pOut+lineOutInc); pRaw++; pOut++; uP+=uvInc; vP+=uvInc; } } } /** Write an intData RGB value converted from YUV, * The y range between 16 and 235 becomes 0...255 * u, v should be between -112 and +112 */ final void writeRGBfromYUV(int y, int u, int v, int[]pixels, int intArrayIndex) { //int r = (int)(1.164*(y-16)+1.596*v+0.5); //int g = (int)(1.164*(y-16)-0.391*u-0.813*v+0.5); //int b = (int)(1.164*(y-16)+2.018*u+0.5); int r = (9535*y + 13074*v -148464) >> 13; int g = (9535*y - 6660*v - 3203*u -148464) >> 13; int b = (9535*y + 16531*u -148464) >> 13; if (r>255) r=255; if (r<0) r=0; if (g>255) g=255; if (g<0) g=0; if (b>255) b=255; if (b<0) b=0; pixels[intArrayIndex] = 0xff000000 | (r<<16) | (g<<8) | b; } /** Read 8-byte int with Intel (little-endian) byte order * (note: RandomAccessFile.readLong has other byte order than AVI) */ final long readLong() throws IOException { long low = readInt() & 0x00000000FFFFFFFFL; long high = readInt() & 0x00000000FFFFFFFFL; long result = high <<32 | low; return (long) result; //(high << 32 | low); } /** Read 4-byte int with Intel (little-endian) byte order * (note: RandomAccessFile.readInt has other byte order than AVI) */ final int readInt() throws IOException { int result = 0; for (int shiftBy = 0; shiftBy < 32; shiftBy += 8) result |= (raFile.readByte() & 0xff) << shiftBy; return result; } /** Read 2-byte short with Intel (little-endian) byte order * (note: RandomAccessFile.readShort has other byte order than AVI) */ final short readShort() throws IOException { int low = raFile.readByte() & 0xff; int high = raFile.readByte() & 0xff; return (short) (high << 8 | low); } /** Read type of next chunk that is not JUNK. * Returns type (or 0 if no non-JUNK chunk until endPosition) */ private int readType(long endPosition) throws IOException { while (true) { long pos = raFile.getFilePointer(); if (pos%paddingGranularity!=0) { pos = (pos/paddingGranularity+1)*paddingGranularity; raFile.seek(pos); //pad to even address } if (pos >= endPosition) return 0; int type = readInt(); if (type != FOURCC_JUNK) return type; long size = readInt()&SIZE_MASK; if (verbose) IJ.log("Skip JUNK: "+posSizeString(size)); raFile.seek(raFile.getFilePointer()+size); //skip junk } } private void setFramesPerSecond (ImagePlus imp) { if (dwMicroSecPerFrame<1000 && dwStreamRate>0) //if no reasonable frame time, get it from rate dwMicroSecPerFrame = (int)(dwStreamScale*1e6/dwStreamRate); if (dwMicroSecPerFrame>=1000) imp.getCalibration().fps = 1e6 / dwMicroSecPerFrame; } private String frameLabel(long timeMicroSec) { return IJ.d2s(timeMicroSec/1.e6)+" s"; } private String posSizeString(long size) throws IOException { return posSizeString(raFile.getFilePointer(), size); } private String posSizeString(long pos, long size) { return "0x"+Long.toHexString(pos)+"-0x"+Long.toHexString(pos+size-1)+" ("+size+" Bytes)"; } private String timeString() { return " (t="+(System.currentTimeMillis()-startTime)+" ms)"; } /** returns a string of a four-cc code corresponding to an int (Intel byte order) */ private String fourccString(int fourcc) { String s = ""; for (int i=0; i<4; i++) { int c = fourcc&0xff; s += Character.toString((char)c); fourcc >>= 8; } return s; } /** tries to close the given file (if not null) */ private void closeFile(RandomAccessFile rFile) { if (rFile != null) try { rFile.close(); } catch (Exception e) {} } private void error(String msg) { aborting = true; IJ.error("AVI Reader", msg); } private String exceptionMessage (Exception e) { String msg; if (e.getClass() == Exception.class) //for "home-built" exceptions: message only msg = e.getMessage(); else msg = e + "\n" + e.getStackTrace()[0]+"\n"+e.getStackTrace()[1]; return "An error occurred reading the AVI file.\n \n" + msg; } /** An input stream reading from a RandomAccessFile (starting at the current position). * This class also adds 'Define Huffman Table' (DHT) segments to convert MJPG to JPEG. */ final private static int BUFFERSIZE = 4096; //should be large enough to hold the full JFIF header // up to beginning of the image data and the Huffman tables final private static byte[] HUFFMAN_TABLES = new byte[] { //the 'DHT' segment (byte)0xFF,(byte)0xC4,0x01,(byte)0xA2, //these 4 bytes are tag & length; data follow 0x00,0x00,0x01,0x05,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x01,0x00,0x03,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 0x08,0x09,0x0A,0x0B,0x10,0x00,0x02,0x01,0x03,0x03,0x02,0x04,0x03,0x05,0x05,0x04,0x04,0x00, 0x00,0x01,0x7D,0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61, 0x07,0x22,0x71,0x14,0x32,(byte)0x81,(byte)0x91,(byte)0xA1,0x08,0x23,0x42, (byte)0xB1,(byte)0xC1,0x15,0x52,(byte)0xD1,(byte)0xF0,0x24, 0x33,0x62,0x72,(byte)0x82,0x09,0x0A,0x16,0x17,0x18,0x19,0x1A,0x25,0x26,0x27,0x28,0x29,0x2A,0x34, 0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56, 0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78, 0x79,0x7A,(byte)0x83,(byte)0x84,(byte)0x85,(byte)0x86,(byte)0x87,(byte)0x88,(byte)0x89, (byte)0x8A,(byte)0x92,(byte)0x93,(byte)0x94,(byte)0x95,(byte)0x96,(byte)0x97,(byte)0x98,(byte)0x99, (byte)0x9A,(byte)0xA2,(byte)0xA3,(byte)0xA4,(byte)0xA5,(byte)0xA6,(byte)0xA7,(byte)0xA8,(byte)0xA9, (byte)0xAA,(byte)0xB2,(byte)0xB3,(byte)0xB4,(byte)0xB5,(byte)0xB6,(byte)0xB7,(byte)0xB8,(byte)0xB9, (byte)0xBA,(byte)0xC2,(byte)0xC3,(byte)0xC4,(byte)0xC5,(byte)0xC6,(byte)0xC7,(byte)0xC8,(byte)0xC9, (byte)0xCA,(byte)0xD2,(byte)0xD3,(byte)0xD4,(byte)0xD5,(byte)0xD6,(byte)0xD7,(byte)0xD8,(byte)0xD9, (byte)0xDA,(byte)0xE1,(byte)0xE2,(byte)0xE3,(byte)0xE4,(byte)0xE5,(byte)0xE6,(byte)0xE7,(byte)0xE8, (byte)0xE9,(byte)0xEA,(byte)0xF1,(byte)0xF2,(byte)0xF3,(byte)0xF4,(byte)0xF5,(byte)0xF6,(byte)0xF7, (byte)0xF8,(byte)0xF9,(byte)0xFA,0x11,0x00,0x02,0x01,0x02,0x04,0x04,0x03,0x04,0x07,0x05,0x04,0x04,0x00,0x01, 0x02,0x77,0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71, 0x13,0x22,0x32,(byte)0x81,0x08,0x14,0x42,(byte)0x91,(byte)0xA1,(byte)0xB1,(byte)0xC1,0x09,0x23,0x33, 0x52,(byte)0xF0,0x15,0x62, 0x72,(byte)0xD1,0x0A,0x16,0x24,0x34,(byte)0xE1,0x25,(byte)0xF1,0x17,0x18,0x19,0x1A,0x26,0x27,0x28,0x29,0x2A, 0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56, 0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78, 0x79,0x7A,(byte)0x82,(byte)0x83,(byte)0x84,(byte)0x85,(byte)0x86,(byte)0x87,(byte)0x88,(byte)0x89, (byte)0x8A,(byte)0x92,(byte)0x93,(byte)0x94,(byte)0x95,(byte)0x96,(byte)0x97,(byte)0x98, (byte)0x99,(byte)0x9A,(byte)0xA2,(byte)0xA3,(byte)0xA4,(byte)0xA5,(byte)0xA6,(byte)0xA7,(byte)0xA8, (byte)0xA9,(byte)0xAA,(byte)0xB2,(byte)0xB3,(byte)0xB4,(byte)0xB5,(byte)0xB6,(byte)0xB7,(byte)0xB8, (byte)0xB9,(byte)0xBA,(byte)0xC2,(byte)0xC3,(byte)0xC4,(byte)0xC5,(byte)0xC6,(byte)0xC7,(byte)0xC8, (byte)0xC9,(byte)0xCA,(byte)0xD2,(byte)0xD3,(byte)0xD4,(byte)0xD5,(byte)0xD6,(byte)0xD7,(byte)0xD8, (byte)0xD9,(byte)0xDA,(byte)0xE2,(byte)0xE3,(byte)0xE4,(byte)0xE5,(byte)0xE6,(byte)0xE7,(byte)0xE8, (byte)0xE9,(byte)0xEA,(byte)0xF2,(byte)0xF3,(byte)0xF4,(byte)0xF5,(byte)0xF6,(byte)0xF7,(byte)0xF8, (byte)0xF9,(byte)0xFA }; final private static int HUFFMAN_LENGTH = 420; class raInputStream extends InputStream { RandomAccessFile rFile; //where to read the data from int readableSize; //number of bytes that one should expect to be readable boolean fixMJPG; //whether to use an ugly hack to convert MJPG frames to JPEG byte[] buffer; //holds beginning of data for fixing Huffman tables int bufferPointer; //next position in buffer to read int bufferLength; //bytes allocated in buffer /** Constructor */ raInputStream (RandomAccessFile rFile, int readableSize, boolean fixMJPG) throws IOException { this.rFile = rFile; this.readableSize = readableSize; this.fixMJPG = fixMJPG; if (fixMJPG) { buffer = new byte[BUFFERSIZE]; bufferLength = Math.min(BUFFERSIZE-HUFFMAN_LENGTH, readableSize); bufferLength = rFile.read(buffer, 0, bufferLength); addHuffmanTables(); } } public int available () { return readableSize; } // Read methods: // There is no check against reading beyond the allowed range, which is // start position + readableSize // (i.e., reading beyond the frame in the avi file would be possible). /** Read a single byte */ public int read () throws IOException { readableSize--; if (fixMJPG) { int result = buffer[bufferPointer] & 0xff; bufferPointer++; if (bufferPointer >= bufferLength) fixMJPG = false; //buffer exhausted, no more attempt to fix it return result; } else return rFile.read(); } /** Read bytes into an array */ public int read (byte[] b, int off, int len) throws IOException { //IJ.log("read "+len+" bytes, fix="+fixMJPG); int nBytes; if (fixMJPG) { nBytes = Math.min(len, bufferLength-bufferPointer); System.arraycopy(buffer, bufferPointer, b, off, nBytes); bufferPointer += nBytes; if (bufferPointer >= bufferLength) { fixMJPG = false; if (len-nBytes > 0) nBytes += rFile.read(b, off+nBytes, len-nBytes); } } else nBytes = rFile.read(b, off, len); readableSize -= nBytes; return nBytes; } // Add Huffman table if not present yet private void addHuffmanTables() { if (readShort(0)!=0xffd8 || bufferLength<6) return; //not a start of JPEG-like data int offset = 2; int segmentLength = 0; do { int code = readShort(offset); //read segment type //IJ.log("code=0x"+Long.toHexString(code)); if (code==0xffc4) //Huffman table found, nothing to do return; else if (code==0xffda || code==0xffd9) { //start of image data or end of image? insertHuffmanTables(offset); return; //finished } offset += 2; segmentLength = readShort(offset); //read length of this segment offset += segmentLength; //and skip the segment contents } while (offset<bufferLength-4 && segmentLength>=0); } // read a short from the buffer private int readShort(int offset) { return ((buffer[offset]&0xff)<<8) | (buffer[offset+1]&0xff); } // insert Huffman tables at the given position private void insertHuffmanTables(int position) { //IJ.log("inserting Huffman tables"); System.arraycopy(buffer, position, buffer, position+HUFFMAN_LENGTH, bufferLength-position); System.arraycopy(HUFFMAN_TABLES, 0, buffer, position, HUFFMAN_LENGTH); bufferLength += HUFFMAN_LENGTH; readableSize += HUFFMAN_LENGTH; } } public void displayDialog(boolean displayDialog) { this.displayDialog = displayDialog; } }
43.250159
155
0.68191
6c9607e7ea9e7368220a3dcdca4d07fa45d6e25c
14,544
/* * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.beans.decoder; import com.sun.beans.finder.ClassFinder; import java.beans.ExceptionListener; import java.io.IOException; import java.io.StringReader; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import jdk.internal.misc.SharedSecrets; /** * The main class to parse JavaBeans XML archive. * * @since 1.7 * * @author Sergey A. Malenkov * * @see ElementHandler */ public final class DocumentHandler extends DefaultHandler { private final AccessControlContext acc = AccessController.getContext(); private final Map<String, Class<? extends ElementHandler>> handlers = new HashMap<>(); private final Map<String, Object> environment = new HashMap<>(); private final List<Object> objects = new ArrayList<>(); private Reference<ClassLoader> loader; private ExceptionListener listener; private Object owner; private ElementHandler handler; /** * Creates new instance of document handler. */ public DocumentHandler() { setElementHandler("java", JavaElementHandler.class); // NON-NLS: the element name setElementHandler("null", NullElementHandler.class); // NON-NLS: the element name setElementHandler("array", ArrayElementHandler.class); // NON-NLS: the element name setElementHandler("class", ClassElementHandler.class); // NON-NLS: the element name setElementHandler("string", StringElementHandler.class); // NON-NLS: the element name setElementHandler("object", ObjectElementHandler.class); // NON-NLS: the element name setElementHandler("void", VoidElementHandler.class); // NON-NLS: the element name setElementHandler("char", CharElementHandler.class); // NON-NLS: the element name setElementHandler("byte", ByteElementHandler.class); // NON-NLS: the element name setElementHandler("short", ShortElementHandler.class); // NON-NLS: the element name setElementHandler("int", IntElementHandler.class); // NON-NLS: the element name setElementHandler("long", LongElementHandler.class); // NON-NLS: the element name setElementHandler("float", FloatElementHandler.class); // NON-NLS: the element name setElementHandler("double", DoubleElementHandler.class); // NON-NLS: the element name setElementHandler("boolean", BooleanElementHandler.class); // NON-NLS: the element name // some handlers for new elements setElementHandler("new", NewElementHandler.class); // NON-NLS: the element name setElementHandler("var", VarElementHandler.class); // NON-NLS: the element name setElementHandler("true", TrueElementHandler.class); // NON-NLS: the element name setElementHandler("false", FalseElementHandler.class); // NON-NLS: the element name setElementHandler("field", FieldElementHandler.class); // NON-NLS: the element name setElementHandler("method", MethodElementHandler.class); // NON-NLS: the element name setElementHandler("property", PropertyElementHandler.class); // NON-NLS: the element name } /** * Returns the class loader used to instantiate objects. * If the class loader has not been explicitly set * then {@code null} is returned. * * @return the class loader used to instantiate objects */ public ClassLoader getClassLoader() { return (this.loader != null) ? this.loader.get() : null; } /** * Sets the class loader used to instantiate objects. * If the class loader is not set * then default class loader will be used. * * @param loader a classloader to use */ public void setClassLoader(ClassLoader loader) { this.loader = new WeakReference<ClassLoader>(loader); } /** * Returns the exception listener for parsing. * The exception listener is notified * when handler catches recoverable exceptions. * If the exception listener has not been explicitly set * then default exception listener is returned. * * @return the exception listener for parsing */ public ExceptionListener getExceptionListener() { return this.listener; } /** * Sets the exception listener for parsing. * The exception listener is notified * when handler catches recoverable exceptions. * * @param listener the exception listener for parsing */ public void setExceptionListener(ExceptionListener listener) { this.listener = listener; } /** * Returns the owner of this document handler. * * @return the owner of this document handler */ public Object getOwner() { return this.owner; } /** * Sets the owner of this document handler. * * @param owner the owner of this document handler */ public void setOwner(Object owner) { this.owner = owner; } /** * Returns the handler for the element with specified name. * * @param name the name of the element * @return the corresponding element handler */ public Class<? extends ElementHandler> getElementHandler(String name) { Class<? extends ElementHandler> type = this.handlers.get(name); if (type == null) { throw new IllegalArgumentException("Unsupported element: " + name); } return type; } /** * Sets the handler for the element with specified name. * * @param name the name of the element * @param handler the corresponding element handler */ public void setElementHandler(String name, Class<? extends ElementHandler> handler) { this.handlers.put(name, handler); } /** * Indicates whether the variable with specified identifier is defined. * * @param id the identifier * @return @{code true} if the variable is defined; * @{code false} otherwise */ public boolean hasVariable(String id) { return this.environment.containsKey(id); } /** * Returns the value of the variable with specified identifier. * * @param id the identifier * @return the value of the variable */ public Object getVariable(String id) { if (!this.environment.containsKey(id)) { throw new IllegalArgumentException("Unbound variable: " + id); } return this.environment.get(id); } /** * Sets new value of the variable with specified identifier. * * @param id the identifier * @param value new value of the variable */ public void setVariable(String id, Object value) { this.environment.put(id, value); } /** * Returns the array of readed objects. * * @return the array of readed objects */ public Object[] getObjects() { return this.objects.toArray(); } /** * Adds the object to the list of readed objects. * * @param object the object that is readed from XML document */ void addObject(Object object) { this.objects.add(object); } /** * Disables any external entities. */ @Override public InputSource resolveEntity(String publicId, String systemId) { return new InputSource(new StringReader("")); } /** * Prepares this handler to read objects from XML document. */ @Override public void startDocument() { this.objects.clear(); this.handler = null; } /** * Parses opening tag of XML element * using corresponding element handler. * * @param uri the namespace URI, or the empty string * if the element has no namespace URI or * if namespace processing is not being performed * @param localName the local name (without prefix), or the empty string * if namespace processing is not being performed * @param qName the qualified name (with prefix), or the empty string * if qualified names are not available * @param attributes the attributes attached to the element */ @Override @SuppressWarnings("deprecation") public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { ElementHandler parent = this.handler; try { this.handler = getElementHandler(qName).newInstance(); this.handler.setOwner(this); this.handler.setParent(parent); } catch (Exception exception) { throw new SAXException(exception); } for (int i = 0; i < attributes.getLength(); i++) try { String name = attributes.getQName(i); String value = attributes.getValue(i); this.handler.addAttribute(name, value); } catch (RuntimeException exception) { handleException(exception); } this.handler.startElement(); } /** * Parses closing tag of XML element * using corresponding element handler. * * @param uri the namespace URI, or the empty string * if the element has no namespace URI or * if namespace processing is not being performed * @param localName the local name (without prefix), or the empty string * if namespace processing is not being performed * @param qName the qualified name (with prefix), or the empty string * if qualified names are not available */ @Override public void endElement(String uri, String localName, String qName) { try { this.handler.endElement(); } catch (RuntimeException exception) { handleException(exception); } finally { this.handler = this.handler.getParent(); } } /** * Parses character data inside XML element. * * @param chars the array of characters * @param start the start position in the character array * @param length the number of characters to use */ @Override public void characters(char[] chars, int start, int length) { if (this.handler != null) { try { while (0 < length--) { this.handler.addCharacter(chars[start++]); } } catch (RuntimeException exception) { handleException(exception); } } } /** * Handles an exception using current exception listener. * * @param exception an exception to handle * @see #setExceptionListener */ public void handleException(Exception exception) { if (this.listener == null) { throw new IllegalStateException(exception); } this.listener.exceptionThrown(exception); } /** * Starts parsing of the specified input source. * * @param input the input source to parse */ public void parse(final InputSource input) { if ((this.acc == null) && (null != System.getSecurityManager())) { throw new SecurityException("AccessControlContext is not set"); } AccessControlContext stack = AccessController.getContext(); SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Void>() { public Void run() { try { SAXParserFactory.newInstance().newSAXParser().parse(input, DocumentHandler.this); } catch (ParserConfigurationException exception) { handleException(exception); } catch (SAXException wrapper) { Exception exception = wrapper.getException(); if (exception == null) { exception = wrapper; } handleException(exception); } catch (IOException exception) { handleException(exception); } return null; } }, stack, this.acc); } /** * Resolves class by name using current class loader. * This method handles exception using current exception listener. * * @param name the name of the class * @return the object that represents the class */ public Class<?> findClass(String name) { try { return ClassFinder.resolveClass(name, getClassLoader()); } catch (ClassNotFoundException exception) { handleException(exception); return null; } } }
35.130435
117
0.633113
7cf3c1861616e7c78bcd741f8656aabad05a7646
236
package problem_001; public class Problem_001 { public static void main(String []args) { int sum = 0; for(int i = 1; i < 1000; i++) sum += (i % 3 ==0 || i % 5 == 0) ? i : 0; System.out.print(sum); //233168 } }
21.454545
45
0.529661
1f7a5d36454e2a9d905c08753e02c87553d1f522
620
package io.github.ust.mico.readandforward; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; @Component @Slf4j public class Sender { @Autowired private KafkaTemplate<String, String> kafkaTemplate; @Value("${kafka.output-topic}") private String topic; public void send(String message) { log.info("sending msg:'{}' to topic:'{}'", message, topic); kafkaTemplate.send(topic, message); } }
24.8
63
0.766129
6ce2213387bf35f768e4a14b0fcd775a90580b55
1,213
package org.jeecg.modules.cable.mapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Param; import org.jeecg.modules.cable.entity.Inventory; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.jeecg.modules.cable.vo.InventoryListVo; import org.jeecg.modules.cable.vo.InventoryListsVo; import org.jeecg.modules.cable.vo.InventoryVo; import org.jeecg.modules.cable.vo.YikuVo; import java.util.List; /** * @Description: 库存表 * @Author: jeecg-boot * @Date: 2020-05-22 * @Version: V1.0 */ public interface InventoryMapper extends BaseMapper<Inventory> { /** * 根据仓库id和库位id查当前库位存放的物品(分页) * * @param inventoryVo * @param page * @Author Xm * @Date 2020/5/22 15:35 */ List<InventoryListsVo> InsurancePageList(@Param("inventoryVo") InventoryListsVo inventoryVo, @Param("page") Page<InventoryListsVo> page); List<InventoryListsVo> InsurancePageList(@Param("storageLocationId") Integer storageLocationId); List<YikuVo> yikuVoPage(@Param("yikuVo") YikuVo yikuVo, @Param("page") Page<YikuVo> page); void yikuDel(@Param("id") Integer id); void yikuAdd(@Param("val") YikuVo yikuVo); }
30.325
141
0.736191
717575529f2e8f3e00bd56e09eed4617ff1c68cc
2,285
package org.broadinstitute.hellbender.engine.spark.datasources; import htsjdk.variant.variantcontext.VariantContext; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.LongWritable; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.broadinstitute.hellbender.exceptions.GATKException; import org.broadinstitute.hellbender.utils.variant.Variant; import org.broadinstitute.hellbender.utils.variant.VariantContextVariantAdapter; import org.seqdoop.hadoop_bam.VCFInputFormat; import org.seqdoop.hadoop_bam.VariantContextWritable; import java.util.List; /** * VariantsSparkSource loads Variants from files serially (using FeatureDataSource<VariantContext>) or in parallel * using Hadoop-BAM. */ public final class VariantsSparkSource { private final JavaSparkContext ctx; public VariantsSparkSource(JavaSparkContext ctx) { this.ctx = ctx; } /** * Loads variants in parallel using Hadoop-BAM works for vcfs and bcfs. * @param vcfs files to load variants from. * @return JavaRDD<Variant> of variants from all files. */ public JavaRDD<Variant> getParallelVariants(final List<String> vcfs) { JavaRDD<Variant> rddVariants = ctx.emptyRDD(); for (String vcf : vcfs) { JavaRDD<Variant> variants = getParallelVariants(vcf); rddVariants.union(variants); } return rddVariants; } /** * Loads variants in parallel using Hadoop-BAM for vcfs and bcfs. * @param vcf file to load variants from. * @return JavaRDD<Variant> of variants from all files. */ public JavaRDD<Variant> getParallelVariants(final String vcf) { JavaPairRDD<LongWritable, VariantContextWritable> rdd2 = ctx.newAPIHadoopFile( vcf, VCFInputFormat.class, LongWritable.class, VariantContextWritable.class, new Configuration()); return rdd2.map(v1 -> { VariantContext variant = v1._2().get(); if (variant.getCommonInfo() == null) { throw new GATKException("no common info"); } return VariantContextVariantAdapter.sparkVariantAdapter(variant); }); } }
38.083333
114
0.709847
e1f1f1f7bc9f855e198fcec0ebc9648c9015a869
3,408
package es.codeurjc.gp_rest.objects; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; @Entity public class User { //#region Variables @Id @GeneratedValue(strategy = GenerationType.AUTO) int id; String name; String password; private String role; @OneToOne(cascade=CascadeType.ALL) CustomList<ForumEntry> forumEntries; @OneToOne(cascade=CascadeType.ALL) CustomList<Comment> comments; @OneToOne(cascade=CascadeType.ALL) CustomList<Game> games; @OneToMany(cascade=CascadeType.ALL) List<Notification> notifications; @OneToMany(mappedBy="user", cascade=CascadeType.ALL) List<CustomList<ListElement>> myLists; //#endregion //#region Constructor public User() {} public User(String name, String password, String role){ this.name = name; this.password = password; this.role = role; this.forumEntries = new CustomList<ForumEntry>("[ForumEntries]", this); this.comments = new CustomList<Comment>("[Comments]", this); this.games = new CustomList<Game>("[Games]", this); this.notifications = new ArrayList<Notification>(); this.myLists = new ArrayList<CustomList<ListElement>>(); } //#endregion //#region Getters&Setters public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; //TODO: Store the password hashed. } public void setPassword(String password) { this.password = password; } public String getRole(){ return role; } public CustomList<ForumEntry> getForumEntries() { return forumEntries; } public void followForumEntry(ForumEntry fe){ forumEntries.addElement(fe); } public CustomList<Comment> getComments() { return comments; } public void followComment(Comment c){ comments.addElement(c); } public CustomList<Game> getGames() { return games; } public void followGame(Game game){ games.addElement(game); } public List<Notification> getNotifications() { return notifications; } public List<CustomList<ListElement>> getMyLists() { return myLists; } //#endregion //#region Object management Methods public boolean addNotification(Notification notification) { return this.notifications.add(notification); } public Notification getNotification(int index){ return this.notifications.get(index); } public boolean removeNotification(Notification notification){ return this.notifications.remove(notification); } public boolean addMyList(CustomList<ListElement> myList) { return this.myLists.add(myList); } public CustomList<ListElement> getMyList(int index){ return this.myLists.get(index); } public boolean removeMyList(CustomList<ListElement> myList){ return this.myLists.remove(myList); } //#endregion }
24.342857
99
0.664613
22cbf47556ec4b30dd024d1ce7388526e1e8782d
1,875
/* * Copyright by Zoltán Cseresnyés, Ruman Gerst * * Research Group Applied Systems Biology - Head: Prof. Dr. Marc Thilo Figge * https://www.leibniz-hki.de/en/applied-systems-biology.html * HKI-Center for Systems Biology of Infection * Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Institute (HKI) * Adolf-Reichwein-Straße 23, 07745 Jena, Germany * * The project code is licensed under BSD 2-Clause. * See the LICENSE file provided with the code for the full license. */ package org.hkijena.jipipe.extensions.parameters.library.pairs; import org.hkijena.jipipe.extensions.parameters.api.collections.ListParameter; import org.hkijena.jipipe.extensions.parameters.api.pairs.PairParameter; /** * A parameter that renames an integer into another integer */ public class DoubleAndDoublePairParameter extends PairParameter<Double, Double> { /** * Creates a new instance */ public DoubleAndDoublePairParameter() { super(Double.class, Double.class); } /** * Creates a copy * * @param other the original */ public DoubleAndDoublePairParameter(DoubleAndDoublePairParameter other) { super(other); } /** * A collection of multiple {@link DoubleAndDoublePairParameter} */ public static class List extends ListParameter<DoubleAndDoublePairParameter> { /** * Creates a new instance */ public List() { super(DoubleAndDoublePairParameter.class); } /** * Creates a copy * * @param other the original */ public List(List other) { super(DoubleAndDoublePairParameter.class); for (DoubleAndDoublePairParameter filter : other) { add(new DoubleAndDoublePairParameter(filter)); } } } }
29.296875
100
0.665067
b080c445498101b1499d297adf86c2a922c8f0bc
520
package com.example.server; import lombok.extern.log4j.Log4j2; import org.springframework.messaging.handler.annotation.MessageMapping; import reactor.core.publisher.Flux; import java.time.Duration; /** * @author cui */ @Log4j2 public class KeeperHandler { @MessageMapping("client-status") public Flux<String> statusUpdate(String status) { log.info("Connection {}", status); return Flux.interval(Duration.ofSeconds(5)).map(index -> String.valueOf(Runtime.getRuntime().freeMemory())); } }
26
116
0.730769
ee70b90595ed8c2e516b9e89ad4a1342874133bb
8,441
package org.apache.log4j; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.helpers.AppenderAttachableImpl; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.AppenderAttachable; import org.apache.log4j.spi.LoggingEvent; public class AsyncAppender extends AppenderSkeleton implements AppenderAttachable { public static final int DEFAULT_BUFFER_SIZE = 128; private final List buffer = new ArrayList(); private final Map discardMap = new HashMap(); private int bufferSize = 128; AppenderAttachableImpl aai; private final AppenderAttachableImpl appenders = new AppenderAttachableImpl(); private final Thread dispatcher; private boolean locationInfo = false; private boolean blocking = true; public AsyncAppender() { this.aai = this.appenders; this.dispatcher = new Thread(new AsyncAppender.Dispatcher(this, this.buffer, this.discardMap, this.appenders)); this.dispatcher.setDaemon(true); this.dispatcher.setName("AsyncAppender-Dispatcher-" + this.dispatcher.getName()); this.dispatcher.start(); } public void addAppender(Appender newAppender) { synchronized(this.appenders) { this.appenders.addAppender(newAppender); } } public void append(LoggingEvent event) { if (this.dispatcher != null && this.dispatcher.isAlive() && this.bufferSize > 0) { event.getNDC(); event.getThreadName(); event.getMDCCopy(); if (this.locationInfo) { event.getLocationInformation(); } event.getRenderedMessage(); event.getThrowableStrRep(); synchronized(this.buffer) { while(true) { int previousSize = this.buffer.size(); if (previousSize < this.bufferSize) { this.buffer.add(event); if (previousSize == 0) { this.buffer.notifyAll(); } break; } boolean discard = true; if (this.blocking && !Thread.interrupted() && Thread.currentThread() != this.dispatcher) { try { this.buffer.wait(); discard = false; } catch (InterruptedException var8) { Thread.currentThread().interrupt(); } } if (discard) { String loggerName = event.getLoggerName(); AsyncAppender.DiscardSummary summary = (AsyncAppender.DiscardSummary)this.discardMap.get(loggerName); if (summary == null) { summary = new AsyncAppender.DiscardSummary(event); this.discardMap.put(loggerName, summary); } else { summary.add(event); } break; } } } } else { synchronized(this.appenders) { this.appenders.appendLoopOnAppenders(event); } } } public void close() { synchronized(this.buffer) { this.closed = true; this.buffer.notifyAll(); } try { this.dispatcher.join(); } catch (InterruptedException var5) { Thread.currentThread().interrupt(); LogLog.error("Got an InterruptedException while waiting for the dispatcher to finish.", var5); } synchronized(this.appenders) { Enumeration iter = this.appenders.getAllAppenders(); if (iter != null) { while(iter.hasMoreElements()) { Object next = iter.nextElement(); if (next instanceof Appender) { ((Appender)next).close(); } } } } } public Enumeration getAllAppenders() { synchronized(this.appenders) { return this.appenders.getAllAppenders(); } } public Appender getAppender(String name) { synchronized(this.appenders) { return this.appenders.getAppender(name); } } public boolean getLocationInfo() { return this.locationInfo; } public boolean isAttached(Appender appender) { synchronized(this.appenders) { return this.appenders.isAttached(appender); } } public boolean requiresLayout() { return false; } public void removeAllAppenders() { synchronized(this.appenders) { this.appenders.removeAllAppenders(); } } public void removeAppender(Appender appender) { synchronized(this.appenders) { this.appenders.removeAppender(appender); } } public void removeAppender(String name) { synchronized(this.appenders) { this.appenders.removeAppender(name); } } public void setLocationInfo(boolean flag) { this.locationInfo = flag; } public void setBufferSize(int size) { if (size < 0) { throw new NegativeArraySizeException("size"); } else { synchronized(this.buffer) { this.bufferSize = size < 1 ? 1 : size; this.buffer.notifyAll(); } } } public int getBufferSize() { return this.bufferSize; } public void setBlocking(boolean value) { synchronized(this.buffer) { this.blocking = value; this.buffer.notifyAll(); } } public boolean getBlocking() { return this.blocking; } private static class Dispatcher implements Runnable { private final AsyncAppender parent; private final List buffer; private final Map discardMap; private final AppenderAttachableImpl appenders; public Dispatcher(AsyncAppender parent, List buffer, Map discardMap, AppenderAttachableImpl appenders) { this.parent = parent; this.buffer = buffer; this.appenders = appenders; this.discardMap = discardMap; } public void run() { boolean isActive = true; try { while(isActive) { LoggingEvent[] events = null; synchronized(this.buffer) { int bufferSize = this.buffer.size(); for(isActive = !this.parent.closed; bufferSize == 0 && isActive; isActive = !this.parent.closed) { this.buffer.wait(); bufferSize = this.buffer.size(); } if (bufferSize > 0) { events = new LoggingEvent[bufferSize + this.discardMap.size()]; this.buffer.toArray(events); int index = bufferSize; for(Iterator iter = this.discardMap.values().iterator(); iter.hasNext(); events[index++] = ((AsyncAppender.DiscardSummary)iter.next()).createEvent()) { } this.buffer.clear(); this.discardMap.clear(); this.buffer.notifyAll(); } } if (events != null) { for(int i = 0; i < events.length; ++i) { synchronized(this.appenders) { this.appenders.appendLoopOnAppenders(events[i]); } } } } } catch (InterruptedException var11) { Thread.currentThread().interrupt(); } } } private static final class DiscardSummary { private LoggingEvent maxEvent; private int count; public DiscardSummary(LoggingEvent event) { this.maxEvent = event; this.count = 1; } public void add(LoggingEvent event) { if (event.getLevel().toInt() > this.maxEvent.getLevel().toInt()) { this.maxEvent = event; } ++this.count; } public LoggingEvent createEvent() { String msg = MessageFormat.format("Discarded {0} messages due to full event buffer including: {1}", new Integer(this.count), this.maxEvent.getMessage()); return new LoggingEvent("org.apache.log4j.AsyncAppender.DONT_REPORT_LOCATION", Logger.getLogger(this.maxEvent.getLoggerName()), this.maxEvent.getLevel(), msg, (Throwable)null); } } }
30.919414
185
0.573747
ead8d9f375c766377cbdad9a47b10461eb97a124
2,030
package com.revolsys.raster; import org.jeometry.common.data.type.DataType; public abstract class AbstractBand implements Band { private DataType dataType; private int height; private int width; @Override public byte getByte(final double x, final double y) { // TODO Auto-generated method stub return 0; } @Override public byte getByte(final int columnIndex, final int rowIndex) { return (byte)getLong(columnIndex, rowIndex); } @Override public DataType getDataType() { return this.dataType; } @Override public double getDouble(final double x, final double y) { // TODO Auto-generated method stub return 0; } @Override public double getDouble(final int columnIndex, final int rowIndex) { final long value = getLong(columnIndex, rowIndex); return Double.longBitsToDouble(value); } @Override public float getFloat(final double x, final double y) { return 0; } @Override public float getFloat(final int columnIndex, final int rowIndex) { final int value = getInt(columnIndex, rowIndex); return Float.intBitsToFloat(value); } @Override public int getHeight() { return this.height; } @Override public int getInt(final double x, final double y) { return 0; } @Override public int getInt(final int columnIndex, final int rowIndex) { return (int)getLong(columnIndex, rowIndex); } @Override public long getLong(final double x, final double y) { return 0; } @Override public long getLong(final int columnIndex, final int rowIndex) { return 0; } @Override public Band getOverview(final int index) { return null; } @Override public int getOverviewCount() { return 0; } @Override public short getShort(final double x, final double y) { return 0; } @Override public short getShort(final int columnIndex, final int rowIndex) { return (short)getLong(columnIndex, rowIndex); } @Override public int getWidth() { return this.width; } }
20.09901
70
0.692118
55054f42f5c7279e01468ae58d6ab6e3a263ddff
1,472
package bungee.vaccum.module.teamchat; import bungee.vaccum.api.vBungeeAPI; import bungee.vaccum.module.teamchat.commands.TeamChatCommand; import bungee.vaccum.module.teamchat.listener.JoinListener; import net.md_5.bungee.api.plugin.Plugin; import java.io.IOException; import java.util.ArrayList; import java.util.UUID; import java.util.concurrent.TimeUnit; public final class TeamChat extends Plugin { private static TeamChat instance; private vBungeeAPI bungeeAPI; private ArrayList<UUID> teamChatList; public static String prefix = "§7» §9TeamChat §8| §7"; @Override public void onEnable() { // Plugin startup logic instance = this; bungeeAPI = vBungeeAPI.getInstance(); getProxy().getPluginManager().registerCommand(this, new TeamChatCommand("teamchat")); getProxy().getPluginManager().registerCommand(this, new TeamChatCommand("tc")); getProxy().getPluginManager().registerListener(this, new JoinListener()); getProxy().getConsole().sendMessage("§7[" + getDescription().getName() + "] Loading..."); getProxy().getConsole().sendMessage("§7[" + getDescription().getName() + "] Successfully version " + getDescription().getVersion() + " loaded"); } @Override public void onDisable() { // Plugin shutdown logic } public static TeamChat getInstance() { return instance; } public vBungeeAPI getBungeeAPI() { return bungeeAPI; } }
32
152
0.699728
4d12f977b1bf502ebe5e1eba72f3ba72ffe90fce
5,141
public void run() { Socket s = null; OutputStream out = null; DataInputStream in = null; try { int count = 0; while (count < 3) { count++; int portAsInt = 0; try { portAsInt = Integer.parseInt(port); } catch (NumberFormatException ee) { throw new Exception("NscaSend.send_nsca(): port was malformed: " + port); } s = new Socket(); s.setKeepAlive(true); s.setSoTimeout(timeout); s.setTcpNoDelay(false); java.net.InetSocketAddress socketAddress = new InetSocketAddress(host, portAsInt); s.connect(socketAddress); if (s.isBound()) break; else { try { s.close(); } catch (Exception e) { } s = null; } } out = s.getOutputStream(); in = new DataInputStream(s.getInputStream()); byte[] received_iv = new byte[128]; in.readFully(received_iv, 0, 128); int time = in.readInt(); String temp; byte[] host_name = new byte[64]; temp = (null == reportingHost) ? "UNKNOWN" : reportingHost; System.arraycopy(temp.getBytes(), 0, host_name, 0, temp.getBytes().length); byte[] service_name = new byte[128]; temp = (null == reportingService) ? "UNKNOWN" : reportingService; System.arraycopy(temp.getBytes(), 0, service_name, 0, temp.getBytes().length); byte[] plugin_output = new byte[512]; message.replaceAll("\n", "<linefeed>"); if ((null != message) && (message.getBytes().length <= 512)) { System.arraycopy(message.getBytes(), 0, plugin_output, 0, message.getBytes().length); } else if (null != message) { System.arraycopy(message.getBytes(), 0, plugin_output, 0, plugin_output.length); } else { System.arraycopy("<null>".getBytes(), 0, plugin_output, 0, plugin_output.length); } int alert_size = 4 + 4 + 4 + 4 + host_name.length + service_name.length + plugin_output.length; byte[] alert = new byte[alert_size]; alert[0] = (byte) ((nsca_version >> 8) & 0xff); alert[1] = (byte) (nsca_version & 0xff); alert[4] = (byte) ((0 >> 24) & 0xff); alert[5] = (byte) ((0 >> 16) & 0xff); alert[6] = (byte) ((0 >> 8) & 0xff); alert[7] = (byte) (0 & 0xff); alert[8] = (byte) ((time >> 24) & 0xff); alert[9] = (byte) ((time >> 16) & 0xff); alert[10] = (byte) ((time >> 8) & 0xff); alert[11] = (byte) (time & 0xff); alert[12] = (byte) ((return_code >> 8) & 0xff); alert[13] = (byte) (return_code & 0xff); int offset = 14; System.arraycopy(host_name, 0, alert, offset, host_name.length); offset += host_name.length; System.arraycopy(service_name, 0, alert, offset, service_name.length); offset += service_name.length; System.arraycopy(plugin_output, 0, alert, offset, plugin_output.length); offset += plugin_output.length; CRC32 crc = new CRC32(); crc.update(alert); long crc_value = crc.getValue(); alert[4] = (byte) ((crc_value >> 24) & 0xff); alert[5] = (byte) ((crc_value >> 16) & 0xff); alert[6] = (byte) ((crc_value >> 8) & 0xff); alert[7] = (byte) (crc_value & 0xff); encrypt_buffer(encryption_method, alert, received_iv); out.write(alert, 0, alert.length); out.flush(); out.close(); out = null; in.close(); in = null; s.close(); s = null; finished = true; } catch (Exception e) { } finally { if (null != out) { try { out.close(); } catch (Exception ee) { } } if (null != out) { try { in.close(); } catch (Exception ee) { } } if (null != s) { try { s.close(); } catch (Exception ee) { } } synchronized (this) { notifyAll(); } } }
45.495575
111
0.414705
1cda4c4b338bc9e2130b2bd3a6089bfa8b95f91a
57
package dsa.container; public class ContainerTestFX { }
11.4
30
0.789474
8bcb0a50ce4be7bc8ba39b5777d17360ab4d6435
8,620
/******************************************************************************* * ___ _ ____ ____ * / _ \ _ _ ___ ___| |_| _ \| __ ) * | | | | | | |/ _ \/ __| __| | | | _ \ * | |_| | |_| | __/\__ \ |_| |_| | |_) | * \__\_\\__,_|\___||___/\__|____/|____/ * * Copyright (c) 2014-2019 Appsicle * Copyright (c) 2019-2020 QuestDB * * 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.questdb.griffin.model; import io.questdb.griffin.OperatorExpression; import io.questdb.std.*; import io.questdb.std.str.CharSink; public class ExpressionNode implements Mutable, Sinkable { public final static ExpressionNodeFactory FACTORY = new ExpressionNodeFactory(); public static final int OPERATION = 1; public static final int CONSTANT = 2; public static final int LITERAL = 4; public static final int MEMBER_ACCESS = 5; public static final int BIND_VARIABLE = 6; public static final int FUNCTION = 8; public static final int ARRAY_ACCESS = 9; public static final int CONTROL = 16; public static final int SET_OPERATION = 32; public static final int QUERY = 65; public static final int UNKNOWN = 0; public final ObjList<ExpressionNode> args = new ObjList<>(4); public CharSequence token; public QueryModel queryModel; public int precedence; public int position; public ExpressionNode lhs; public ExpressionNode rhs; public int type; public int paramCount; public int intrinsicValue = IntrinsicModel.UNDEFINED; public boolean innerPredicate = false; private ExpressionNode() { } public static boolean compareNodesExact(ExpressionNode a, ExpressionNode b) { if (a == null && b == null) { return true; } if (a == null || b == null || a.type != b.type) { return false; } return Chars.equals(a.token, b.token) && compareArgsExact(a, b); } public static boolean compareNodesGroupBy( ExpressionNode groupByExpr, ExpressionNode columnExpr, QueryModel translatingModel ) { if (groupByExpr == null && columnExpr == null) { return true; } if (groupByExpr == null || columnExpr == null || groupByExpr.type != columnExpr.type) { return false; } if (!Chars.equals(groupByExpr.token, columnExpr.token)) { int index = translatingModel.getAliasToColumnMap().keyIndex(columnExpr.token); if (index > -1) { return false; } final QueryColumn qc = translatingModel.getAliasToColumnMap().valueAt(index); final CharSequence tok = groupByExpr.token; final CharSequence qcTok = qc.getAst().token; if (Chars.equals(qcTok, tok)) { return true; } int dot = Chars.indexOf(tok, '.'); if (dot > -1 && translatingModel.getAliasIndex(tok, 0, dot) > -1 && Chars.equals(qcTok, tok, dot + 1, tok.length()) ) { return compareArgs(groupByExpr, columnExpr, translatingModel); } return false; } return compareArgs(groupByExpr, columnExpr, translatingModel); } public void clear() { args.clear(); token = null; precedence = 0; position = 0; lhs = null; rhs = null; type = UNKNOWN; paramCount = 0; intrinsicValue = IntrinsicModel.UNDEFINED; queryModel = null; innerPredicate = false; } public ExpressionNode of(int type, CharSequence token, int precedence, int position) { clear(); // override literal with bind variable if (type == LITERAL && token != null && (token.charAt(0) == '$' || token.charAt(0) == ':')) { this.type = BIND_VARIABLE; } else { this.type = type; } this.precedence = precedence; this.token = token; this.position = position; return this; } @Override public void toSink(CharSink sink) { switch (paramCount) { case 0: if (queryModel != null) { sink.put('(').put(queryModel).put(')'); } else { sink.put(token); if (type == FUNCTION) { sink.put("()"); } } break; case 1: sink.put(token); sink.put('('); rhs.toSink(sink); sink.put(')'); break; case 2: if (OperatorExpression.isOperator(token)) { lhs.toSink(sink); sink.put(' '); sink.put(token); sink.put(' '); rhs.toSink(sink); } else { sink.put(token); sink.put('('); lhs.toSink(sink); sink.put(','); rhs.toSink(sink); sink.put(')'); } break; default: int n = args.size(); if (OperatorExpression.isOperator(token) && n > 0) { // special case for "in" args.getQuick(n - 1).toSink(sink); sink.put(' '); sink.put(token); sink.put(' '); sink.put('('); for (int i = n - 2; i > -1; i--) { if (i < n - 2) { sink.put(','); } args.getQuick(i).toSink(sink); } sink.put(')'); } else { sink.put(token); sink.put('('); for (int i = n - 1; i > -1; i--) { if (i < n - 1) { sink.put(','); } args.getQuick(i).toSink(sink); } sink.put(')'); } break; } } private static boolean compareArgs( ExpressionNode groupByExpr, ExpressionNode columnExpr, QueryModel translatingModel ) { final int groupByArgsSize = groupByExpr.args.size(); final int selectNodeArgsSize = columnExpr.args.size(); if (groupByArgsSize != selectNodeArgsSize) { return false; } if (groupByArgsSize < 3) { return compareNodesGroupBy(groupByExpr.lhs, columnExpr.lhs, translatingModel) && compareNodesGroupBy(groupByExpr.rhs, columnExpr.rhs, translatingModel); } for (int i = 0; i < groupByArgsSize; i++) { if (!compareNodesGroupBy(groupByExpr.args.get(i), columnExpr.args.get(i), translatingModel)) { return false; } } return true; } private static boolean compareArgsExact(ExpressionNode a, ExpressionNode b) { final int groupByArgsSize = a.args.size(); final int selectNodeArgsSize = b.args.size(); if (groupByArgsSize != selectNodeArgsSize) { return false; } if (groupByArgsSize < 3) { return compareNodesExact(a.lhs, b.lhs) && compareNodesExact(a.rhs, b.rhs); } for (int i = 0; i < groupByArgsSize; i++) { if (!compareNodesExact(a.args.get(i), b.args.get(i))) { return false; } } return true; } public static final class ExpressionNodeFactory implements ObjectFactory<ExpressionNode> { @Override public ExpressionNode newInstance() { return new ExpressionNode(); } } }
33.281853
106
0.501624
1f769eaccf8cedbde0bcf7fc8b03bf04759ea7a2
930
package org.symphonyoss.symphony.apps.authentication.spring.configuration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.symphonyoss.symphony.apps.authentication.keystore.KeystoreProvider; import org.symphonyoss.symphony.apps.authentication.spring.keystore.EnvKeystoreProvider; /** * Spring Configuration to create application keystore provider. * * Created by rsanchez on 08/03/18. */ @Configuration @ConditionalOnProperty(name = "app-authentication.api.enabled", havingValue = "true") public class KeystoreProviderConfiguration { @Bean @ConditionalOnMissingBean(KeystoreProvider.class) public KeystoreProvider keystoreProvider() { return new EnvKeystoreProvider(); } }
35.769231
88
0.831183
7dbd7ffae6f7b97643d8679befd6afb3fc6100a4
844
package ultimategdbot.guildsettings; import sx.blah.discord.handle.obj.IGuild; import sx.blah.discord.handle.obj.IRole; import ultimategdbot.exceptions.InvalidValueException; import ultimategdbot.util.AppTools; /** * Guild setting which value is a Discord role * * @author Alex1304 * */ public abstract class RoleSetting extends GuildSetting<IRole> { public RoleSetting(IGuild guild, String info, IRole value) { super(guild, info, value); } @Override public String valueToString() { if (value == null) return super.valueToString(); return "@" + value.getName(); } @Override public IRole parseValue(String valueStr) throws InvalidValueException { IRole role = AppTools.stringToRole(valueStr, guild); if (role == null) throw new InvalidValueException("This role couldn't be found."); return role; } }
22.210526
72
0.735782
819f404586e724ffbaf65b6428d618e7fe0eb609
484
package br.com.otavio.data.analysis.entity; import java.math.BigDecimal; public class SaleItem { private final String id; private final int quantity; private final BigDecimal price; public SaleItem(final String id, final int quantity, final BigDecimal price) { this.id = id; this.quantity = quantity; this.price = price; } public String getId() { return id; } public int getQuantity() { return quantity; } public BigDecimal getPrice() { return price; } }
17.285714
79
0.719008
48b34513d5209c1b5cacb0eb0d5b530d5c936576
295
/** * Puzzle game using Java AWT * Copyright @ 2011 Trac Quang Hoa */ package hoaftq.puzzle.game; /** * Entry class of puzzle game */ public class Puzzle { public static void main(String[] args) { GameFrame gameFrame = new GameFrame(); gameFrame.setVisible(true); } }
18.4375
42
0.650847
03b9c449f6cd169c6fbcdc4a8118b041ff0c2329
2,420
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.aws.greengrass.lambdatransformer.integrationtests; import com.aws.greengrass.dependency.State; import com.aws.greengrass.lifecyclemanager.GlobalStateChangeListener; import com.aws.greengrass.lifecyclemanager.Kernel; import com.aws.greengrass.mqttclient.MqttClient; import com.aws.greengrass.testcommons.testutilities.GGServiceTestUtil; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; import java.nio.file.Path; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; public class NucleusLaunchUtils extends GGServiceTestUtil { private static final long TEST_TIME_OUT_SEC = 30L; public Kernel kernel; GlobalStateChangeListener listener; @TempDir Path rootDir; @Mock MqttClient mqttClient; public void startNucleusWithConfig(String configFile) throws InterruptedException { startNucleusWithConfig(configFile, State.RUNNING, false, false, false); } void startNucleusWithConfig(String configFile, boolean mockCloud, boolean mockDao) throws InterruptedException { startNucleusWithConfig(configFile, State.RUNNING, false, mockCloud, mockDao); } void startNucleusWithConfig(String configFile, State expectedState, boolean mockDatabase) throws InterruptedException { startNucleusWithConfig(configFile, expectedState, mockDatabase, false, true); } void startNucleusWithConfig(String configFile, State expectedState, boolean mockDatabase, boolean mockCloud, boolean mockDao) throws InterruptedException { CountDownLatch shadowManagerRunning = new CountDownLatch(1); kernel.parseArgs("-r", rootDir.toAbsolutePath().toString(), "-i", getClass().getResource(configFile).toString()); kernel.getContext().addGlobalStateChangeListener(listener); kernel.getContext().put(MqttClient.class, mqttClient); // assume we are always connected when(mqttClient.connected()).thenReturn(true); // set retry config to only try once so we can test failures earlier kernel.launch(); assertTrue(shadowManagerRunning.await(TEST_TIME_OUT_SEC, TimeUnit.SECONDS)); } }
39.672131
123
0.756198
935ce350834ccf4c577c526d8157d530d27b96c3
341
package graphics.component; import entity.Component; import math.Vector3f; import math.Vector4f; public class LineRenderComponent implements Component { public Vector3f p1, p2; public Vector4f color; public LineRenderComponent(Vector3f p1, Vector3f p2, Vector4f color) { this.p1 = p1; this.p2 = p2; this.color = color; } }
17.05
69
0.747801
bd7fec5f305938f244b4ec2067272d37ea5c11e0
725
package egovframework.com.cmm.service.impl; import egovframework.rte.psl.dataaccess.EgovAbstractMapper; import javax.annotation.Resource; import org.apache.ibatis.session.SqlSessionFactory; /** * EgovComAbstractDAO.java 클래스 * * @author 서준식 * @since 2011. 9. 23. * @version 1.0 * @see * * <pre> * << 개정이력(Modification Information) >> * * 수정일 수정자 수정내용 * ------- ------------- ---------------------- * 2011. 9. 23. 서준식 최초 생성 * </pre> */ public abstract class EgovComAbstractDAO extends EgovAbstractMapper{ @Override @Resource(name="egov.sqlSession") public void setSqlSessionFactory(SqlSessionFactory sqlSession) { super.setSqlSessionFactory(sqlSession); } }
20.714286
68
0.644138
bfc6327a72e87fef1c82fe1f5acd7392d33174d0
18,761
package hr.fer.zemris.jcms.service2.course.assessments; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import hr.fer.zemris.jcms.beans.cached.CourseScoreTable; import hr.fer.zemris.jcms.beans.cached.Dependencies; import hr.fer.zemris.jcms.beans.cached.DependencyItem; import hr.fer.zemris.jcms.beans.cached.STEFlagValue; import hr.fer.zemris.jcms.beans.cached.STEScore; import hr.fer.zemris.jcms.beans.cached.STEStudent; import hr.fer.zemris.jcms.beans.cached.STHEAssessment; import hr.fer.zemris.jcms.beans.cached.STHEFlag; import hr.fer.zemris.jcms.beans.cached.STHEStudent; import hr.fer.zemris.jcms.beans.cached.ScoreTableEntry; import hr.fer.zemris.jcms.beans.cached.ScoreTableHeaderEntry; import hr.fer.zemris.jcms.caching.JCMSCacheFactory; import hr.fer.zemris.jcms.dao.DAOHelper; import hr.fer.zemris.jcms.dao.DAOHelperFactory; import hr.fer.zemris.jcms.model.Assessment; import hr.fer.zemris.jcms.model.AssessmentFlag; import hr.fer.zemris.jcms.model.CourseInstanceKeyValue; import hr.fer.zemris.jcms.model.Grade; import hr.fer.zemris.jcms.model.GradesVisibility; import hr.fer.zemris.jcms.model.Group; import hr.fer.zemris.jcms.model.GroupOwner; import hr.fer.zemris.jcms.model.User; import hr.fer.zemris.jcms.model.UserGroup; import hr.fer.zemris.jcms.security.JCMSSecurityManagerFactory; import hr.fer.zemris.jcms.service.util.GradesUtil; import hr.fer.zemris.jcms.service.util.GroupUtil; import hr.fer.zemris.jcms.service2.course.CourseInstanceServiceSupport; import hr.fer.zemris.jcms.web.actions.data.AdminAssessmentSummaryViewData; import hr.fer.zemris.jcms.web.actions.data.StudentScoreBrowserSelectionData; import hr.fer.zemris.jcms.web.actions.data.StudentScoreBrowserSettingsData; import hr.fer.zemris.jcms.web.actions.data.support.AbstractActionData; import hr.fer.zemris.util.InputStreamWrapper; import javax.persistence.EntityManager; /** * Sloj usluge koji nudi općenito navigiranje kroz provjere, zastavice i slično. * * @author marcupic * */ public class SummaryViewService { /** * Metoda dohvaća sve provjere i zastavice i priprema ih za prikaz korisniku. * Konačni podatci pripremaju se i u JSON obliku kako bi se njima lakše manipuliralo * u JavaScript-u. * * @param em entity manager * @param data podatci */ public static void showAdminAssessmentSummaryView(EntityManager em, AdminAssessmentSummaryViewData data) { // Dohvat kolegija if(!CourseInstanceServiceSupport.fillCourseInstance(em, data, data.getCourseInstanceID())) return; boolean canView = JCMSSecurityManagerFactory.getManager().canViewAssessments(data.getCourseInstance()); if(!canView) { data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission")); data.setResult(AbstractActionData.RESULT_FATAL); return; } DAOHelper dh = DAOHelperFactory.getDAOHelper(); List<User> courseUsers = null; if(data.getSelectedGroupID()==null || data.getSelectedGroupID().longValue()==-1) { // ako moze vidjeti sve, OK, inace error if(!JCMSSecurityManagerFactory.getManager().canManageAssessments(data.getCourseInstance())) { data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission")); data.setResult(AbstractActionData.RESULT_FATAL); return; } courseUsers = dh.getCourseInstanceDAO().findCourseUsers(em, data.getCourseInstance().getId()); } else { Group g = dh.getGroupDAO().get(em, data.getSelectedGroupID()); if(g==null || !g.getCompositeCourseID().equals(data.getCourseInstance().getId()) || !g.getRelativePath().startsWith("0/")) { data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission")); data.setResult(AbstractActionData.RESULT_FATAL); return; } if(!JCMSSecurityManagerFactory.getManager().canManageAssessments(data.getCourseInstance())) { List<GroupOwner> gowners = dh.getGroupDAO().findForGroup(em, g); boolean present = false; for(GroupOwner go : gowners) { if(go.getUser().equals(data.getCurrentUser())) { present = true; break; } } if(!present) { data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission")); data.setResult(AbstractActionData.RESULT_FATAL); return; } } courseUsers = new ArrayList<User>(g.getUsers().size()); for(UserGroup ug : g.getUsers()) { courseUsers.add(ug.getUser()); } data.setSelectedGroup(g); } Set<Long> ids = new HashSet<Long>(courseUsers.size()); for(User u : courseUsers) { ids.add(u.getId()); } data.setAllowedUsers(ids); data.setResult(AbstractActionData.RESULT_SUCCESS); Map<Long,Grade> gradeMap = null; if(data.getCourseInstance().getGradingPolicy()!=null && (data.getCourseInstance().getGradingPolicy().getGradesValid() && data.getCourseInstance().getGradingPolicy().getGradesVisibility()!=GradesVisibility.NOT_VISIBLE)) { // Dohvati još i ocjene: List<Grade> allGrades = DAOHelperFactory.getDAOHelper().getCourseInstanceDAO().listGradesFor(em, data.getCourseInstance()); gradeMap = GradesUtil.mapGradeByUserID(allGrades); } List<UserGroup> lectureUGs = dh.getGroupDAO().findAllLectureUserGroups(em, data.getCourseInstance().getId()); Map<Long,UserGroup> lectureGroups = GroupUtil.mapUserGroupByUserID(lectureUGs); // ====================================== // Ovaj dio se je radio izvan transakcije // ====================================== if(data.getCourseInstance()!=null) { CourseScoreTable table = JCMSCacheFactory.getCache().getCourseScoreTable(data.getCourseInstance().getId()); data.setTable(table); if(table!=null) { // Najprije dohvati stablo ovisnosti Dependencies deps = JCMSCacheFactory.getCache().getDependencies(data.getCourseInstance().getId()); if(deps==null) { // Imamo problem! Ajmo sve proglasiti root komponentama... int brojProvjera = 0; for(int i = 0; i < table.getTableHeader().size(); i++) { ScoreTableHeaderEntry e = table.getTableHeader().get(i); if(e.getUniqueID().endsWith(":A") || e.getUniqueID().endsWith(":F")) { brojProvjera++; } } DependencyItem[] roots = new DependencyItem[brojProvjera]; brojProvjera = 0; for(int i = 0; i < table.getTableHeader().size(); i++) { ScoreTableHeaderEntry e = table.getTableHeader().get(i); if(e.getUniqueID().endsWith(":A") || e.getUniqueID().endsWith(":F")) { roots[brojProvjera] = new DependencyItem(e.getUniqueID(), new DependencyItem[0]); brojProvjera++; } } Arrays.sort(roots); deps = new Dependencies(data.getCourseInstance().getId(), roots); } data.setDependenciesJSON(deps.toJSONStringBuilder().toString()); // Zatim u JSON prebaci zaglavlja StringBuilder headersJSON = new StringBuilder(500); headersJSON.append("["); for(int i = 0; i < table.getTableHeader().size(); i++) { ScoreTableHeaderEntry e = table.getTableHeader().get(i); if(i>0) headersJSON.append(",\n"); headersJSON.append("{"); headersJSON.append("\"headerID\": ").append(e.getId()).append(", "); headersJSON.append("\"headerUniqueID\": \"").append(e.getUniqueID()).append("\", "); if(e instanceof STHEAssessment) { STHEAssessment s = (STHEAssessment)e; headersJSON.append("\"shortName\": \"").append(s.getShortName()).append("\", "); } else if(e instanceof STHEFlag) { STHEFlag s = (STHEFlag)e; headersJSON.append("\"shortName\": \"").append(s.getShortName()).append("\", "); } else if(e instanceof STHEStudent) { headersJSON.append("\"shortName\": \"Student\", "); } headersJSON.append("\"headerType\": \"").append(e.getUniqueID().substring(e.getUniqueID().length()-1)).append("\""); headersJSON.append("}"); } if(table.getTableHeader().size()>0) headersJSON.append(",\n"); headersJSON.append("{"); headersJSON.append("\"headerID\": -3, "); headersJSON.append("\"headerUniqueID\": \"lgroup\", "); headersJSON.append("\"shortName\": \"Grupa\", "); headersJSON.append("\"headerType\": \"L\""); headersJSON.append("}"); if(gradeMap!=null) { headersJSON.append(",\n"); headersJSON.append("{"); headersJSON.append("\"headerID\": -2, "); headersJSON.append("\"headerUniqueID\": \"grade\", "); headersJSON.append("\"shortName\": \"Ocjena\", "); headersJSON.append("\"headerType\": \"G\""); headersJSON.append("}"); } headersJSON.append("]"); data.setHeadersJSON(headersJSON.toString()); headersJSON = null; int indexNo = 30000; boolean normal = true; for(int i = 0; i < table.getTableHeader().size(); i++) { ScoreTableHeaderEntry e = table.getTableHeader().get(i); if(e.getSortKey().equals(data.getSortKey())) { indexNo = i; normal = true; break; } if(e.getReverseSortKey().equals(data.getSortKey())) { indexNo = i; normal = false; break; } } if(indexNo==30000) { indexNo = 0; } List<ScoreTableEntry[]> entries = new ArrayList<ScoreTableEntry[]>(data.getAllowedUsers().size()); int[] origIndex = table.getIndexes().get(indexNo); Set<Long> allowedUsers = data.getAllowedUsers(); if(normal) { for(int i = 0; i < origIndex.length; i++) { ScoreTableEntry[] e = table.getTableItems().get(origIndex[i]); if(!allowedUsers.contains(e[0].getId())) continue; entries.add(e); } } else { for(int i = origIndex.length-1; i >= 0; i--) { ScoreTableEntry[] e = table.getTableItems().get(origIndex[i]); if(!allowedUsers.contains(e[0].getId())) continue; entries.add(e); } } data.setEntries(entries); StringBuilder dataJSON = new StringBuilder(1024*1024); dataJSON.append("["); boolean prvi = true; for(ScoreTableEntry[] row : entries) { if(prvi) { prvi = false; } else { dataJSON.append(", "); } dataJSON.append("["); boolean prviRedak = true; Grade grade = null; UserGroup ug = null; for(ScoreTableEntry e : row) { if(prviRedak) { prviRedak = false; } else { dataJSON.append(", "); } dataJSON.append("\n"); dataJSON.append("{"); dataJSON.append("\"id\": ").append(e.getId()).append(", "); if(e instanceof STEStudent) { STEStudent s = (STEStudent)e; dataJSON.append("\"j\": \"").append(s.getJmbag()).append("\", "); // jmbag dataJSON.append("\"l\": \"").append(s.getLastName()).append("\", "); // lastName dataJSON.append("\"f\": \"").append(s.getFirstName()).append("\""); // firstName if(gradeMap!=null) grade = gradeMap.get(s.getId()); ug = lectureGroups.get(s.getId()); } else if(e instanceof STEScore) { STEScore s = (STEScore)e; dataJSON.append("\"ep\": ").append(s.getEffectivePresent()).append(", "); // effectivePresent dataJSON.append("\"er\": ").append(s.getEffectiveRank()).append(", "); // effectiveRank dataJSON.append("\"ea\": \"").append(s.getEffectiveScoreAsString()).append("\", "); // effectiveScoreAsString dataJSON.append("\"es\": ").append(s.getEffectiveScore()).append(", "); // effectiveScore dataJSON.append("\"e\": ").append(s.isError()).append(", "); // error dataJSON.append("\"p\": ").append(s.isPresent()).append(", "); // present dataJSON.append("\"sa\": \"").append(s.getScoreAsString()).append("\", "); // scoreAsString dataJSON.append("\"s\": ").append(s.getScore()).append(", "); // score dataJSON.append("\"ra\": \"").append(s.getRawScoreAsString()).append("\", "); // rawScoreAsString dataJSON.append("\"rs\": ").append(s.getRawScore()).append(", "); // rawScore dataJSON.append("\"x\": \"").append(s.getStatus().toString()).append("\", "); // status dataJSON.append("\"y\": \"").append(s.getEffectiveStatus().toString()).append("\", "); // effectiveStatus dataJSON.append("\"r\": ").append(s.getRank()); // rank } else if(e instanceof STEFlagValue) { STEFlagValue s = (STEFlagValue)e; dataJSON.append("\"v\": ").append(s.isValue()).append(", "); // value dataJSON.append("\"ms\": ").append(s.isManuallySet()).append(", "); // manuallySet dataJSON.append("\"mv\": ").append(s.isManualValue()).append(", "); // manualValue dataJSON.append("\"e\": ").append(s.isError()); // error } dataJSON.append("}"); } if(row.length>0) { dataJSON.append(", "); dataJSON.append("\n"); } dataJSON.append("{"); if(ug==null) { dataJSON.append("\"id\": -1, "); dataJSON.append("\"g\": \"\""); // grade } else { dataJSON.append("\"id\": -1, "); dataJSON.append("\"n\": \"").append(ug.getGroup().getName()).append("\""); // name of group } dataJSON.append("}"); if(gradeMap!=null) { dataJSON.append(", "); dataJSON.append("\n"); dataJSON.append("{"); if(grade==null) { dataJSON.append("\"id\": -1, "); dataJSON.append("\"g\": \"\""); // grade } else { dataJSON.append("\"id\": ").append(grade.getId()).append(", "); dataJSON.append("\"g\": \"").append(grade.getGrade()).append("\""); // grade } dataJSON.append("}"); } dataJSON.append("]"); } dataJSON.append("]"); data.setDataJSON(dataJSON.toString()); } } } public static void studentScoreBrowserSelection(EntityManager em, StudentScoreBrowserSelectionData data) { // Dohvat kolegija if(!CourseInstanceServiceSupport.fillCourseInstance(em, data, data.getCourseInstanceID())) return; boolean canManage = JCMSSecurityManagerFactory.getManager().canManageAssessments(data.getCourseInstance()); if(!canManage) { data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission")); data.setResult(AbstractActionData.RESULT_FATAL); return; } DAOHelper dh = DAOHelperFactory.getDAOHelper(); CourseInstanceKeyValue cikv = dh.getCourseInstanceKeyValueDAO().get(em, data.getCourseInstance(), "studScoreBrowser"); String kind = resolveStudentScoreBrowser(cikv); data.setKind(kind); data.setResult(AbstractActionData.RESULT_SUCCESS); } public static void studentScoreBrowserSelectionChange(EntityManager em, StudentScoreBrowserSelectionData data) { // Dohvat kolegija if(!CourseInstanceServiceSupport.fillCourseInstance(em, data, data.getCourseInstanceID())) return; boolean canManage = JCMSSecurityManagerFactory.getManager().canManageAssessments(data.getCourseInstance()); if(!canManage) { data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission")); data.setResult(AbstractActionData.RESULT_FATAL); return; } DAOHelper dh = DAOHelperFactory.getDAOHelper(); CourseInstanceKeyValue cikv = dh.getCourseInstanceKeyValueDAO().get(em, data.getCourseInstance(), "studScoreBrowser"); String kind = data.getKind(); if(!isValidStudentScoreBrowser(kind)) { kind = "AUTO"; } if(cikv==null) { cikv = new CourseInstanceKeyValue(data.getCourseInstance(), "studScoreBrowser", kind); dh.getCourseInstanceKeyValueDAO().save(em, cikv); } else { cikv.setValue(kind); } data.setKind(kind); data.setResult(AbstractActionData.RESULT_SUCCESS); } public static boolean isValidStudentScoreBrowser(String kind) { if(kind==null) return false; return kind.equals("AUTO") || kind.equals("TREE1"); } public static String resolveStudentScoreBrowser(CourseInstanceKeyValue cikv) { String kind = "AUTO"; if(cikv!=null && cikv.getValue()!=null && !cikv.getValue().isEmpty()) { kind = cikv.getValue(); } if(!isValidStudentScoreBrowser(kind)) { kind = "AUTO"; } return kind; } public static void studentScoreBrowserSettings(EntityManager em, StudentScoreBrowserSettingsData data) { // Dohvat kolegija if(!CourseInstanceServiceSupport.fillCourseInstance(em, data, data.getCourseInstanceID())) return; boolean canManage = JCMSSecurityManagerFactory.getManager().canManageAssessments(data.getCourseInstance()); if(!canManage) { data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission")); data.setResult(AbstractActionData.RESULT_FATAL); return; } DAOHelper dh = DAOHelperFactory.getDAOHelper(); if(data.getWhat()==null || data.getWhat().isEmpty()) { data.setResult(AbstractActionData.RESULT_SUCCESS); return; } if("flat".equals(data.getWhat())) { List<Assessment> assessments = AssessmentsUtil.getSortedCourseInstanceAssessments(em, data.getCourseInstance()); List<AssessmentFlag> assessmentFlags = AssessmentsUtil.getSortedCourseInstanceAssessmentFlags(em, data.getCourseInstance()); StringBuilder sb = new StringBuilder(1024); for(Assessment a : assessments) { sb.append("A\t").append(a.getId()).append("\t").append(a.getShortName()).append("\t").append(a.getName()).append("\r\n"); } for(AssessmentFlag a : assessmentFlags) { sb.append("F\t").append(a.getId()).append("\t").append(a.getShortName()).append("\t").append(a.getName()).append("\r\n"); } data.setResult("TEXTOK"); try { data.setStream(InputStreamWrapper.createInputStreamWrapperFromText(sb.toString(), "text/plain")); } catch(IOException ex) {} return; } if("hier".equals(data.getWhat())) { CourseInstanceKeyValue cikv = dh.getCourseInstanceKeyValueDAO().get(em, data.getCourseInstance(), "studScoreTree"); String res = ""; if(cikv!=null && cikv.getValue()!=null) { res = cikv.getValue(); if(res==null) res = ""; } data.setResult("TEXTOK"); try { data.setStream(InputStreamWrapper.createInputStreamWrapperFromText(res, "text/plain")); } catch(IOException ex) {} return; } if("stor".equals(data.getWhat())) { CourseInstanceKeyValue cikv = dh.getCourseInstanceKeyValueDAO().get(em, data.getCourseInstance(), "studScoreTree"); String res = ""; if(data.getReqdata()!=null) { res = data.getReqdata(); } if(cikv==null) { cikv = new CourseInstanceKeyValue(data.getCourseInstance(), "studScoreTree", res); dh.getCourseInstanceKeyValueDAO().save(em, cikv); } else { cikv.setValue(res); } data.setResult("TEXTOK"); try { data.setStream(InputStreamWrapper.createInputStreamWrapperFromText("OK", "text/plain")); } catch(IOException ex) {} return; } data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission")); data.setResult(AbstractActionData.RESULT_FATAL); return; } }
40.873638
222
0.674857
29011470c6e99f335c94d3516596eb5f1c6ff8c8
14,234
package connplantsv2.connplantsv2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.sql.Statement; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.CharacterData; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class GetMIIResponse { public String executeShopOrderGETService(String stringURL, Statement stmt) throws IOException{ String outValue = null; URL url = new URL(stringURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Document doc = null; try { doc = (Document) db.parse(in); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } NodeList nodes = ((org.w3c.dom.Document) doc).getElementsByTagName("Row"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList nl = element.getElementsByTagName("SITE"); Element line = (Element) nl.item(0); String site = getCharacterDataFromElement(line); nl = element.getElementsByTagName("SHOP_ORDER"); line = (Element) nl.item(0); String shoporder = getCharacterDataFromElement(line); nl = element.getElementsByTagName("HANDLE"); line = (Element) nl.item(0); String handle = getCharacterDataFromElement(line); nl = element.getElementsByTagName("ITEM_BO"); line = (Element) nl.item(0); String item = getCharacterDataFromElement(line); nl = element.getElementsByTagName("PLANNED_ROUTER_BO"); line = (Element) nl.item(0); String router = getCharacterDataFromElement(line); nl = element.getElementsByTagName("QTY_TO_BUILD"); line = (Element) nl.item(0); String qty_to_build = getCharacterDataFromElement(line); nl = element.getElementsByTagName("QTY_DONE"); line = (Element) nl.item(0); String qty_done = getCharacterDataFromElement(line); nl = element.getElementsByTagName("QTY_SCRAPPED"); line = (Element) nl.item(0); String qty_scrapped = getCharacterDataFromElement(line); nl = element.getElementsByTagName("MODIFIED_DATE_TIME"); line = (Element) nl.item(0); String modified_dt = getCharacterDataFromElement(line); MySQLConnection myserverCon = new MySQLConnection(); String returnMsg = myserverCon.insertMIIShopOrderData(site, shoporder, item, qty_to_build, qty_done, qty_scrapped, modified_dt, router, handle, stmt); System.out.println("Data is inserted "+returnMsg); } return outValue; } public String executeSFCGETService(String stringURL, Statement stmt) throws IOException{ String outValue = null; URL url = new URL(stringURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Document doc = null; try { doc = (Document) db.parse(in); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } NodeList nodes = ((org.w3c.dom.Document) doc).getElementsByTagName("Row"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList nl = element.getElementsByTagName("SITE"); Element line = (Element) nl.item(0); String site = getCharacterDataFromElement(line); nl = element.getElementsByTagName("SHOP_ORDER_BO"); line = (Element) nl.item(0); String shoporder = getCharacterDataFromElement(line); nl = element.getElementsByTagName("SFC"); line = (Element) nl.item(0); String sfc = getCharacterDataFromElement(line); nl = element.getElementsByTagName("STATUS_BO"); line = (Element) nl.item(0); String status = getCharacterDataFromElement(line); nl = element.getElementsByTagName("QTY"); line = (Element) nl.item(0); String qty = getCharacterDataFromElement(line); nl = element.getElementsByTagName("QTY_DONE"); line = (Element) nl.item(0); String qty_done = getCharacterDataFromElement(line); nl = element.getElementsByTagName("QTY_SCRAPPED"); line = (Element) nl.item(0); String qty_scrapped = getCharacterDataFromElement(line); nl = element.getElementsByTagName("MODIFIED_DATE_TIME"); line = (Element) nl.item(0); String modified_dt = getCharacterDataFromElement(line); MySQLConnection myserverCon = new MySQLConnection(); String returnMsg = myserverCon.insertMIISFCData(site, shoporder, sfc, status, qty, qty_done, qty_scrapped, modified_dt, stmt); System.out.println("Data is inserted "+returnMsg); } return outValue; } public String executeOperationService(String operationURL, Statement stmt) throws IOException { String outValue = null; URL url = new URL(operationURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Document doc = null; try { doc = (Document) db.parse(in); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } NodeList nodes = ((org.w3c.dom.Document) doc).getElementsByTagName("Row"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList nl = element.getElementsByTagName("SITE"); Element line = (Element) nl.item(0); String site = getCharacterDataFromElement(line); nl = element.getElementsByTagName("SHOP_ORDER"); line = (Element) nl.item(0); String shoporder = getCharacterDataFromElement(line); nl = element.getElementsByTagName("SFC"); line = (Element) nl.item(0); String sfc = getCharacterDataFromElement(line); nl = element.getElementsByTagName("OPERATION"); line = (Element) nl.item(0); String operation = getCharacterDataFromElement(line); nl = element.getElementsByTagName("ROUTER"); line = (Element) nl.item(0); String router = getCharacterDataFromElement(line); nl = element.getElementsByTagName("MATERIAL"); line = (Element) nl.item(0); String material = getCharacterDataFromElement(line); nl = element.getElementsByTagName("WORK_CENTER"); line = (Element) nl.item(0); String workcenter = getCharacterDataFromElement(line); nl = element.getElementsByTagName("QTY_IN_QUEUE"); line = (Element) nl.item(0); String qty_queue = getCharacterDataFromElement(line); nl = element.getElementsByTagName("QTY_IN_WORK"); line = (Element) nl.item(0); String qty_work = getCharacterDataFromElement(line); nl = element.getElementsByTagName("QTY_COMPLETE"); line = (Element) nl.item(0); String qty_complete = getCharacterDataFromElement(line); nl = element.getElementsByTagName("STEP_ID"); line = (Element) nl.item(0); String step_id = getCharacterDataFromElement(line); MySQLConnection myserverCon = new MySQLConnection(); String returnMsg = myserverCon.insertMIIOperationData(site, shoporder, sfc, operation, router, material, workcenter, qty_queue, qty_work, qty_complete, step_id, stmt); System.out.println("Data is inserted "+returnMsg); } return outValue; } public String executeSiteService(String siteURL, Statement stmt) throws IOException{ String outValue = null; URL url = new URL(siteURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Document doc = null; try { doc = (Document) db.parse(in); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } NodeList nodes = ((org.w3c.dom.Document) doc).getElementsByTagName("Row"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList nl = element.getElementsByTagName("SITE"); Element line = (Element) nl.item(0); String site = getCharacterDataFromElement(line); nl = element.getElementsByTagName("DESCRIPTION"); line = (Element) nl.item(0); String description = getCharacterDataFromElement(line); nl = element.getElementsByTagName("TIME_ZONE"); line = (Element) nl.item(0); String time_zone = getCharacterDataFromElement(line); MySQLConnection myserverCon = new MySQLConnection(); String returnMsg = myserverCon.insertMIISiteData(site, description, time_zone, stmt); System.out.println("Data is inserted "+returnMsg); } return outValue; } public String executeResourceService(String resourceURL, Statement stmt) throws IOException{ String outValue = null; URL url = new URL(resourceURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Document doc = null; try { doc = (Document) db.parse(in); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } NodeList nodes = ((org.w3c.dom.Document) doc).getElementsByTagName("Row"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList nl = element.getElementsByTagName("SITE"); Element line = (Element) nl.item(0); String site = getCharacterDataFromElement(line); nl = element.getElementsByTagName("RESRCE"); line = (Element) nl.item(0); String resource = getCharacterDataFromElement(line); nl = element.getElementsByTagName("RES_DESC"); line = (Element) nl.item(0); String res_desc = getCharacterDataFromElement(line); nl = element.getElementsByTagName("WORK_CENTER_BO"); line = (Element) nl.item(0); String workcenter = getCharacterDataFromElement(line); nl = element.getElementsByTagName("WC_DESC"); line = (Element) nl.item(0); String wc_desc = getCharacterDataFromElement(line); MySQLConnection myserverCon = new MySQLConnection(); String returnMsg = myserverCon.insertMIIResourceData(site, resource, res_desc, workcenter, wc_desc, stmt); System.out.println("Data is inserted "+returnMsg); } return outValue; } public String executeResourceTimeLogService(String resTimeLogURL, Statement stmt) throws IOException{ String outValue = null; URL url = new URL(resTimeLogURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Document doc = null; try { doc = (Document) db.parse(in); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } NodeList nodes = ((org.w3c.dom.Document) doc).getElementsByTagName("Row"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList nl = element.getElementsByTagName("SITE"); Element line = (Element) nl.item(0); String site = getCharacterDataFromElement(line); nl = element.getElementsByTagName("RESOURCE_BO"); line = (Element) nl.item(0); String resource = getCharacterDataFromElement(line); nl = element.getElementsByTagName("RES_DESC"); line = (Element) nl.item(0); String res_desc = getCharacterDataFromElement(line); nl = element.getElementsByTagName("START_DATE_TIME"); line = (Element) nl.item(0); String startDT = getCharacterDataFromElement(line); nl = element.getElementsByTagName("END_DATE_TIME"); line = (Element) nl.item(0); String endDT = getCharacterDataFromElement(line); nl = element.getElementsByTagName("RESOURCE_STATUS_BO"); line = (Element) nl.item(0); String resourceStatus = getCharacterDataFromElement(line); nl = element.getElementsByTagName("STATUS_DESC"); line = (Element) nl.item(0); String status_desc = getCharacterDataFromElement(line); MySQLConnection myserverCon = new MySQLConnection(); String returnMsg = myserverCon.insertMIIResourceTimeLogData(site, resource, res_desc, startDT, endDT, resourceStatus, status_desc, stmt); System.out.println("Data is inserted "+returnMsg); } return outValue; } public static String getCharacterDataFromElement(Element e) { Node child = e.getFirstChild(); if (child instanceof CharacterData) { CharacterData cd = (CharacterData) child; return cd.getData(); } return "?"; } }
31.146608
171
0.698117
71b9e3c89aead93d07ba0a575417f1a63ff1d443
3,250
package DSS.GestFuncionarios; import DSS.Exceptions.CredenciaisInvalidasException; import DSS.Exceptions.UsernameJaExisteException; import DSS.Exceptions.UsernameNaoExisteException; import java.util.Map; /** * Interface IGestFuncionariosFacade que contém os seguintes métodos */ public interface IGestFuncionariosFacade{ /** * Método que regista um Funcionario no sistema * @param username Username do Funcionario * @param password Password do Funcionario * @throws UsernameJaExisteException Exceção lançada quando já existe um Funcionamrio com o mesmo username */ void registaFuncionario(String username, String password) throws UsernameJaExisteException; /** * Método que efetua a autenticação de um Funcionario * @param username Username do Funcionario * @param password Password do Funcionario * @return Booleano que indica se o Funcionario foi autenticado com sucesso * @throws CredenciaisInvalidasException Exceção lançada quando as credenciais inseridas não coincidem com as de nenhum Funcionario registado no sistema */ boolean autenticaFuncionario(String username, String password) throws CredenciaisInvalidasException; /** * Método que verifica se um Funcionario está autenticado * @param username Username do Funcionario * @return Booleano que indica se o Funcionario está autenticado */ boolean isAutenticado(String username); /** * Método getter do mapa de GestFuncionarioFacade * @return Mapa dos funcionarios do sistema */ Map<String, Funcionario> getFuncionarios(); /** * Método getter de um Funcionario * @param username Username do Funcionario * @return Funcionario procurado * @throws UsernameNaoExisteException Exceção lançada quando não é encontrado o Funcionario com o username dado */ Funcionario getFuncionario(String username) throws UsernameNaoExisteException; /** * Método que incrementa as recepções de equipamentos de um Funcionario * @param username Username do Funcionario */ void incrementaRecepcoes(String username); /** * Método que incrementa as entregas de equipamentos de um Funcionario * @param username Username do Funcionario */ void incrementaEntregas(String username); /** * Método que remove um Funcionario do sistema * @param username Username do Funcionario */ void removeFuncionario (String username); /** * Método que verifica se existe um dado funcionario * @param username Username do Funcionario * @return Booleano que indica se esse Funcionario existe * @throws UsernameNaoExisteException Exceção lançada quando não existe tal Funcionario */ boolean existeFuncionario(String username) throws UsernameNaoExisteException; /** * Método que verifica se existe algum Funcionario no sistema * @return Booleano que indica se existem algum Funcionario no sistema */ boolean funcionariosIsEmpty(); /** * Método que passa as informações sobre recepções e entregas de equipamentos para String * @return String com informação sobre recepções e entregas */ String imprimeRecepcoesEntregas(); }
36.516854
156
0.736
9e3868de8cc1807ea84948b633ed03845dcfb9e1
2,163
/* * Copyright (c) 2017 Ampool, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. See accompanying LICENSE file. */ package io.ampool.monarch.table.exceptions; import io.ampool.classification.InterfaceAudience; import io.ampool.classification.InterfaceStability; /** * A generic exception indicating that a failure has happened while operating with Monarch cache * * @since 1.0.0.0 */ @InterfaceAudience.Public @InterfaceStability.Stable public abstract class MCacheException extends MException { private static final long serialVersionUID = 6157641775524694873L; public MCacheException() { super(); } /** * Creates a new <code>MCacheException</code> with the given detail message. */ public MCacheException(String message) { super(message); } /** * Creates a new <code>MCacheException</code> with the given detail message and cause. * * @param message message * @param cause cause */ public MCacheException(String message, Throwable cause) { super(message, cause); } /** * Creates a new <code>MCacheException</code> with the given cause and no detail message * * @param cause cause */ public MCacheException(Throwable cause) { super(cause); } /** * Returns the root cause of this <code>GemFireException</code> or <code>null</code> if the cause * is nonexistent or unknown. * * @return Exception */ public Throwable getRootCause() { if (this.getCause() == null) { return null; } Throwable root = this.getCause(); while (root.getCause() != null) { root = root.getCause(); } return root; } }
27.379747
100
0.701803
97690a54a78346ee83c7da2b06951a3d657a9cca
1,694
package net.chinhung.application.component.order.impl.create; import net.chinhung.application.component.order.Create; import net.chinhung.application.component.order.CreateResult; import net.chinhung.application.component.inventory.InventoryComponent; import net.chinhung.application.component.inventory.InventoryQuery; import net.chinhung.application.component.inventory.InventoryQueryResult; import net.chinhung.fundamental.aspect.CommandService; import java.util.List; import java.util.stream.Collectors; public class InventoryQueryDecorator implements CommandService<Create, CreateResult> { private final CommandService<Create, CreateResult> decoratee; private final InventoryComponent inventoryComponent; public InventoryQueryDecorator( final CommandService<Create, CreateResult> decoratee, final InventoryComponent inventoryComponent ) { this.decoratee = decoratee; this.inventoryComponent = inventoryComponent; } @Override public CreateResult execute(Create command) { final List<InventoryQuery> inventoryQueries = command.getItems().stream().map(item -> { return new InventoryQuery(item.getProductId(), item.getName(), item.getQuantity()); }).collect(Collectors.toList()); final InventoryQueryResult result = inventoryComponent.query(inventoryQueries); if (result.getOutOfStockQueries().size() > 0) { String names = result.getOutOfStockQueries().stream().map(q -> q.getProductName()).collect(Collectors.joining(", ")); throw new RuntimeException("products out of stock: " + names); } return decoratee.execute(command); } }
42.35
129
0.744982
30a98d87d76bfa70a8ae68032fcf96e819ebaa05
1,642
package com.example.paywhere.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; /** * FileName: SwaggerConfig * Author: haichaoyang3 * Date: 2020/5/7 14:13 * Description:swagger文档 * History: * since: 1.0.0 */ @Configuration public class SwaggerConfig { private final String version = "1.0"; private final String title = "spring boot 文档示例"; private final String description = "api文档"; private String license = "MIT"; private final String licenseUrl = "https://mit-license.org/"; private final Contact contact = new Contact("haichaoyang", "www.baidu.com", "jackieyung@aliyun.com"); @Bean public Docket build() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(buildApiInfo()) .groupName("2.X版本") .select().apis(RequestHandlerSelectors.basePackage("com.jc.demo.springbootdemo.web.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo buildApiInfo() { return new ApiInfoBuilder().title(title).contact(contact).description(description).license(license).licenseUrl(licenseUrl) .version(version).build(); } }
35.695652
130
0.724726
06cfee539f42389312ec835b4cfb9d864500a2ad
12,989
/* * Project:Easy Web Framework * Description: * EasyFK stands for Easy Web Framework.It's an open source product for E-Business / E-Commerce.It * was launched by a chinese Hezhiping(QQ:110476592) in 2015.The goal of EasyFK is to provide a * foundation and starting point for reliable, secure , simple-to-use ,cost-effective ,scalable * and suitable-for-Chinese E-Business / E-Commerce solutions. With EasyFK, you can get started * right away without the huge deployment and maintenance costs of E-Business / E-Commerce systems. * Of course, you can customize it or use it as a framework to implement your most challenging business needs. * EasyFk is licensed under the Apache License Version 2.0. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Author:hezhiping Email:110476592@qq.com */ package cn.gorun8.easyfk.base.util.collections; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import cn.gorun8.easyfk.base.util.UtilProperties; import cn.gorun8.easyfk.base.util.string.FlexibleStringExpander; /** * Generic ResourceBundle Map Wrapper, given ResourceBundle allows it to be used as a Map * */ @SuppressWarnings("serial") public class ResourceBundleMapWrapper implements Map<String, Object>, Serializable { protected MapStack<String> rbmwStack; protected ResourceBundle initialResourceBundle; protected Map<String, Object> context; protected ResourceBundleMapWrapper() { rbmwStack = MapStack.create(); } /** * When creating new from a InternalRbmWrapper the one passed to the constructor should be the most specific or local InternalRbmWrapper, with more common ones pushed onto the stack progressively. */ public ResourceBundleMapWrapper(InternalRbmWrapper initialInternalRbmWrapper) { this.initialResourceBundle = initialInternalRbmWrapper.getResourceBundle(); this.rbmwStack = MapStack.create(initialInternalRbmWrapper); } /** When creating new from a ResourceBundle the one passed to the constructor should be the most specific or local ResourceBundle, with more common ones pushed onto the stack progressively. */ public ResourceBundleMapWrapper(ResourceBundle initialResourceBundle) { if (initialResourceBundle == null) { throw new IllegalArgumentException("Cannot create ResourceBundleMapWrapper with a null initial ResourceBundle."); } this.initialResourceBundle = initialResourceBundle; this.rbmwStack = MapStack.create(new InternalRbmWrapper(initialResourceBundle)); } public void setInitialResourceBundle(ResourceBundle initialResourceBundle) { if (initialResourceBundle == null) { throw new IllegalArgumentException("Cannot create ResourceBundleMapWrapper with a null initial ResourceBundle."); } this.initialResourceBundle = initialResourceBundle; this.rbmwStack = MapStack.create(new InternalRbmWrapper(initialResourceBundle)); } /** When creating new from a ResourceBundle the one passed to the constructor should be the most specific or local ResourceBundle, with more common ones pushed onto the stack progressively. */ public ResourceBundleMapWrapper(ResourceBundle initialResourceBundle, Map<String, Object> context) { if (initialResourceBundle == null) { throw new IllegalArgumentException("Cannot create ResourceBundleMapWrapper with a null initial ResourceBundle."); } this.initialResourceBundle = initialResourceBundle; this.rbmwStack = MapStack.create(new InternalRbmWrapper(initialResourceBundle)); this.context = context; } /** Puts ResourceBundle on the BOTTOM of the stack (bottom meaning will be overriden by higher layers on the stack, ie everything else already there) */ public void addBottomResourceBundle(ResourceBundle topResourceBundle) { this.rbmwStack.addToBottom(new InternalRbmWrapper(topResourceBundle)); } /** Puts InternalRbmWrapper on the BOTTOM of the stack (bottom meaning will be overriden by higher layers on the stack, ie everything else already there) */ public void addBottomResourceBundle(InternalRbmWrapper topInternalRbmWrapper) { this.rbmwStack.addToBottom(topInternalRbmWrapper); } /** Don't pass the locale to make sure it has the same locale as the base */ public void addBottomResourceBundle(String resource) { if (this.initialResourceBundle == null) { throw new IllegalArgumentException("Cannot add bottom resource bundle, this wrapper was not properly initialized (there is no base/initial ResourceBundle)."); } this.addBottomResourceBundle(new InternalRbmWrapper(UtilProperties.getResourceBundle(resource, this.initialResourceBundle.getLocale()))); } /** In general we don't want to use this, better to start with the more specific ResourceBundle and add layers of common ones... * Puts ResourceBundle on the top of the stack (top meaning will override lower layers on the stack) */ public void pushResourceBundle(ResourceBundle topResourceBundle) { this.rbmwStack.push(new InternalRbmWrapper(topResourceBundle)); } public ResourceBundle getInitialResourceBundle() { return this.initialResourceBundle; } public void clear() { this.rbmwStack.clear(); } public boolean containsKey(Object arg0) { return this.rbmwStack.containsKey(arg0); } public boolean containsValue(Object arg0) { return this.rbmwStack.containsValue(arg0); } public Set<Map.Entry<String, Object>> entrySet() { return this.rbmwStack.entrySet(); } public Object get(Object arg0) { Object value = this.rbmwStack.get(arg0); if (value == null) { value = arg0; } else if (context != null) { try { String str = (String) value; return FlexibleStringExpander.expandString(str, context); } catch (Exception e) { // Potential ClassCastException - do nothing } } return value; } public boolean isEmpty() { return this.rbmwStack.isEmpty(); } public Set<String> keySet() { return this.rbmwStack.keySet(); } public Object put(String key, Object value) { return this.rbmwStack.put(key, value); } public void putAll(Map<? extends String, ? extends Object> arg0) { this.rbmwStack.putAll(arg0); } public Object remove(Object arg0) { return this.rbmwStack.remove(arg0); } public int size() { return this.rbmwStack.size(); } public Collection<Object> values() { return this.rbmwStack.values(); } public static class InternalRbmWrapper implements Map<String, Object>, Serializable { protected ResourceBundle resourceBundle; protected Map<String, Object> topLevelMap; private boolean isMapInitialized = false; public InternalRbmWrapper(ResourceBundle resourceBundle) { if (resourceBundle == null) { throw new IllegalArgumentException("Cannot create InternalRbmWrapper with a null ResourceBundle."); } this.resourceBundle = resourceBundle; } /** * Creates the topLevelMap only when it is required */ private void createMapWhenNeeded() { if (isMapInitialized) { return; } // NOTE: this does NOT return all keys, ie keys from parent // ResourceBundles, so we keep the resourceBundle object to look at // when the main Map doesn't have a certain value if (resourceBundle != null) { Set<String> set = resourceBundle.keySet(); topLevelMap = new HashMap<String, Object>(set.size()); for (String key : set) { Object value = resourceBundle.getObject(key); topLevelMap.put(key, value); } } else { topLevelMap = new HashMap<String, Object>(1); } topLevelMap.put("_RESOURCE_BUNDLE_", resourceBundle); isMapInitialized = true; } /* (non-Javadoc) * @see java.util.Map#size() */ public int size() { if(isMapInitialized) { // this is an approximate size, won't include elements from parent bundles return topLevelMap.size() -1; } else { return resourceBundle.keySet().size(); } } /* (non-Javadoc) * @see java.util.Map#isEmpty() */ public boolean isEmpty() { if (isMapInitialized) { return topLevelMap.isEmpty(); } else { return resourceBundle.keySet().size() == 0; } } /* (non-Javadoc) * @see java.util.Map#containsKey(java.lang.Object) */ public boolean containsKey(Object arg0) { if (isMapInitialized) { if (topLevelMap.containsKey(arg0)) { return true; } } else { try { if (this.resourceBundle.getObject((String) arg0) != null) { return true; } } catch (NullPointerException e) { // happens when arg0 is null } catch (MissingResourceException e) { // nope, not found... nothing, will automatically return // false below } } return false; } /* (non-Javadoc) * @see java.util.Map#containsValue(java.lang.Object) */ public boolean containsValue(Object arg0) { throw new RuntimeException("Not implemented for ResourceBundleMapWrapper"); } /* (non-Javadoc) * @see java.util.Map#get(java.lang.Object) */ public Object get(Object arg0) { Object value = null; if(isMapInitialized) { value = this.topLevelMap.get(arg0); } if (resourceBundle != null) { if (value == null) { try { value = this.resourceBundle.getObject((String) arg0); } catch (MissingResourceException mre) { // do nothing, this will be handled by recognition that the value is still null } } } /* we used to do this here, but now we'll do it in the top-level class since doing it here would prevent searching down the stack if (value == null) { value = arg0; } */ return value; } /* (non-Javadoc) * @see java.util.Map#put(java.lang.Object, java.lang.Object) */ public Object put(String arg0, Object arg1) { throw new RuntimeException("Not implemented/allowed for ResourceBundleMapWrapper"); } /* (non-Javadoc) * @see java.util.Map#remove(java.lang.Object) */ public Object remove(Object arg0) { throw new RuntimeException("Not implemented for ResourceBundleMapWrapper"); } /* (non-Javadoc) * @see java.util.Map#putAll(java.util.Map) */ public void putAll(Map<? extends String, ? extends Object> arg0) { throw new RuntimeException("Not implemented for ResourceBundleMapWrapper"); } /* (non-Javadoc) * @see java.util.Map#clear() */ public void clear() { throw new RuntimeException("Not implemented for ResourceBundleMapWrapper"); } /* (non-Javadoc) * @see java.util.Map#keySet() */ public Set<String> keySet() { createMapWhenNeeded(); return this.topLevelMap.keySet(); } /* (non-Javadoc) * @see java.util.Map#values() */ public Collection<Object> values() { createMapWhenNeeded(); return this.topLevelMap.values(); } /* (non-Javadoc) * @see java.util.Map#entrySet() */ public Set<Map.Entry<String, Object>> entrySet() { createMapWhenNeeded(); return this.topLevelMap.entrySet(); } public ResourceBundle getResourceBundle() { return this.resourceBundle; } /*public String toString() { return this.topLevelMap.toString(); }*/ } }
39.006006
200
0.62014
1d52de6355a9e67fe6d4bb1db997a2c963d4c8c4
1,389
package com.jibug.frpc.common.config; import com.jibug.frpc.common.cluster.enums.RequestType; import com.jibug.frpc.common.codec.compress.CompressEnum; import com.jibug.frpc.common.codec.serialize.SerializeProtocolEnum; /** * @author heyingcai */ public class MethodConfig { private String methodName; private int timeout; private CompressEnum compressType; private SerializeProtocolEnum serializeProtocol; private RequestType requestType; public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public CompressEnum getCompressType() { return compressType; } public void setCompressType(CompressEnum compressType) { this.compressType = compressType; } public SerializeProtocolEnum getSerializeProtocol() { return serializeProtocol; } public void setSerializeProtocol(SerializeProtocolEnum serializeProtocol) { this.serializeProtocol = serializeProtocol; } public RequestType getRequestType() { return requestType; } public void setRequestType(RequestType requestType) { this.requestType = requestType; } }
22.403226
79
0.703384
f7b0acabdfa74d22cf228ff2bb5e5ec1c384f19c
443
package com.silentmatt.dss; import java.io.File; import java.net.URL; import java.util.List; public interface Configuration { boolean colorTestOutput(); boolean compressOutput(); List<String> getDefines(); File getOutputFile(); URL getURL(); boolean isSuccess(); boolean isTest(); boolean showDebuggingOutput(); boolean showNotifications(); boolean showVersion(); boolean watchFile(); }
14.766667
34
0.683973
12b470352c63880c7ef9b0034a11ad32fb825949
458
package poo.conta; public class ContaEspecial extends Conta { private double bonus; public ContaEspecial (String numero) { super(numero); bonus = 0; } public void renderBonus() { super.creditar(bonus); bonus = 0; } public void creditar (double valor) { bonus += valor * 0.01; super.creditar(valor); } }
22.9
46
0.484716
6c1a5b156e9fe98df818cc03da627309ce4460c0
3,133
/* * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.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 com.kuang.templateproject.adapter.entity; import com.kuang.templateproject.utils.Date.DateTimeUtil; import java.io.File; import java.util.Date; public class AudioFile { private String filePath; private String filename; private String tag; private Date date; private File file; private String back_filePath; private File back_file; public AudioFile(String filePath, String tag, Date date, File file, String filename, String back_filePath, File back_file) { this.filePath = filePath; this.tag = tag; this.date = date; this.file = file; this.back_filePath = back_filePath; this.filename = filename; this.back_file = back_file; } public AudioFile(String filePath, String tag, Date date, File file, String filename) { this.filePath = filePath; this.tag = tag; this.date = date; this.filename = filename; this.file = file; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public AudioFile(String tag) { this.tag =tag; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getBack_filePath() { return back_filePath; } public void setBack_filePath(String back_filePath) { this.back_filePath = back_filePath; } public File getBack_file() { return back_file; } public void setBack_file(File back_file) { this.back_file = back_file; } @Override public String toString() { return "AudioFile{" + "filePath='" + filePath + '\'' + ", filename='" + filename + '\'' + ", tag='" + tag + '\'' + ", date=" + DateTimeUtil.DateToStr(date) + ", file=" + file + ", back_filePath='" + back_filePath + '\'' + ", back_file=" + back_file + '}'; } }
24.865079
128
0.604213
0de81b850828618abefbf614450fa6f6b4cced1d
2,434
/* * Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics * * 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.search.nibrs.model; import static org.junit.Assert.*; import org.junit.Test; public class NullArrayTests { @Test public void testVictimSegment() { VictimSegment v = new VictimSegment(); Object[] a = v.getTypeOfInjury(); assertNotNull(a); assertEquals(VictimSegment.TYPE_OF_INJURY_COUNT, a.length); v.setTypeOfInjury(null); a = v.getTypeOfInjury(); assertNotNull(a); assertEquals(VictimSegment.TYPE_OF_INJURY_COUNT, a.length); a = v.getAggravatedAssaultHomicideCircumstances(); assertNotNull(a); assertEquals(VictimSegment.AGGRAVATED_ASSAULT_HOMICIDE_CIRCUMSTANCES_COUNT, a.length); v.setAggravatedAssaultHomicideCircumstances(null); a = v.getAggravatedAssaultHomicideCircumstances(); assertNotNull(a); assertEquals(VictimSegment.AGGRAVATED_ASSAULT_HOMICIDE_CIRCUMSTANCES_COUNT, a.length); a = v.getOffenderNumberRelated(); assertNotNull(a); assertEquals(VictimSegment.OFFENDER_NUMBER_RELATED_COUNT, a.length); v.setOffenderNumberRelated(null); a = v.getOffenderNumberRelated(); assertNotNull(a); assertEquals(VictimSegment.OFFENDER_NUMBER_RELATED_COUNT, a.length); a = v.getVictimOffenderRelationship(); assertNotNull(a); assertEquals(VictimSegment.OFFENDER_NUMBER_RELATED_COUNT, a.length); v.setVictimOffenderRelationship(null); a = v.getVictimOffenderRelationship(); assertNotNull(a); assertEquals(VictimSegment.OFFENDER_NUMBER_RELATED_COUNT, a.length); a = v.getUcrOffenseCodeConnection(); assertNotNull(a); assertEquals(VictimSegment.UCR_OFFENSE_CODE_CONNECTION_COUNT, a.length); v.setUcrOffenseCodeConnection(null); a = v.getUcrOffenseCodeConnection(); assertNotNull(a); assertEquals(VictimSegment.UCR_OFFENSE_CODE_CONNECTION_COUNT, a.length); } }
31.61039
88
0.772802
abdbf49e004bfa57bc4c643069ce727bc2add748
264
package cn.com.smart.report.dao; import org.springframework.stereotype.Repository; import cn.com.smart.dao.impl.BaseDaoImpl; import cn.com.smart.report.bean.entity.TReportField; @Repository public class ReportFieldDao extends BaseDaoImpl<TReportField> { }
22
63
0.806818
9a3e24f83626055b4b2ee085fdb9a4f9d70d3687
927
/* */ package org.apache.aingle.reflect; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Declares that a Java type should be represented by an AIngle union schema. May * be used for base classes or interfaces whose instantiable subclasses can be * listed in the parameters to the @Union annotation. If applied to method * parameters this determines the reflected message parameter type. If applied * to a method, this determines its return type. A null schema may be specified * with {@link java.lang.Void}. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Documented public @interface Union { /** The instantiable classes that compose this union. */ Class[] value(); }
34.333333
91
0.77562
55a1b9e52928515829511273e4a16e51434940d1
1,473
package medium._074; /** * <pre> * author : 残渊 * time : 2019/06/18 * desc : 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: * 每行中的整数从左到右按升序排列。 * 每行的第一个整数大于前一行的最后一个整数 * </pre> */ public class Solution { /** * 输入: * matrix = [ * [1, 3, 5, 7], * [10, 11, 16, 20], * [23, 30, 34, 50] * ] * target = 3 * 输出: true * <p> * 输入: * matrix = [ * [1, 3, 5, 7], * [10, 11, 16, 20], * [23, 30, 34, 50] * ] * target = 13 * 输出: false */ public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0 || matrix[0].length == 0) return false; if(target<matrix[0][0]) return false; int m = matrix[0].length -1; int row = 0; while (row<matrix.length){ if(matrix[row][0]>target){ break; }else if(matrix[row][0] == target){ return true; } row++; } row--; if(target>matrix[row][m]) return false; int left = 0; int right = m; int mid; while (left<=right){ mid = left+(right-left)/2; if(target == matrix[row][mid]){ return true; }else if(target <matrix[row][mid]){ right = mid-1; }else { left = mid+1; } } return false; } }
23.380952
70
0.412084
f829586d0a23e65600ba0abf2f72d9831a320f3d
2,786
package com.moon.core.lang; import com.moon.core.io.FileUtil; import com.moon.core.util.MapUtil; import org.junit.jupiter.api.Test; import java.util.Date; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author moonsky */ public class ArrayUtilTest { @Test void testName() throws Exception { // ValidationUtil.requireDateString(""); // ValidationUtil.of("string"); String path = "D:\\WorkSpaces\\github\\javascript\\json-mock\\node_modules\\codemirror\\theme"; FileUtil.traveller().traverse(path).forEach(name -> { // System.out.println(name.getName()); // String importStr = StringUtil.format("import 'codemirror/theme/{}';", name.getName()); String onlyName = StringUtil.substrBefore(name.getName(), ".css"); String thisName = StringUtil.format("'{}',", onlyName); System.out.println(thisName); }); } @Test void testSplice() { boolean[] arr = {false, true, false, true}; assertEquals(JoinerUtil.join(arr, ","), "false,true,false,true"); boolean[] newArr = ArrayUtil.splice(arr, 1, 1, true, true); assertEquals(JoinerUtil.join(newArr, ","), "false,true,true,false,true"); int[] ints = {1, 2, 3, 4, 5}; assertEquals(JoinerUtil.join(ints, ","), "1,2,3,4,5"); int[] newInts = ArrayUtil.splice(ints, 1, 4, 11, 11, 11, 11); assertEquals(JoinerUtil.join(newInts, ","), "1,11,11,11,11"); newInts = ArrayUtil.splice(ints, 1, 1, 11, 11, 11, 11); assertEquals(JoinerUtil.join(newInts, ","), "1,11,11,11,11,3,4,5"); Object[] objects = {1, 2, 3, 4, 5}; assertEquals(JoinerUtil.join(objects, ","), "1,2,3,4,5"); Object[] newObjects = ArrayUtil.splice(objects, 1, 4, 11, 11, 11, 11); assertEquals(JoinerUtil.join(newObjects, ","), "1,11,11,11,11"); } @Test void testReverse() { Integer[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9}; ArrayUtil.reverse(values); assertEquals(JoinerUtil.join(values, ","), "9,8,7,6,5,4,3,2,1"); values = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8}; ArrayUtil.reverse(values); assertEquals(JoinerUtil.join(values, ","), "8,7,6,5,4,3,2,1"); } @Test void testSum() throws Exception { int[] ints = {}; Map<String, Object> resultMap = ArrayUtil.reduce(20, (map, idx) -> map, MapUtil.newHashMap()); } @Test void testToString() throws Exception { long time = new Date().getTime(); System.out.println(time); String str = LongUtil.toString(time, 62); System.out.println(str); long parsed = LongUtil.parseLong(str, 62); assertEquals(time, parsed); } }
35.265823
103
0.591529
b3c214814b587714edb5203ce8e2f6d97a5249f8
2,877
/* *************************************************************************** * Mica - the Java(tm) Graphics Framework * *************************************************************************** * NOTICE: Permission to use, copy, and modify this software and its * * documentation is hereby granted provided that this notice appears in * * all copies. * * * * Permission to distribute un-modified copies of this software and its * * documentation is hereby granted provided that no fee is charged and * * that this notice appears in all copies. * * * * SOFTWARE FARM MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE * * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT * * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR * * A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SOFTWARE FARM SHALL NOT BE * * LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR * * CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, MODIFICATION OR * * DISTRIBUTION OF THIS SOFTWARE OR ITS DERIVATIVES. * * * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND * * DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * * *************************************************************************** * Copyright (c) 1997-2004 Software Farm, Inc. All Rights Reserved. * *************************************************************************** */ package com.swfm.mica; import java.io.PrintWriter; import java.awt.Graphics; /**---------------------------------------------------------------------------------------------- * @version %I% %G% * @author Michael L. Davis * @release 1.4.1 * @module %M% * @language Java (JDK 1.4) *----------------------------------------------------------------------------------------------*/ public interface MiiPrintDriver extends MiiPropertied { Graphics getGraphics(); MiBounds getDeviceBounds(); MiMargins getMargins(); void setBoundsOfGraphicalContent(MiBounds contentBounds); void init(); void termin(); void newPage(); boolean configure( String filename, int dotsPerInch, String standardPaperSize, String portraitOrLandscape, String colorOutputScheme, int totalNumberOfPages); }
47.95
98
0.456031
15fc564c65cb3c1252f3e31e14015edb8c6c72d6
1,195
package de.longor.talecraft.voxelator.shapes; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import de.longor.talecraft.util.BlockRegion; import de.longor.talecraft.util.MutableBlockPos; import de.longor.talecraft.voxelator.CachedWorldDiff; import de.longor.talecraft.voxelator.VXShape; public class VXShapeBox extends VXShape { private final BlockPos position; private final int width; private final int height; private final int length; public VXShapeBox(BlockPos position, int width, int height, int length) { this.position = position; this.width = width; this.height = height; this.length = length; } @Override public BlockPos getCenter() { return position; } @Override public BlockRegion getRegion() { return new BlockRegion(position, width, height, length); } @Override public boolean test(BlockPos pos, BlockPos center, MutableBlockPos offset, CachedWorldDiff fworld) { int diffx = MathHelper.abs_int(pos.getX() - position.getX()); int diffy = MathHelper.abs_int(pos.getY() - position.getY()); int diffz = MathHelper.abs_int(pos.getZ() - position.getZ()); return diffx < width && diffy < height && diffz < length; } }
28.452381
101
0.754812
4458ed38e2217ec60034491ebfa94dc62fc1ebcb
8,331
/* * Fabric3 * Copyright (c) 2009-2015 Metaform Systems * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Portions originally based on Apache Tuscany 2007 * licensed under the Apache 2.0 license. */ package org.fabric3.binding.zeromq.runtime.message; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import org.fabric3.api.binding.zeromq.model.ZeroMQMetadata; import org.fabric3.api.host.Fabric3Exception; import org.fabric3.binding.zeromq.runtime.MessagingMonitor; import org.fabric3.binding.zeromq.runtime.context.ContextManager; import org.fabric3.spi.container.invocation.CallbackReferenceSerializer; import org.fabric3.spi.container.invocation.WorkContext; import org.fabric3.spi.container.invocation.WorkContextCache; import org.fabric3.spi.container.wire.Interceptor; import org.fabric3.spi.container.wire.InvocationChain; import org.fabric3.binding.zeromq.runtime.SocketAddress; import org.fabric3.spi.host.Port; import org.oasisopen.sca.ServiceRuntimeException; import org.zeromq.ZMQ; import org.zeromq.ZMQ.Socket; /** * */ public abstract class AbstractReceiver implements Receiver, Thread.UncaughtExceptionHandler { protected ContextManager manager; protected SocketAddress address; protected ExecutorService executorService; protected int socketType; protected Interceptor[] interceptors; protected MessagingMonitor monitor; protected Receiver receiver; protected ZeroMQMetadata metadata; protected String id = getClass().getName() + ":" + UUID.randomUUID().toString(); /** * Constructor. * * @param manager the ZeroMQ Context manager * @param address the address to receive messages on * @param chains the invocation chains for dispatching invocations * @param socketType the socket type as defined by ZeroMQ * @param metadata metadata * @param executorService the executor for scheduling work * @param monitor the monitor */ public AbstractReceiver(ContextManager manager, SocketAddress address, List<InvocationChain> chains, int socketType, ZeroMQMetadata metadata, ExecutorService executorService, MessagingMonitor monitor) { this.manager = manager; this.address = address; this.executorService = executorService; this.interceptors = new Interceptor[chains.size()]; for (int i = 0, chainsSize = chains.size(); i < chainsSize; i++) { InvocationChain chain = chains.get(i); interceptors[i] = chain.getHeadInterceptor(); } this.socketType = socketType; this.metadata = metadata; this.monitor = monitor; } public void start() { if (receiver == null) { receiver = new Receiver(); schedule(); } } public void stop() { try { receiver.stop(); } finally { receiver = null; } } public SocketAddress getAddress() { return address; } public void uncaughtException(Thread t, Throwable e) { monitor.error(e); } private void schedule() { executorService.submit(receiver); } /** * Creates a WorkContext for the request. * * client that is wired to it. Otherwise, it is null. * * @param header the serialized work context header * @return the work context */ @SuppressWarnings({"unchecked"}) protected WorkContext setWorkContext(byte[] header) { try { WorkContext workContext = WorkContextCache.getAndResetThreadWorkContext(); if (header == null || header.length == 0) { return workContext; } List<String> stack = CallbackReferenceSerializer.deserialize(header); // add the last callback twice as it will be needed when the callback is made back through the binding if (!stack.isEmpty()) { stack.add(stack.get(stack.size() - 1)); } workContext.addCallbackReferences(stack); return workContext; } catch (Fabric3Exception e) { throw new ServiceRuntimeException("Error deserializing callback references", e); } } protected abstract boolean invoke(Socket socket); protected abstract void response(Socket socket); /** * The message receiver. Responsible for creating socket connections to publishers and polling for messages. */ private class Receiver implements Runnable { private Socket socket; private Socket controlSocket; private ZMQ.Poller poller; private AtomicBoolean active = new AtomicBoolean(true); /** * Signals to stops polling and close the receiver socket, if one is open. Note that the socket cannot be closed in this method, as it will be called on * a different thread than {@link #run()}, which opened the socket. ZeroMQ requires a socket only be accessed by the thread that created it. */ public synchronized void stop() { active.set(false); } public void run() { try { bind(); while (active.get()) { if (poller == null) { // the socket or poller could not be created, abort monitor.error("Failed to initialize ZeroMQ socket, aborting receiver"); return; } long val = poller.poll(); if (val > 0) { byte[] controlPayload = controlSocket.recv(ZMQ.NOBLOCK); if (controlPayload != null) { try { socket.close(); controlSocket.close(); } finally { manager.release(id); } return; } if (!invoke(socket)) { continue; } response(socket); } } // the socket must be closed here on this thread! if (socket != null) { try { socket.close(); controlSocket.close(); } finally { manager.release(id); } socket = null; } } catch (RuntimeException e) { // exception, make sure the thread is rescheduled manager.release(id); schedule(); throw e; } } private void bind() { if (socket != null) { // Socket is still active, ignore. This can happen if bind is called after the receiver has been rescheduled return; } manager.reserve(id); socket = manager.getContext().socket(socketType); SocketHelper.configure(socket, metadata); address.getPort().bind(Port.TYPE.TCP); socket.bind(address.toProtocolString()); controlSocket = manager.createControlSocket(); poller = manager.getContext().poller(); poller.register(controlSocket, ZMQ.Poller.POLLIN); poller.register(socket, ZMQ.Poller.POLLIN); } } }
35.451064
160
0.581923
f546a00bcc2fd07a3df017fbacfb87d8c62265a6
4,368
package com.evernym.sdk.vcx; import com.evernym.sdk.vcx.schema.InvalidSchemahandleException; import com.evernym.sdk.vcx.schema.SchemaApi; import com.evernym.sdk.vcx.vcx.VcxApi; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutionException; public class SchemaApiTest { private String sourceId = "123"; private String schemaName = "schema name"; private String schemaVersion = "1.1.1"; private String schemaData = "['attr1', 'attr2', 'height', 'weight']"; @BeforeEach void setup() throws Exception { System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "DEBUG"); if (!TestHelper.vcxInitialized) { TestHelper.getResultFromFuture(VcxApi.vcxInit(TestHelper.VCX_CONFIG_TEST_MODE)); TestHelper.vcxInitialized = true; } } @Test @DisplayName("create a schema") void createSchema() throws VcxException, ExecutionException, InterruptedException { int schemaHandle = TestHelper.getResultFromFuture(SchemaApi.schemaCreate(sourceId, schemaName, schemaVersion, TestHelper.convertToValidJson(schemaData), 0)); assert (schemaHandle != 0); } @Test @DisplayName("serialise a schema") void serialiseSchema() throws VcxException, ExecutionException, InterruptedException { int schemaHandle = TestHelper.getResultFromFuture(SchemaApi.schemaCreate(sourceId, schemaName, schemaVersion, TestHelper.convertToValidJson(schemaData), 0)); String serialisedSchema = TestHelper.getResultFromFuture(SchemaApi.schemaSerialize(schemaHandle)); assert (serialisedSchema.contains(schemaName)); } @Test @DisplayName("serialise a bad schema throws InvalidSchemahandleException") void serialiseBadSchema() { Assertions.assertThrows(InvalidSchemahandleException.class, () -> { TestHelper.getResultFromFuture(SchemaApi.schemaSerialize(242)); }); } @Test @DisplayName("deserialise a schema") void deserialiseSchema() throws VcxException, ExecutionException, InterruptedException { int schemaHandle = TestHelper.getResultFromFuture(SchemaApi.schemaCreate(sourceId, schemaName, schemaVersion, TestHelper.convertToValidJson(schemaData), 0)); String serialisedSchema = TestHelper.getResultFromFuture(SchemaApi.schemaSerialize(schemaHandle)); int deserilaisedSchemaHandle = TestHelper.getResultFromFuture(SchemaApi.schemaDeserialize(serialisedSchema)); assert (deserilaisedSchemaHandle != 0); } @Test @DisplayName("get id from schema") void getId() throws VcxException, ExecutionException, InterruptedException { int schemaHandle = TestHelper.getResultFromFuture(SchemaApi.schemaCreate(sourceId, schemaName, schemaVersion, TestHelper.convertToValidJson(schemaData), 0)); String schemaId = TestHelper.getResultFromFuture(SchemaApi.schemaGetSchemaId(schemaHandle)); assert (!schemaId.equals("")); } @Test @DisplayName("get id from bad schema throws InvalidSchemaHandleException") void getIdWithError() { Assertions.assertThrows(InvalidSchemahandleException.class, () -> { TestHelper.getResultFromFuture(SchemaApi.schemaGetSchemaId(234)); }); } @Test @DisplayName("get attr from schema") void getAttributes() throws VcxException, ExecutionException, InterruptedException { int schemaHandle = TestHelper.getResultFromFuture(SchemaApi.schemaCreate(sourceId, schemaName, schemaVersion, TestHelper.convertToValidJson(schemaData), 0)); String schemaId = TestHelper.getResultFromFuture(SchemaApi.schemaGetSchemaId(schemaHandle)); String attr = TestHelper.getResultFromFuture(SchemaApi.schemaGetAttributes(sourceId, schemaId)); assert (attr.contains("height")); } @Test @DisplayName("release schema") void releaseSchema() throws VcxException, ExecutionException, InterruptedException { int schemaHandle = TestHelper.getResultFromFuture(SchemaApi.schemaCreate(sourceId, schemaName, schemaVersion, TestHelper.convertToValidJson(schemaData), 0)); int releaseHandle = SchemaApi.schemaRelease(schemaHandle); assert (releaseHandle == 0); } }
45.030928
165
0.743819
ad76e17e6327d733ad776b0e7deca26cf7285919
422
package scripts; import ir.soroushtabesh.hearthstone.controllers.game.scripts.MinionBehavior; import ir.soroushtabesh.hearthstone.controllers.game.viewmodels.MinionObject; public class Taunt extends MinionBehavior { @Override public void onCardPlay() { if (!(getOwnerObject() instanceof MinionObject)) return; ((MinionObject) getOwnerObject()).setTaunt(true); return; } }
28.133333
77
0.720379
8e6ca435b9ce29af86932b0ce79335c21d88d786
6,382
/* * Copyright [2013-2021], Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.polardbx.executor.chunk; import com.alibaba.polardbx.common.utils.GeneralUtil; import com.alibaba.polardbx.executor.vectorized.EvaluationContext; import com.alibaba.polardbx.optimizer.core.datatype.DataType; import com.google.common.base.Preconditions; import org.openjdk.jol.info.ClassLayout; import java.util.Objects; import static com.alibaba.polardbx.common.utils.memory.SizeOf.sizeOf; /** * Reference Block is only designed for the type which cannot be serialized, such as Blob and Clob */ public class ReferenceBlock<T> extends AbstractBlock { private static final long INSTANCE_SIZE = ClassLayout.parseClass(ReferenceBlock.class).instanceSize(); private Object[] values; public ReferenceBlock(DataType<T> dataType, int slotLen) { super(dataType, slotLen); this.values = new Object[slotLen]; estimatedSize = INSTANCE_SIZE + Byte.BYTES * positionCount + sizeOf(values); sizeInBytes = Byte.BYTES * positionCount + sizeOf(values); } public ReferenceBlock(int arrayOffset, int positionCount, boolean[] valueIsNull, Object[] values, DataType<T> dataType) { super(dataType, positionCount, valueIsNull, valueIsNull != null); this.values = Preconditions.checkNotNull(values); estimatedSize = INSTANCE_SIZE + sizeOf(valueIsNull) + sizeOf(values); sizeInBytes = Byte.BYTES * positionCount + sizeOf(values); } public ReferenceBlock(int arrayOffset, int positionCount, boolean[] valueIsNull, Object[] values, DataType<T> dataType, boolean hasNull) { super(dataType, positionCount, valueIsNull, hasNull); this.values = Preconditions.checkNotNull(values); estimatedSize = INSTANCE_SIZE + sizeOf(valueIsNull) + sizeOf(values); sizeInBytes = Byte.BYTES * positionCount + sizeOf(values); } @SuppressWarnings("unchecked") public T getReference(int position) { checkReadablePosition(position); return (T) values[position + arrayOffset]; } @Override public boolean equals(int position, Block otherBlock, int otherPosition) { boolean n1 = isNull(position); boolean n2 = otherBlock.isNull(otherPosition); if (n1 && n2) { return true; } else if (n1 != n2) { return false; } if (otherBlock instanceof ReferenceBlock) { return getReference(position).equals(((ReferenceBlock) otherBlock).getReference(otherPosition)); } else if (otherBlock instanceof ReferenceBlockBuilder) { return getReference(position).equals(((ReferenceBlockBuilder) otherBlock).getReference(otherPosition)); } else { throw new AssertionError(); } } @Override public T getObject(int position) { return getReference(position); } @Override public void writePositionTo(int position, BlockBuilder blockBuilder) { blockBuilder.writeObject(getObject(position)); } @Override public int hashCode(int position) { if (isNull(position)) { return 0; } return Objects.hashCode(values[position + arrayOffset]); } @Override public void copySelected(boolean selectedInUse, int[] sel, int size, RandomAccessBlock output) { if (output instanceof ReferenceBlock) { ReferenceBlock outputVectorSlot = (ReferenceBlock) output; if (selectedInUse) { for (int i = 0; i < size; i++) { int j = sel[i]; outputVectorSlot.values[j] = values[j]; } } else { System.arraycopy(values, 0, outputVectorSlot.values, 0, size); } } else { BlockUtils.copySelectedInCommon(selectedInUse, sel, size, this, output); } super.copySelected(selectedInUse, sel, size, output); } @Override public void shallowCopyTo(RandomAccessBlock another) { if (!(another instanceof ReferenceBlock)) { GeneralUtil.nestedException("cannot shallow copy to " + another == null ? null : another.toString()); } ReferenceBlock vectorSlot = (ReferenceBlock) another; super.shallowCopyTo(vectorSlot); vectorSlot.values = values; } @Override protected Object getElementAtUnchecked(int position) { return values[position]; } @Override public void setElementAt(int position, Object element) { super.updateElementAt(position, element, e -> values[position] = e); } public Object[] objectArray() { return values; } /** * Make type-specific block from this block. * * @param context Evaluation Context * @return Type-specific block. */ public Block toTypeSpecificBlock(EvaluationContext context) { BlockBuilder blockBuilder = BlockBuilders.create(dataType, context.getExecutionContext(), positionCount); int batchSize = context.getPreAllocatedChunk().batchSize(); boolean isSelectionInUse = context.getPreAllocatedChunk().isSelectionInUse(); if (isSelectionInUse) { int[] selection = context.getPreAllocatedChunk().selection(); for (int i = 0; i < batchSize; i++) { int j = selection[i]; Object value = isNull[j] ? null : values[j]; blockBuilder.writeObject(value); } } else { for (int i = 0; i < batchSize; i++) { Object value = isNull[i] ? null : values[i]; blockBuilder.writeObject(value); } } return blockBuilder.build(); } }
36.468571
115
0.646662
38aed255822d600f76499fecee6c2cadf3c46a54
5,730
package com.alipay.api.response; import java.util.Date; import java.util.List; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; import com.alipay.api.domain.TradeFundBill; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.trade.query response. * * @author auto create * @since 1.0, 2016-08-09 15:25:00 */ public class AlipayTradeQueryResponse extends AlipayResponse { private static final long serialVersionUID = 5681141974473617732L; /** * 支付宝店铺编号 */ @ApiField("alipay_store_id") private String alipayStoreId; /** * 买家支付宝账号 */ @ApiField("buyer_logon_id") private String buyerLogonId; /** * 买家实付金额,单位为元,两位小数。该金额代表该笔交易买家实际支付的金额,不包含商户折扣等金额 */ @ApiField("buyer_pay_amount") private String buyerPayAmount; /** * 买家在支付宝的用户id */ @ApiField("buyer_user_id") private String buyerUserId; /** * 本次交易支付所使用的单品券优惠的商品优惠信息 */ @ApiField("discount_goods_detail") private String discountGoodsDetail; /** * 交易支付使用的资金渠道 */ @ApiListField("fund_bill_list") @ApiField("trade_fund_bill") private List<TradeFundBill> fundBillList; /** * 行业特殊信息(例如在医保卡支付业务中,向用户返回医疗信息)。 */ @ApiField("industry_sepc_detail") private String industrySepcDetail; /** * 交易中用户支付的可开具发票的金额,单位为元,两位小数。该金额代表该笔交易中可以给用户开具发票的金额 */ @ApiField("invoice_amount") private String invoiceAmount; /** * 买家支付宝用户号,该字段将废弃,不要使用 */ @ApiField("open_id") private String openId; /** * 商家订单号 */ @ApiField("out_trade_no") private String outTradeNo; /** * 积分支付的金额,单位为元,两位小数。该金额代表该笔交易中用户使用积分支付的金额,比如集分宝或者支付宝实时优惠等 */ @ApiField("point_amount") private String pointAmount; /** * 实收金额,单位为元,两位小数。该金额为本笔交易,商户账户能够实际收到的金额 */ @ApiField("receipt_amount") private String receiptAmount; /** * 本次交易打款给卖家的时间 */ @ApiField("send_pay_date") private Date sendPayDate; /** * 商户门店编号 */ @ApiField("store_id") private String storeId; /** * 请求交易支付中的商户店铺的名称 */ @ApiField("store_name") private String storeName; /** * 商户机具终端编号 */ @ApiField("terminal_id") private String terminalId; /** * 交易的订单金额,单位为元,两位小数。该参数的值为支付时传入的total_amount */ @ApiField("total_amount") private String totalAmount; /** * 支付宝交易号 */ @ApiField("trade_no") private String tradeNo; /** * 交易状态:WAIT_BUYER_PAY(交易创建,等待买家付款)、TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)、TRADE_SUCCESS(交易支付成功)、TRADE_FINISHED(交易结束,不可退款) */ @ApiField("trade_status") private String tradeStatus; public void setAlipayStoreId(String alipayStoreId) { this.alipayStoreId = alipayStoreId; } public String getAlipayStoreId( ) { return this.alipayStoreId; } public void setBuyerLogonId(String buyerLogonId) { this.buyerLogonId = buyerLogonId; } public String getBuyerLogonId( ) { return this.buyerLogonId; } public void setBuyerPayAmount(String buyerPayAmount) { this.buyerPayAmount = buyerPayAmount; } public String getBuyerPayAmount( ) { return this.buyerPayAmount; } public void setBuyerUserId(String buyerUserId) { this.buyerUserId = buyerUserId; } public String getBuyerUserId( ) { return this.buyerUserId; } public void setDiscountGoodsDetail(String discountGoodsDetail) { this.discountGoodsDetail = discountGoodsDetail; } public String getDiscountGoodsDetail( ) { return this.discountGoodsDetail; } public void setFundBillList(List<TradeFundBill> fundBillList) { this.fundBillList = fundBillList; } public List<TradeFundBill> getFundBillList( ) { return this.fundBillList; } public void setIndustrySepcDetail(String industrySepcDetail) { this.industrySepcDetail = industrySepcDetail; } public String getIndustrySepcDetail( ) { return this.industrySepcDetail; } public void setInvoiceAmount(String invoiceAmount) { this.invoiceAmount = invoiceAmount; } public String getInvoiceAmount( ) { return this.invoiceAmount; } public void setOpenId(String openId) { this.openId = openId; } public String getOpenId( ) { return this.openId; } public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public String getOutTradeNo( ) { return this.outTradeNo; } public void setPointAmount(String pointAmount) { this.pointAmount = pointAmount; } public String getPointAmount( ) { return this.pointAmount; } public void setReceiptAmount(String receiptAmount) { this.receiptAmount = receiptAmount; } public String getReceiptAmount( ) { return this.receiptAmount; } public void setSendPayDate(Date sendPayDate) { this.sendPayDate = sendPayDate; } public Date getSendPayDate( ) { return this.sendPayDate; } public void setStoreId(String storeId) { this.storeId = storeId; } public String getStoreId( ) { return this.storeId; } public void setStoreName(String storeName) { this.storeName = storeName; } public String getStoreName( ) { return this.storeName; } public void setTerminalId(String terminalId) { this.terminalId = terminalId; } public String getTerminalId( ) { return this.terminalId; } public void setTotalAmount(String totalAmount) { this.totalAmount = totalAmount; } public String getTotalAmount( ) { return this.totalAmount; } public void setTradeNo(String tradeNo) { this.tradeNo = tradeNo; } public String getTradeNo( ) { return this.tradeNo; } public void setTradeStatus(String tradeStatus) { this.tradeStatus = tradeStatus; } public String getTradeStatus( ) { return this.tradeStatus; } }
21.222222
120
0.698778
28e5b811a3eea41060fdb5076e7148cb467b0634
507
package com.huan.common.aspect.check; import javax.validation.groups.Default; import java.lang.annotation.*; /** * 在方法、类、参数上添加该注解开启校验 * * @author <a href = "mailto:njpkhuan@gmail.com" > huan </a > * @date 2021/1/26 * @since 1.0.0 */ @Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface CheckParam { Class<?>[] specialClass() default {Object.class}; Class<?>[] value() default {Default.class}; }
23.045455
70
0.708087
57ced5650c65ed2e745de59543a72f6dbef1b29d
1,371
package pers.li.funning.utils; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author:luofeng * @createTime : 2018/10/11 11:37 * @description: 获取当前会话的request和response:在获取时,可能会出现空指针异常 */ @Deprecated public class HttpServletUtil { private static RequestAttributes ra = RequestContextHolder.getRequestAttributes(); private static WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext(); public static <T> T getHttpServletObject( Class<T> clazz){ if(clazz == HttpServletRequest.class){ return (T) ((ServletRequestAttributes)ra).getRequest(); }else if(clazz == HttpServletResponse.class){ return (T) ((ServletRequestAttributes) ra).getResponse(); } return null; } public static ServletContext getServletContext(){ ServletContext servletContext = webApplicationContext.getServletContext(); return servletContext; } }
35.153846
113
0.765864
0f3cc4e761f7bc4002038f039ee142a35754c27c
1,114
package com.udacity.critter.domain.model.user; import lombok.Getter; import lombok.Setter; import java.util.Set; import javax.persistence.*; import java.time.DayOfWeek; import lombok.NoArgsConstructor; import lombok.AllArgsConstructor; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Table(name = "employees") public class Employee { @Id @Column(name = "employee_id", nullable = false) @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "name") private String name; @ElementCollection(targetClass = EmployeeSkill.class) @Enumerated(EnumType.STRING) @CollectionTable( name = "employees_skills", joinColumns = @JoinColumn(name = "employee_id") ) @Column(name = "skill_name") private Set<EmployeeSkill> skills; @ElementCollection(targetClass = DayOfWeek.class) @Enumerated(EnumType.STRING) @CollectionTable( name = "employees_availability", joinColumns = @JoinColumn(name = "employee_id") ) @Column(name = "weekday") private Set<DayOfWeek> daysAvailable; }
24.217391
57
0.710952
bff49d5fdfa825c0c6869ef029e1a064acc0e1f9
297
package org.enricogiurin.ocp11.practice.ch3; public class Dinosaur { class Pterodactyl extends Dinosaur {} public void roar() { var dino = new Dinosaur(); dino.new Pterodactyl(); //valid new Dinosaur.Pterodactyl(); //valid ...Dinosaur prefix is optional } }
24.75
74
0.653199
155901ded9b33fb21073cba9f9c6ebb8c00c6ab8
3,330
/* * 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 Interface.Home; public class JpHome extends javax.swing.JPanel { /** * Creates new form JpHome */ public JpHome() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); setBackground(new java.awt.Color(255, 255, 255)); setPreferredSize(new java.awt.Dimension(1255, 600)); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setPreferredSize(new java.awt.Dimension(1255, 600)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Interface/Images/welcome.png"))); // NOI18N jLabel1.setMaximumSize(new java.awt.Dimension(1258, 519)); jLabel1.setMinimumSize(new java.awt.Dimension(1258, 519)); jLabel1.setPreferredSize(new java.awt.Dimension(1258, 519)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(175, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 908, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(175, 175, 175)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(163, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(165, 165, 165)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 1258, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
44.4
127
0.691592
013f08a169c81895ffc7f2cb7fb7d473d567d277
105
package com.monitor4all.tinySpring.service; public interface HelloService { void sayHelloWorld(); }
17.5
43
0.780952
91db069a537a9d32e884898b61eb098e12bcb09a
3,345
/* * 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.wink.itest.providers; import java.util.HashSet; import java.util.Set; import org.apache.wink.itest.providers.readers.MyMessageBodyReaderApplicationWildcardForShort; import org.apache.wink.itest.providers.readers.MyMessageBodyReaderForStrings; import org.apache.wink.itest.providers.readers.MyMessageBodyReaderInherited; import org.apache.wink.itest.providers.readers.MyMessageBodyReaderJSONForInteger; import org.apache.wink.itest.providers.readers.MyMessageBodyReaderJSONForLong; import org.apache.wink.itest.providers.readers.MyMessageBodyReaderJSONForShort; import org.apache.wink.itest.providers.readers.MyMessageBodyReaderWildcardForShort; import org.apache.wink.itest.providers.readers.MyMessageBodyReaderXMLAndJSONForNumber; public class Application extends javax.ws.rs.core.Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> clazzes = new HashSet<Class<?>>(); clazzes.add(MyResource.class); return clazzes; } @Override public Set<Object> getSingletons() { Set<Object> objs = new HashSet<Object>(); objs.add(new ExceptionMapperForMyException()); objs.add(new MyJAXBContextResolverForXML()); objs.add(new MyExceptionContextResolver()); objs.add(new MyStringContextForAllWildcard()); objs.add(new MyStringContextForTextWildcard()); objs.add(new MyStringContextResolverForXML()); objs.add(new MyStringContextResolverForXML2()); objs.add(new MyStringContextResolverForXMLAndJSON()); objs.add(new MyMessageBodyWriterJSONForInteger()); objs.add(new MyMessageBodyWriterJSONForLong()); objs.add(new MyMessageBodyWriterXMLAndJSONForNumber()); objs.add(new MyMessageBodyWriterJSONForShort()); objs.add(new MyMessageBodyWriterApplicationWildcardForShort()); objs.add(new MyMessageBodyWriterWildcardForShort()); objs.add(new MyStringWriterForStrings()); objs.add(new MyMessageBodyWriterInherited()); objs.add(new MyMessageBodyReaderJSONForInteger()); objs.add(new MyMessageBodyReaderJSONForLong()); objs.add(new MyMessageBodyReaderXMLAndJSONForNumber()); objs.add(new MyMessageBodyReaderApplicationWildcardForShort()); objs.add(new MyMessageBodyReaderJSONForShort()); objs.add(new MyMessageBodyReaderWildcardForShort()); objs.add(new MyMessageBodyReaderForStrings()); objs.add(new MyMessageBodyReaderInherited()); return objs; } }
42.884615
94
0.749776
54f994c7855dba6d9027142aa78fe09d473227a6
494
package glomer.mongodb.exception; public class DocumentHasChildrenException extends Exception { private static final long serialVersionUID = 1L; public DocumentHasChildrenException() { } public DocumentHasChildrenException(String message) { super(message); } public DocumentHasChildrenException(Throwable cause) { super(cause); } public DocumentHasChildrenException(String message, Throwable cause) { super(message, cause); } }
22.454545
74
0.714575
54abbc31175820bcacb8bc1227f0c774fc1a9c18
3,953
package de.wackernagel.android.example.sidekick; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final SimpleAdapter adapter = new SimpleAdapter(); adapter.setItems(Arrays.asList( new SimpleItem( "Widgets - AspectRatioImageView", AspectRatioImageViewActivity.class ), new SimpleItem( "Widgets - CircularRevealView", RevealViewActivity.class ), new SimpleItem( "Widgets - IndicatorView", IndicatorActivity.class ), new SimpleItem( "Utils - Tooltip", TooltipActivity.class ), new SimpleItem( "Utils - ColorFilterUtils", ColorFilterUtilsActivity.class ), new SimpleItem( "Utils - Device and Network", DeviceActivity.class ), new SimpleItem( "Utils - Drawable Tinting", TintingActivity.class ), new SimpleItem( "Helper - Grid Gutter Decoration", GridGutterDecorationActivity.class ), new SimpleItem( "Resources - Colors", ColorsActivity.class ) )); final RecyclerView recyclerView = ( RecyclerView ) findViewById(R.id.recyclerView); recyclerView.setAdapter( adapter ); } private static class SimpleItem { final String name; final Class<?> activity; SimpleItem(String name, Class<?> activity) { this.name = name; this.activity = activity; } } private static class SimpleAdapter extends RecyclerView.Adapter<SimpleViewHolder> { private ArrayList<SimpleItem> items = new ArrayList<>(); private LayoutInflater inflater = null; void setItems( List<SimpleItem> items ) { clearItems(); addItems(items); } void addItems( List<SimpleItem> items ) { this.items.addAll( items ); notifyItemRangeInserted( items.size(), items.size() ); } void clearItems() { int size = items.size(); this.items.clear(); notifyItemRangeRemoved(0, size); } SimpleItem getItem( int position ) { return items.get( position ); } @Override public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if( inflater == null ) inflater = LayoutInflater.from( parent.getContext() ); return new SimpleViewHolder(inflater.inflate( R.layout.simple_item, parent, false ) ); } @Override public void onBindViewHolder(SimpleViewHolder holder, int position) { final int adaptPos = holder.getAdapterPosition(); holder.text.setText( items.get( position ).name ); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if( adaptPos != RecyclerView.NO_POSITION ) v.getContext().startActivity(new Intent(v.getContext(), getItem(adaptPos).activity)); } }); } @Override public int getItemCount() { return items.size(); } } private static class SimpleViewHolder extends RecyclerView.ViewHolder { TextView text; SimpleViewHolder(View itemView) { super(itemView); text = ( TextView ) itemView.findViewById(R.id.text); } } }
35.936364
109
0.627119
889135fef746c5792bf0ca28a927c680825459a7
2,037
package AlgeRule; import AlgeNode.AlgeNode; import AlgeNode.SPJNode; import AlgeNode.EmptyNode; import SymbolicRexNode.BoolPredicate; import SymbolicRexNode.RexNodeUtility; import SymbolicRexNode.RexNotIn; import SymbolicRexNode.SymbolicColumn; import Z3Helper.z3Utility; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import org.apache.calcite.rex.RexNode; import java.util.ArrayList; import java.util.List; import java.util.Set; public class SPJ2Empty extends AlgeRuleBase{ public SPJ2Empty (AlgeNode input) { this.input = input ;} @Override public boolean preCondition() { if (this.input instanceof SPJNode) { SPJNode spjNode = (SPJNode) this.input; List<BoolExpr> assign = new ArrayList<>(); Set<RexNode> conditions = spjNode.getConditions(); if(!conditions.isEmpty()) { Context z3Context = this.input.getZ3Context(); List<SymbolicColumn> inputSymbolicColumns = inputSymbolicColumns(spjNode,z3Context); RexNodeUtility.reset(); SymbolicColumn symbolicCondition = BoolPredicate.getAndNodeSymbolicColumn(conditions,inputSymbolicColumns,assign,z3Context); RexNodeUtility.reset(); assign.add(symbolicCondition.isValueTrue()); if(z3Utility.isUnsat(z3Utility.mkAnd(assign,z3Context),z3Context)) { return true; } } } return false; } private List<SymbolicColumn> inputSymbolicColumns (SPJNode node,Context z3Context) { List<SymbolicColumn> inputColumns = new ArrayList<>(); for (AlgeNode input : node.getInputs()){ for (RexNode outputExpr : input.getOutputExpr()){ inputColumns.add(SymbolicColumn.mkNewSymbolicColumn(z3Context,outputExpr)); } } return inputColumns; } @Override public AlgeNode transformation() { return (new EmptyNode(this.input.getZ3Context())); } }
35.12069
140
0.667649
6c71ed6eb69e4dd7200843c180e1907f9c4921e3
2,918
package search; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.lucene.analysis.en.EnglishAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.deeplearning4j.models.embeddings.wordvectors.WordVectors; import org.nd4j.linalg.ops.transforms.Transforms; import strategy.enwiki.ENWikiIndexStrategy; import strategy.table.TableStrategy; import utils.Consts; import utils.LuceneTools; import java.io.IOException; import java.util.Arrays; public class TableReranker { public static final double GAMMA = 0.2; private static final Logger logger = LogManager.getLogger(TableReranker.class); private final WordVectors wordVectors; private final ENWikiSearcher enWikiSearcher; private final TableStrategy tableStrategy; public TableReranker(WordVectors wordVectors, ENWikiSearcher enWikiSearcher, TableStrategy tableStrategy) { this.wordVectors = wordVectors; this.enWikiSearcher = enWikiSearcher; this.tableStrategy = tableStrategy; } public ScoreDoc[] rerank(ScoreDoc[] scoreDocs, IndexSearcher indexSearcher, String queryString) throws IOException { ScoreDoc[] rerankedScores = new ScoreDoc[scoreDocs.length]; try { for (int i = 0; i < scoreDocs.length; i++) { var scoreDoc = scoreDocs[i]; var docID = scoreDoc.doc; var newScore = calculateScore(indexSearcher.doc(docID), queryString); rerankedScores[i] = new ScoreDoc(docID, newScore); } Arrays.sort(rerankedScores, (o1, o2) -> Float.compare(o2.score, o1.score)); } catch (Exception e) { return scoreDocs; } return rerankedScores; } public float calculateScore(Document document, String queryString) throws IOException { var pgTitle = document.get(Consts.PAGE_TITLE); var documentLabels = tableStrategy.getDocumentLabels(document); var documentMean = wordVectors.getWordVectorsMean(documentLabels); var topWikiDoc = enWikiSearcher.searchTopDocument(pgTitle); var wikiText = topWikiDoc.get(ENWikiIndexStrategy.FIELD_TEXT); var engAnalyzer = new EnglishAnalyzer(); var queryLabels = LuceneTools.tokenizeString(engAnalyzer, queryString); var queryMean = wordVectors.getWordVectorsMean(queryLabels); var wikitextLabels = LuceneTools.tokenizeString(engAnalyzer, wikiText); var wikitextMean = wordVectors.getWordVectorsMean(wikitextLabels); var cosineSimWikitextToQuery = Transforms.cosineSim(queryMean, wikitextMean); var cosineSimDocumentToQuery = Transforms.cosineSim(queryMean, documentMean); return (float) ((1 - GAMMA) * cosineSimWikitextToQuery + (GAMMA) * cosineSimDocumentToQuery); } }
44.212121
120
0.727553
35c536e9470b73d3a264f332209972de5dd51373
1,733
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache; import org.ehcache.config.persistence.PersistenceConfiguration; import org.ehcache.exceptions.StateTransitionException; import org.junit.Test; import java.io.File; import static org.ehcache.CacheManagerBuilder.newCacheManagerBuilder; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Alex Snaps */ public class PersistentCacheManagerTest { @Test public void testInitializesLocalPersistenceService() { final File rootDirectory = mock(File.class); when(rootDirectory.exists()).thenReturn(true); when(rootDirectory.getAbsolutePath()).thenReturn("CRAP!"); try { newCacheManagerBuilder().with(new PersistenceConfiguration(rootDirectory)).build(true); } catch (Exception e) { assertThat(e, instanceOf(StateTransitionException.class)); assertThat(e.getCause(), instanceOf(IllegalArgumentException.class)); assertThat(e.getCause().getMessage().endsWith("CRAP!"), is(true)); } } }
33.980392
93
0.757646
9436448bc15e77b52685515299ffdb43d1046588
1,447
/** * Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caintegrator/LICENSE.txt for details. */ package gov.nih.nci.caintegrator.application.study; import gov.nih.nci.caintegrator.domain.AbstractCaIntegrator2Object; import gov.nih.nci.caintegrator.domain.application.Query; /** * An AuthorizedQuery is a <code>Query</code> that has been * authorized for inclusion in an <code>AuthorizedStudyElementsGroup</code>. */ public class AuthorizedQuery extends AbstractCaIntegrator2Object { private static final long serialVersionUID = 1L; private Query query; private AuthorizedStudyElementsGroup authorizedStudyElementsGroup; /** * @param query the query to set */ public void setQuery(Query query) { this.query = query; } /** * @return the Query */ public Query getQuery() { return query; } /** * @param authorizedStudyElementsGroup the authorizedStudyElementsGroup to set */ public void setAuthorizedStudyElementsGroup(AuthorizedStudyElementsGroup authorizedStudyElementsGroup) { this.authorizedStudyElementsGroup = authorizedStudyElementsGroup; } /** * @return the authorizedStudyElementsGroup */ public AuthorizedStudyElementsGroup getAuthorizedStudyElementsGroup() { return authorizedStudyElementsGroup; } }
30.145833
108
0.724257
88ac389cd68a35e4a74e1c5ff8e66e160b0e37ec
377
public class Solution { public int reverse(int a) { String str = String.valueOf(a); StringBuilder sb = new StringBuilder(str); String rev = sb.reverse().toString(); try{ if(a<0){ return(Integer.valueOf(rev)*-1); }else{ return(Integer.valueOf(rev)); } }catch(Exception e){ return(0); } } }
17.952381
50
0.535809
e6cb4b06de4f9032e49c050c575bc54dcac0a339
1,709
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.uiDesigner; import com.intellij.designer.DesignerEditorPanelFacade; import com.intellij.designer.LightToolWindowManager; import com.intellij.designer.ToggleEditorModeAction; import com.intellij.ide.palette.impl.PaletteToolWindowManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindowAnchor; import com.intellij.uiDesigner.editor.UIFormEditor; import com.intellij.uiDesigner.propertyInspector.DesignerToolWindowManager; import org.jetbrains.annotations.Nullable; /** * @author Alexander Lobas */ public abstract class AbstractToolWindowManager extends LightToolWindowManager { protected AbstractToolWindowManager(Project project) { super(project); } @Nullable @Override protected DesignerEditorPanelFacade getDesigner(FileEditor editor) { if (editor instanceof UIFormEditor) { UIFormEditor formEditor = (UIFormEditor)editor; return formEditor.getEditor(); } return null; } @Override protected ToggleEditorModeAction createToggleAction(ToolWindowAnchor anchor) { return new ToggleEditorModeAction(this, myProject, anchor) { @Override protected LightToolWindowManager getOppositeManager() { AbstractToolWindowManager designerManager = DesignerToolWindowManager.getInstance(myProject); AbstractToolWindowManager paletteManager = PaletteToolWindowManager.getInstance(myProject); return myManager == designerManager ? paletteManager : designerManager; } }; } }
38.840909
140
0.794617
3246672a0030337e4d4320adce9585643f1d05de
5,201
package com.gentics.mesh.etc.config; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.gentics.mesh.etc.config.env.EnvironmentVariable; import com.gentics.mesh.etc.config.env.Option; import io.vertx.core.json.JsonObject; public class OAuth2ServerConfig implements Option { private static final String MESH_AUTH_OAUTH2_SERVER_CONF_REALM_ENV = "MESH_AUTH_OAUTH2_SERVER_CONF_REALM"; private static final String MESH_AUTH_OAUTH2_SERVER_CONF_AUTH_SERVER_URL_ENV = "MESH_AUTH_OAUTH2_SERVER_CONF_AUTH_SERVER_URL"; private static final String MESH_AUTH_OAUTH2_SERVER_CONF_AUTH_SSL_REQUIRED_ENV = "MESH_AUTH_OAUTH2_SERVER_CONF_AUTH_SSL_REQUIRED"; private static final String MESH_AUTH_OAUTH2_SERVER_CONF_RESOURCE_ENV = "MESH_AUTH_OAUTH2_SERVER_CONF_RESOURCE"; private static final String MESH_AUTH_OAUTH2_SERVER_CONF_CONFIDENTIAL_PORT_ENV = "MESH_AUTH_OAUTH2_SERVER_CONF_CONFIDENTIAL_PORT"; static final String MESH_AUTH_OAUTH2_SERVER_CONF_CREDENTIALS = "MESH_AUTH_OAUTH2_SERVER_CONF_CREDENTIALS"; @JsonProperty(required = true) @JsonPropertyDescription("Realm name to be used.") @EnvironmentVariable(name = MESH_AUTH_OAUTH2_SERVER_CONF_REALM_ENV, description = "Override the configured OAuth2 server realm.") private String realm = "master"; @JsonProperty(required = true) @JsonPropertyDescription("URL to the authentication server.") @EnvironmentVariable(name = MESH_AUTH_OAUTH2_SERVER_CONF_AUTH_SERVER_URL_ENV, description = "Override the configured OAuth2 server URL.") private String authServerUrl = "http://localhost:3000/auth"; @JsonProperty(required = false) @JsonPropertyDescription("SSL Required flag of the realm.") @EnvironmentVariable(name = MESH_AUTH_OAUTH2_SERVER_CONF_AUTH_SSL_REQUIRED_ENV, description = "Override the configured OAuth2 server SSL-required flag.") private String sslRequired = "external"; @JsonProperty(required = false) @JsonPropertyDescription("Name of the resource to be used.") @EnvironmentVariable(name = MESH_AUTH_OAUTH2_SERVER_CONF_RESOURCE_ENV, description = "Override the configured OAuth2 server resource name.") private String resource; @JsonProperty(required = false) @JsonPropertyDescription("Additional credentials for client-server communication.") private Map<String, String> credentials = new HashMap<>(); @JsonProperty(required = false) @EnvironmentVariable(name = MESH_AUTH_OAUTH2_SERVER_CONF_CONFIDENTIAL_PORT_ENV, description = "Override the configured OAuth2 confidential port.") private int confidentialPort = 0; /** * Return the realm name. * * @return */ public String getRealm() { return realm; } /** * Set the realm name. * * @param realm * @return Fluent API */ public OAuth2ServerConfig setRealm(String realm) { this.realm = realm; return this; } /** * Return the authentication server url. * * @return */ public String getAuthServerUrl() { return authServerUrl; } /** * Return the authentication server url. * * @param authServerUrl * @return Fluent API */ public OAuth2ServerConfig setAuthServerUrl(String authServerUrl) { this.authServerUrl = authServerUrl; return this; } public String getSslRequired() { return sslRequired; } public OAuth2ServerConfig setSslRequired(String sslRequired) { this.sslRequired = sslRequired; return this; } public String getResource() { return resource; } public OAuth2ServerConfig setResource(String resource) { this.resource = resource; return this; } public int getConfidentialPort() { return confidentialPort; } public OAuth2ServerConfig setConfidentialPort(int confidentialPort) { this.confidentialPort = confidentialPort; return this; } /** * Return the configured credentials. * * @return */ public Map<String, String> getCredentials() { return credentials; } public OAuth2ServerConfig setCredentials(Map<String, String> credentials) { this.credentials = credentials; return this; } @EnvironmentVariable(name = MESH_AUTH_OAUTH2_SERVER_CONF_CREDENTIALS, description = "Override the configured OAuth2 server credentials (as JSON Object String).") public void setCredentialsViaEnv(JsonObject credentialsObject) { for(String key : credentialsObject.fieldNames()) { Object val = credentialsObject.getValue(key); if (val == null || val instanceof String) { this.addCredential(key, (String) val); } } } /** * Add the given credential pair to the map of credentials. * * @param key * @param value * @return Fluent API */ public OAuth2ServerConfig addCredential(String key, String value) { this.credentials.put(key, value); return this; } @JsonIgnore public JsonObject toJson() { JsonObject config = new JsonObject(); config.put("realm", getRealm()); config.put("auth-server-url", getAuthServerUrl()); config.put("ssl-required", getSslRequired()); config.put("resource", getResource()); config.put("credentials", getCredentials()); config.put("confidential-port", getConfidentialPort()); return config; } }
30.958333
162
0.772928
3637894f2616eeb43857d3237b9ccf839f8f69ad
4,400
package recyclerview; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.ListAdapter; import androidx.recyclerview.widget.RecyclerView; import com.example.nachtaktiverhalbaffe.kartenspiele.R; import java.util.Objects; import Database.Kartenspiele.Kartenspiel; public class kartenspiele_adapter extends ListAdapter<Kartenspiel, kartenspiele_adapter.Kartenspiele_ListViewHolder> { public String mId; public static String id; View.OnClickListener itemClickListener = null; public kartenspiele_adapter(View.OnClickListener itemClickListener) { super(DIFF_CALLBACK); this.itemClickListener = itemClickListener; } private static final DiffUtil.ItemCallback<Kartenspiel> DIFF_CALLBACK = new DiffUtil.ItemCallback<Kartenspiel>() { @Override public boolean areItemsTheSame(@NonNull Kartenspiel oldItem, @NonNull Kartenspiel newItem) { return oldItem.getName().equals(newItem.getName()); } @Override public boolean areContentsTheSame(@NonNull Kartenspiel oldItem, @NonNull Kartenspiel newItem) { return oldItem.getName().equals(newItem.getName()) && Objects.equals(oldItem.getKartendeck(), newItem.getKartendeck()) && Objects.equals(oldItem.getKomplexitaet(),newItem.getKomplexitaet()) && oldItem.getSpieleranzahl_min()==newItem.getSpieleranzahl_min() && oldItem.getSpieleranzahl_max()==newItem.getSpieleranzahl_max() && oldItem.getSpielzeit().equals(newItem.getSpielzeit()); }}; class Kartenspiele_ListViewHolder extends RecyclerView.ViewHolder { public TextView name, spielzeit, spieleranzahl, komplexitaet, kartendeck; ImageView icon; CardView cv; public Kartenspiele_ListViewHolder(View itemView, View.OnClickListener itemClickListener) { //Variablen für cards setzen super(itemView); icon= itemView.findViewById(R.id.kartenspiel_icon); name= itemView.findViewById(R.id.spielname); spielzeit = itemView.findViewById(R.id.spielzeit); spieleranzahl = itemView.findViewById(R.id.spieleranzahl); komplexitaet = itemView.findViewById(R.id.komplex); kartendeck = itemView.findViewById(R.id.kartendeck); cv= itemView.findViewById(R.id.kartenspiel_cardview); cv.setClickable(true); } } @Override public kartenspiele_adapter.Kartenspiele_ListViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.kartenspiele_card, null); Kartenspiele_ListViewHolder holder = new Kartenspiele_ListViewHolder(v, itemClickListener); return holder; } @Override public void onBindViewHolder(final kartenspiele_adapter.Kartenspiele_ListViewHolder holder, int position) { final Kartenspiel list = getItem(position); holder.cv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Id setzen zum eindeutigen identifizieren der Partie mId = list.getName(); id = mId; //Neuen Onclicklistener zum editieren und automatisch drücken holder.cv.setOnClickListener(itemClickListener); holder.cv.performClick();} }); //Partiebezeichnung und Spielernamen setzen (Sind fest im Layout Implementiert) String spieleranzahl = String.valueOf(list.getSpieleranzahl_min()).toString() + "-" + String.valueOf(list.getSpieleranzahl_max()).toString(); holder.icon.setImageResource(list.getIcon()); holder.kartendeck.setText(list.getKartendeck()); holder.komplexitaet.setText(list.getKomplexitaet()); holder.spieleranzahl.setText(spieleranzahl); holder.spielzeit.setText(list.getSpielzeit()); holder.name.setText(list.getName()); } @Override public int getItemViewType(int position) { return position; } }
41.509434
181
0.700455
ab0c6c34d98c219ddea625d2b1bcb10898b2adc4
1,843
package net.fushizen.invokedynamic.proxy; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ArbitraryConstructorTests { public static class Superclass { final boolean b; final char c; final short s; final int i; final long l; final float f; final double d; final Object o; public Superclass(boolean b, char c, short s, int i, long l, float f, double d, Object o) { this.b = b; this.c = c; this.s = s; this.i = i; this.l = l; this.f = f; this.d = d; this.o = o; } } @Test public void testArbitraryConstructor() throws Throwable { DynamicProxy dynamicProxy = DynamicProxy.builder() .withSuperclass(Superclass.class) .withConstructor( Boolean.TYPE, Character.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE, Object.class ) .build(); Superclass obj = dynamicProxy.construct( true, 'a', (short)1234, 0x7FFFFFFF, 0x1_0000_0000L, 0.123f, 0.555d, "hello, world" ); assertEquals(true, obj.b); assertEquals('a', obj.c); assertEquals(1234, obj.s); assertEquals(0x7FFFFFFF, obj.i); assertEquals(0x1_0000_0000L, obj.l); assertEquals(0.123f, obj.f, 0.01); assertEquals(0.555d, obj.d, 0.01); assertEquals("hello, world", obj.o); } }
27.507463
99
0.467173
20b8fe72edb75b33f16f9af7747aae9c2bec02d4
311
package com.bootdo.clouddoadmin.constants; /** * @author bootdo 1992lcg@163.com * @version V1.0 */ public class Constants { public static final String USER_TOKEN_ID = "userId"; public static final String USER_TOKEN_NAME = "name"; public static final String JWT_PRIVATE_KEY = "wwwwbootdocom"; }
23.923077
65
0.729904
21e936043ac41fab12029d8b4af78c90b4c72455
1,335
package com.jakubeeee.iotaccess.core; import org.testcontainers.containers.PostgreSQLContainer; /** * Singleton class used for initialization of docker container able to run PostgreSQL database for testing purposes. It * specifies the database version, publishes database url, username and password as environmental variables and makes * sure only one instance of the database can be created at the same time. */ public class CustomPostgreSQL12Container extends PostgreSQLContainer<CustomPostgreSQL12Container> { private static final String IMAGE_TAG = "postgres:12"; private static CustomPostgreSQL12Container container; private CustomPostgreSQL12Container() { super(IMAGE_TAG); } public static CustomPostgreSQL12Container getInstance() { if (container == null) container = new CustomPostgreSQL12Container(); return container; } @Override public void start() { super.start(); System.setProperty("TEST_POSTGRESQL_URL", container.getJdbcUrl()); System.setProperty("TEST_POSTGRESQL_USERNAME", container.getUsername()); System.setProperty("TEST_POSTGRESQL_PASSWORD", container.getPassword()); } @Override public void stop() { // do nothing - the container will be destroyed along with jvm instance } }
34.230769
119
0.731086
ca26c0e318e1235a442b1845e4790671efefcc77
1,442
package com.imm; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; /** * 启动程序 * * @author imm */ @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) @MapperScan("com.imm.*.mapper") public class ImmApplication { public static void main(String[] args) { // System.setProperty("spring.devtools.restart.enabled", "false"); SpringApplication.run(ImmApplication.class, args); System.out.println("(♥◠‿◠)ノ゙ IMM启动成功 ლ(´ڡ`ლ)゙ \n" + " ___ ___ \n" + " ___ /__/\\ /__/\\ \n" + " / /\\ | |::\\ | |::\\ \n" + " / /:/ | |:|:\\ | |:|:\\ \n" + " /__/::\\ __|__|:|\\:\\ __|__|:|\\:\\ \n" + " \\__\\/\\:\\__ /__/::::| \\:\\ /__/::::| \\:\\\n" + " \\ \\:\\/\\ \\ \\:\\~~\\__\\/ \\ \\:\\~~\\__\\/\n" + " \\__\\::/ \\ \\:\\ \\ \\:\\ \n" + " /__/:/ \\ \\:\\ \\ \\:\\ \n" + " \\__\\/ \\ \\:\\ \\ \\:\\ \n" + " \\__\\/ \\__\\/ "); } }
42.411765
79
0.389736
bd293e89afc47a2a0da22183277250e7aeb7146a
258
package com.davidbracewell.apollo.linear; /** * @author David B. Bracewell */ public class DenseFloatNDArrayTest extends BaseNDArrayTest { public DenseFloatNDArrayTest() { super(NDArrayFactory.DENSE_FLOAT); } }// END OF DenseDoubleNDArrayTest
23.454545
60
0.755814
0eaee574ac682cb7f15c15af5a71dcd467caea4e
1,884
package com.qa.ims.persistence.domain; public class Order { private Long order_id; private Long cust_id; private Double totalPrice; public Order(Long cust_id, Double totalPrice) { this.cust_id = cust_id; this.totalPrice = totalPrice; } public Order(Long order_id, Long cust_id, Double totalPrice) { this.order_id = order_id; this.cust_id = cust_id; this.totalPrice = totalPrice; } public Long getOrder_id() { return order_id; } public void setOrder_id(Long order_id) { this.order_id = order_id; } public Long getCust_id() { return cust_id; } public void setCust_id(Long cust_id) { this.cust_id = cust_id; } public Double getTotalPrice() { return totalPrice; } public void setTotalPrice(Double totalPrice) { this.totalPrice = totalPrice; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cust_id == null) ? 0 : cust_id.hashCode()); result = prime * result + ((order_id == null) ? 0 : order_id.hashCode()); result = prime * result + ((totalPrice == null) ? 0 : totalPrice.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Order other = (Order) obj; if (cust_id == null) { if (other.cust_id != null) return false; } else if (!cust_id.equals(other.cust_id)) return false; if (order_id == null) { if (other.order_id != null) return false; } else if (!order_id.equals(other.order_id)) return false; if (totalPrice == null) { if (other.totalPrice != null) return false; } else if (!totalPrice.equals(other.totalPrice)) return false; return true; } public String toString() { return "order_id:" + order_id + " cust_id:" + cust_id + " totalPrice:" + totalPrice; } }
22.164706
86
0.666136
9175fc49ba4dba3f119650a42bc5f95185f1c790
5,565
/* * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.exec.tez; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import com.google.common.base.Preconditions; import org.apache.commons.lang.ArrayUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.serde2.SerDeUtils; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.InputSplit; import org.apache.hadoop.mapred.split.SplitLocationProvider; import org.apache.hive.common.util.Murmur3; import org.apache.tez.runtime.api.InputInitializerContext; import org.slf4j.Logger; public class Utils { public static SplitLocationProvider getSplitLocationProvider(Configuration conf, Logger LOG) throws IOException { // fall back to checking confs return getSplitLocationProvider(conf, true, LOG); } public static SplitLocationProvider getSplitLocationProvider(Configuration conf, boolean useCacheAffinity, Logger LOG) throws IOException { return getSplitLocationProvider(conf, useCacheAffinity, null, LOG); } public static SplitLocationProvider getSplitLocationProvider(Configuration conf, boolean useCacheAffinity, InputInitializerContext context, Logger LOG) throws IOException { String engine = HiveConf.getVar(conf, HiveConf.ConfVars.HIVE_EXECUTION_ENGINE); boolean useCustomLocations = HiveConf.getVar(conf, HiveConf.ConfVars.HIVE_EXECUTION_MODE).equals("llap") && HiveConf.getBoolVar(conf, HiveConf.ConfVars.LLAP_CLIENT_CONSISTENT_SPLITS) && useCacheAffinity && (engine.equals("mr3") || engine.equals("tez")) && context != null; SplitLocationProvider splitLocationProvider; LOG.info("SplitGenerator using llap affinitized locations: " + useCustomLocations); if (useCustomLocations) { splitLocationProvider = new SplitLocationProvider() { @Override public String[] getLocations(InputSplit split) throws IOException { if (!(split instanceof FileSplit)) { return split.getLocations(); } FileSplit fsplit = (FileSplit) split; long hash = hash1(getHashInputForSplit(fsplit.getPath().toString(), fsplit.getStart())); String location = context.getLocationHintFromHash(hash); if (LOG.isDebugEnabled()) { String splitDesc = "Split at " + fsplit.getPath() + " with offset=" + fsplit.getStart(); LOG.debug(splitDesc + " mapped to location=" + location); } return (location != null) ? new String[] { location } : null; } private byte[] getHashInputForSplit(String path, long start) { // Explicitly using only the start offset of a split, and not the length. Splits generated on // block boundaries and stripe boundaries can vary slightly. Try hashing both to the same node. // There is the drawback of potentially hashing the same data on multiple nodes though, when a // large split is sent to 1 node, and a second invocation uses smaller chunks of the previous // large split and send them to different nodes. byte[] pathBytes = path.getBytes(); byte[] allBytes = new byte[pathBytes.length + 8]; System.arraycopy(pathBytes, 0, allBytes, 0, pathBytes.length); SerDeUtils.writeLong(allBytes, pathBytes.length, start >> 3); return allBytes; } private long hash1(byte[] bytes) { final int PRIME = 104729; // Same as hash64's default seed. return Murmur3.hash64(bytes, 0, bytes.length, PRIME); } @Override public String toString() { return "LLAP SplitLocationProvider"; } }; } else { splitLocationProvider = new SplitLocationProvider() { @Override public String[] getLocations(InputSplit split) throws IOException { if (split == null) { return null; } String[] locations = split.getLocations(); if (locations != null && locations.length == 1) { if ("localhost".equals(locations[0])) { return ArrayUtils.EMPTY_STRING_ARRAY; } } return locations; } @Override public String toString() { return "Default SplitLocationProvider"; } }; } return splitLocationProvider; } }
43.476563
105
0.647799
03e7ada0477476653590e1a547d5ce0c9dc7ffd5
139
package com.aliexpress.tool.jcombo; public class JCombo { public static void main(String args[]) { new MainWindow(); } }
15.444444
44
0.647482
255b6e2bf54a689a73c63433bc48f9b78ab15e78
1,099
package fun.yanwk.helloquarkus.rest.json; import javax.ws.rs.*; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Set; @Path("/fruits") @Produces("application/json") // 虽然 RESTEasy 支持自动协商, @Consumes("application/json") // 但 Quarkus 强烈建议添加这两个注解,有助于 native 构建时分析所需 JAX-RS provider 种类,缩减程序大小。 public class FruitResource { private final Set<Fruit> fruits = Collections.newSetFromMap(Collections.synchronizedMap(new LinkedHashMap<>())); /** * 填充一点初始数据 */ public FruitResource() { fruits.add(new Fruit("Apple", "Winter fruit")); fruits.add(new Fruit("Pineapple", "Tropical fruit")); } @GET public Set<Fruit> list() { return fruits; } @POST public Set<Fruit> add(Fruit fruit) { fruits.add(fruit); return fruits; } /** * 删除逻辑还是有点问题的 * @param fruit 这个对象的反序列化有问题 * @return 返回全部列表 */ @DELETE public Set<Fruit> delete(Fruit fruit) { fruits.removeIf(existingFruit -> existingFruit.name.contentEquals(fruit.name)); return fruits; } }
23.891304
116
0.646952
3217ebb460e1091706d478efd974b01fc81f93b1
370
package kr.co.sosang.sosofriends.admin.dao; import java.util.List; import java.util.Map; import kr.co.sosang.sosofriends.admin.domain.NoticeInfo; public interface AdminDAO { public int getlastNum(String k_code) throws Exception; public int addItems(Map<String, Object> param)throws Exception; public List<Map<String,Object>> selectUserList()throws Exception; }
23.125
66
0.794595
8b894e83802ec8117d252558baada39ba07c80dd
32,310
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.controle.view; import com.controle.dao.CondominioDAO; import com.controle.dao.DAOFactory; import com.controle.modelo.Condominio; import com.utilitarios.Formatados; import java.text.ParseException; import javax.swing.JFormattedTextField; import javax.swing.JOptionPane; import javax.swing.JTextField; /** * * @author Daniel */ public class FrmCadMorador extends javax.swing.JInternalFrame { /** * Creates new form FrmCadCondominio * * @throws java.text.ParseException */ public FrmCadMorador() throws ParseException { initComponents(); Formatados.mascara(jFormattedTextFieldFone, "(##)####-####"); Formatados.mascara(jFormattedTextFieldCpf, "###.###.###-##"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jTextFieldCodigo = new javax.swing.JTextField(); jTextFieldNome = new javax.swing.JTextField(); jTextFieldApto = new javax.swing.JTextField(); jTextFieldBloco = new javax.swing.JTextField(); jFormattedTextFieldFone = new javax.swing.JFormattedTextField(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jFormattedTextFieldFracaoIdeal = new javax.swing.JFormattedTextField(); jFormattedTextFieldCota = new javax.swing.JFormattedTextField(); jLabel16 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jButtonNovo = new javax.swing.JButton(); jButtonSalvar = new javax.swing.JButton(); jButtonExcluir = new javax.swing.JButton(); jButtonSair = new javax.swing.JButton(); jButtonPesquisar = new javax.swing.JButton(); jButtonEditar = new javax.swing.JButton(); jTextFieldPesquisa = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jButtonPrimeiro = new javax.swing.JButton(); jButtonAnterior = new javax.swing.JButton(); jButtonProximo = new javax.swing.JButton(); jButtonUltimo = new javax.swing.JButton(); jLabel18 = new javax.swing.JLabel(); jFormattedTextFieldCpf = new javax.swing.JFormattedTextField(); jLabel21 = new javax.swing.JLabel(); jComboBoxCondominio = new javax.swing.JComboBox<>(); jLabel9 = new javax.swing.JLabel(); jFormattedTextFieldFone1 = new javax.swing.JFormattedTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setClosable(true); jLabel1.setText("Código:"); jLabel2.setText("Nome:"); jLabel4.setText("Apto:"); jLabel5.setText("Bloco:"); jLabel7.setText("Telefone:"); jTextFieldCodigo.setEnabled(false); jTextFieldNome.setEnabled(false); jTextFieldApto.setEnabled(false); jTextFieldBloco.setEnabled(false); jFormattedTextFieldFone.setEnabled(false); jLabel14.setText("Fração Ideal:"); jLabel15.setText("Valor Cota:"); jFormattedTextFieldFracaoIdeal.setEnabled(false); jFormattedTextFieldCota.setEnabled(false); jLabel16.setFont(new java.awt.Font("sansserif", 0, 24)); // NOI18N jLabel16.setText("Cadastro Morador"); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jButtonNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/controlecondominio/imagens/add.png"))); // NOI18N jButtonNovo.setToolTipText("Novo"); jButtonNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonNovoActionPerformed(evt); } }); jButtonSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/controlecondominio/imagens/accept.png"))); // NOI18N jButtonSalvar.setToolTipText("Salvar"); jButtonSalvar.setEnabled(false); jButtonSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSalvarActionPerformed(evt); } }); jButtonExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/controlecondominio/imagens/application_remove.png"))); // NOI18N jButtonExcluir.setToolTipText("Excluir"); jButtonExcluir.setEnabled(false); jButtonExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonExcluirActionPerformed(evt); } }); jButtonSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/controlecondominio/imagens/home_next.png"))); // NOI18N jButtonSair.setToolTipText("Sair"); jButtonSair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSairActionPerformed(evt); } }); jButtonPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/controlecondominio/imagens/search.png"))); // NOI18N jButtonPesquisar.setToolTipText("Pesquisar"); jButtonPesquisar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonPesquisarActionPerformed(evt); } }); jButtonEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/controlecondominio/imagens/application_edit.png"))); // NOI18N jButtonEditar.setToolTipText("Editar"); jButtonEditar.setEnabled(false); jButtonEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonEditarActionPerformed(evt); } }); jTextFieldPesquisa.setToolTipText("Pesquisar Código"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonSair, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonNovo, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonSalvar, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonPesquisar, javax.swing.GroupLayout.Alignment.TRAILING)) .addComponent(jButtonEditar)))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButtonExcluir) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jTextFieldPesquisa)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(14, Short.MAX_VALUE) .addComponent(jTextFieldPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonPesquisar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonNovo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonSalvar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonEditar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonExcluir) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonSair) .addContainerGap()) ); jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jButtonPrimeiro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/controlecondominio/imagens/skip_backward.png"))); // NOI18N jButtonPrimeiro.setToolTipText("Primeiro"); jButtonPrimeiro.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonPrimeiroActionPerformed(evt); } }); jButtonAnterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/controlecondominio/imagens/rewind.png"))); // NOI18N jButtonAnterior.setToolTipText("Anterior"); jButtonAnterior.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAnteriorActionPerformed(evt); } }); jButtonProximo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/controlecondominio/imagens/fast_forward.png"))); // NOI18N jButtonProximo.setToolTipText("Próximo"); jButtonProximo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonProximoActionPerformed(evt); } }); jButtonUltimo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/controlecondominio/imagens/skip_forward.png"))); // NOI18N jButtonUltimo.setToolTipText("Último"); jButtonUltimo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonUltimoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jButtonPrimeiro) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonAnterior) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonProximo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonUltimo) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonPrimeiro) .addComponent(jButtonAnterior) .addComponent(jButtonProximo) .addComponent(jButtonUltimo)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel18.setText("CPF:"); jLabel21.setText("Condomínio:"); jComboBoxCondominio.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jLabel9.setText("Celular:"); jFormattedTextFieldFone1.setEnabled(false); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(243, 243, 243) .addComponent(jLabel16)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(layout.createSequentialGroup() .addGap(3, 3, 3) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(jLabel2))))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel7))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jTextFieldCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel21) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBoxCondominio, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jTextFieldNome, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel18) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jFormattedTextFieldCpf)) .addGroup(layout.createSequentialGroup() .addComponent(jTextFieldApto, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldBloco, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel15) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jFormattedTextFieldCota, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jFormattedTextFieldFracaoIdeal)) .addGroup(layout.createSequentialGroup() .addComponent(jFormattedTextFieldFone, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jFormattedTextFieldFone1, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 523, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(136, 136, 136))) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextFieldCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel21) .addComponent(jComboBoxCondominio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextFieldNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18) .addComponent(jFormattedTextFieldCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextFieldBloco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4) .addComponent(jTextFieldApto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14) .addComponent(jLabel15) .addComponent(jFormattedTextFieldFracaoIdeal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jFormattedTextFieldCota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jFormattedTextFieldFone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7) .addComponent(jFormattedTextFieldFone1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addGap(29, 29, 29) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(15, 15, 15)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void desbloquearCampos() { jTextFieldNome.setEnabled(true); jTextFieldApto.setEnabled(true); jTextFieldBloco.setEnabled(true); jFormattedTextFieldFone.setEnabled(true); jFormattedTextFieldFracaoIdeal.setEnabled(true); jFormattedTextFieldCota.setEnabled(true); jFormattedTextFieldCpf.setEnabled(true); jButtonSalvar.setEnabled(true); jButtonEditar.setEnabled(true); jButtonExcluir.setEnabled(true); } private void bloquearCampos() { jTextFieldNome.setEnabled(false); jTextFieldApto.setEnabled(false); jTextFieldBloco.setEnabled(false); jFormattedTextFieldFone.setEnabled(false); jFormattedTextFieldFracaoIdeal.setEnabled(false); jFormattedTextFieldCota.setEnabled(false); jFormattedTextFieldCpf.setEnabled(false); jButtonSalvar.setEnabled(false); jButtonEditar.setEnabled(false); jButtonExcluir.setEnabled(false); } private void jButtonNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNovoActionPerformed desbloquearCampos(); }//GEN-LAST:event_jButtonNovoActionPerformed private void jButtonSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSairActionPerformed dispose(); }//GEN-LAST:event_jButtonSairActionPerformed private void jButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalvarActionPerformed }//GEN-LAST:event_jButtonSalvarActionPerformed private void jButtonPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPesquisarActionPerformed String vazio = ""; if (jTextFieldPesquisa.getText().equals(vazio)) { JOptionPane.showMessageDialog(null, "É necessário informar um código para ser pesquisado!"); } else { } }//GEN-LAST:event_jButtonPesquisarActionPerformed private void jButtonEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditarActionPerformed }//GEN-LAST:event_jButtonEditarActionPerformed private void jButtonExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExcluirActionPerformed Condominio condominio = new Condominio(); condominio.setCodCondominio(Integer.parseInt(jTextFieldCodigo.getText())); CondominioDAO j = DAOFactory.getDAOFactory().getCondominioDAO(); j.excluir(condominio); JOptionPane.showMessageDialog(null, "Condomínio Excluído com Sucesso!"); limparCampos(); bloquearCampos(); }//GEN-LAST:event_jButtonExcluirActionPerformed private void jButtonAnteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAnteriorActionPerformed CondominioDAO j = DAOFactory.getDAOFactory().getCondominioDAO(); int a = Integer.parseInt(jTextFieldCodigo.getText()); try { Condominio condominio = j.anterior(a); jTextFieldCodigo.setText(condominio.getCodCondominio().toString()); jTextFieldNome.setText(condominio.getNomeCondominio()); jTextFieldApto.setText(condominio.getBairroCondominio()); jTextFieldBloco.setText(condominio.getCidadeCondominio()); jFormattedTextFieldFone.setText(condominio.getFoneCondominio()); jFormattedTextFieldCpf.setText(condominio.getCnpjCondominio()); jFormattedTextFieldFracaoIdeal.setText(condominio.getMultaCondominio().toString()); jFormattedTextFieldCota.setText(condominio.getRateioCondominio().toString()); jButtonNovo.setEnabled(false); desbloquearCampos(); jButtonSalvar.setEnabled(false); //JOptionPane.showMessageDialog(null, "Registro Encontrado!"); } catch (NullPointerException e) { limparCampos(); JOptionPane.showMessageDialog(null, "Registro não existe!"); } }//GEN-LAST:event_jButtonAnteriorActionPerformed private void jButtonPrimeiroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPrimeiroActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButtonPrimeiroActionPerformed private void jButtonUltimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUltimoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButtonUltimoActionPerformed private void jButtonProximoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonProximoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButtonProximoActionPerformed private void msg(JTextField jt, String m) { if (jt.getText().isEmpty()) { JOptionPane.showMessageDialog(null, m); jt.requestFocus(); } } private String validarDoubleValor(JFormattedTextField j) { if (new Formatados().verificarSeEntradaENumeroDouble(new Formatados().tirarAVirgulaDoValor(j.getText()))) { Double numero = new Formatados().formatarValorStringParaDouble(j.getText()); return String.valueOf(numero); } return null; } private void limparCampos() { jTextFieldCodigo.setText(""); jTextFieldNome.setText(""); jTextFieldApto.setText(""); jTextFieldBloco.setText(""); jFormattedTextFieldFone.setText(""); jFormattedTextFieldFracaoIdeal.setText(""); jFormattedTextFieldCota.setText(""); jFormattedTextFieldCpf.setText(""); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonAnterior; private javax.swing.JButton jButtonEditar; private javax.swing.JButton jButtonExcluir; private javax.swing.JButton jButtonNovo; private javax.swing.JButton jButtonPesquisar; private javax.swing.JButton jButtonPrimeiro; private javax.swing.JButton jButtonProximo; private javax.swing.JButton jButtonSair; private javax.swing.JButton jButtonSalvar; private javax.swing.JButton jButtonUltimo; private javax.swing.JComboBox<String> jComboBoxCondominio; private javax.swing.JFormattedTextField jFormattedTextFieldCota; private javax.swing.JFormattedTextField jFormattedTextFieldCpf; private javax.swing.JFormattedTextField jFormattedTextFieldFone; private javax.swing.JFormattedTextField jFormattedTextFieldFone1; private javax.swing.JFormattedTextField jFormattedTextFieldFracaoIdeal; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextFieldApto; private javax.swing.JTextField jTextFieldBloco; private javax.swing.JTextField jTextFieldCodigo; private javax.swing.JTextField jTextFieldNome; private javax.swing.JTextField jTextFieldPesquisa; // End of variables declaration//GEN-END:variables }
56.387435
191
0.653791
b9478d2c99532e1516747d270beab6fdba78972d
3,118
package som.interpreter.nodes.specialized; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.DirectCallNode; import som.interpreter.nodes.ExpressionNode; import som.interpreter.nodes.PreevaluatedExpression; import som.interpreter.nodes.nary.QuaternaryExpressionNode; import som.vmobjects.SBlock; import som.vmobjects.SInvokable; import tools.dym.Tags.LoopNode; public abstract class IntToByDoMessageNode extends QuaternaryExpressionNode implements PreevaluatedExpression { private final SInvokable blockMethod; @Child private DirectCallNode valueSend; public IntToByDoMessageNode(final ExpressionNode orignialNode, final SBlock block) { super(orignialNode.getSourceSection()); blockMethod = block.getMethod(); valueSend = Truffle.getRuntime().createDirectCallNode( blockMethod.getCallTarget()); } public IntToByDoMessageNode(final IntToByDoMessageNode node) { super(node.getSourceSection()); this.blockMethod = node.blockMethod; this.valueSend = node.valueSend; } @Override protected boolean isTaggedWith(final Class<?> tag) { if (tag == LoopNode.class) { return true; } else { return super.isTaggedWith(tag); } } @Override public final Object doPreEvaluated(final VirtualFrame frame, final Object[] arguments) { return executeEvaluated(frame, arguments[0], arguments[1], arguments[2], arguments[3]); } protected final boolean isSameBlockLong(final SBlock block) { return block.getMethod() == blockMethod; } protected final boolean isSameBlockDouble(final SBlock block) { return block.getMethod() == blockMethod; } @Specialization(guards = "isSameBlockLong(block)") public final long doIntToByDo(final VirtualFrame frame, final long receiver, final long limit, final long step, final SBlock block) { try { if (receiver <= limit) { valueSend.call(frame, new Object[] {block, receiver}); } for (long i = receiver + 1; i <= limit; i += step) { valueSend.call(frame, new Object[] {block, i}); } } finally { if (CompilerDirectives.inInterpreter()) { SomLoop.reportLoopCount(limit - receiver, this); } } return receiver; } @Specialization(guards = "isSameBlockDouble(block)") public final long doIntToByDo(final VirtualFrame frame, final long receiver, final double limit, final long step, final SBlock block) { try { if (receiver <= limit) { valueSend.call(frame, new Object[] {block, receiver}); } for (long i = receiver + 1; i <= limit; i += step) { valueSend.call(frame, new Object[] {block, i}); } } finally { if (CompilerDirectives.inInterpreter()) { SomLoop.reportLoopCount((long) limit - receiver, this); } } return receiver; } @Override public boolean isResultUsed(final ExpressionNode child) { return false; } }
31.18
137
0.700128
441f2a139e5fa9641b6495779bf16f1a088a0de2
25,396
/* Copyright 2004-2019 Jim Voris * * 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.qumasoft.server; import com.qumasoft.qvcslib.QVCSConstants; import com.qumasoft.server.dataaccess.BranchDAO; import com.qumasoft.server.dataaccess.DirectoryDAO; import com.qumasoft.server.dataaccess.FileDAO; import com.qumasoft.server.dataaccess.FileHistoryDAO; import com.qumasoft.server.dataaccess.ProjectDAO; import com.qumasoft.server.dataaccess.impl.BranchDAOImpl; import com.qumasoft.server.dataaccess.impl.DirectoryDAOImpl; import com.qumasoft.server.dataaccess.impl.FileDAOImpl; import com.qumasoft.server.dataaccess.impl.FileHistoryDAOImpl; import com.qumasoft.server.dataaccess.impl.ProjectDAOImpl; import com.qumasoft.server.datamodel.Branch; import com.qumasoft.server.datamodel.Directory; import com.qumasoft.server.datamodel.FileHistory; import com.qumasoft.server.datamodel.Project; import java.util.List; /** * A helper class for some common methods that help figure out what kind of merge we'll have for a given file. * * @author Jim Voris */ public class MergeTypeHelper { private final String projectName; private final String branchName; /** * Merge type helper constructor. * * @param project the name of the project. * @param branch the branch name. */ public MergeTypeHelper(String project, String branch) { this.projectName = project; this.branchName = branch; } private String getProjectName() { return this.projectName; } private String getBranchName() { return this.branchName; } /** * We figure out whether the file has been renamed on the parent branch. * * @param fileId the file id. * @param parentBranchname the name of the parent branch. * @return true if the file moved on the branch. */ public boolean wasFileRenamedOnParentBranch(Integer fileId, String parentBranchname) { String schemaName = QVCSEnterpriseServer.getDatabaseManager().getSchemaName(); boolean retFlag = false; ProjectDAO projectDAO = new ProjectDAOImpl(schemaName); BranchDAO branchDAO = new BranchDAOImpl(schemaName); FileDAO fileDAO = new FileDAOImpl(schemaName); FileHistoryDAO fileHistoryDAO = new FileHistoryDAOImpl(schemaName); Project project = projectDAO.findByProjectName(getProjectName()); Branch parentBranch = branchDAO.findByProjectIdAndBranchName(project.getProjectId(), parentBranchname); Branch branch = branchDAO.findByProjectIdAndBranchName(project.getProjectId(), getBranchName()); if ((parentBranch != null) && (branch != null)) { ProjectBranch projectBranch = BranchManager.getInstance().getBranch(getProjectName(), branch.getBranchName()); com.qumasoft.server.datamodel.File foundFile = findFile(branchDAO, fileDAO, branch, project.getProjectId(), fileId); if ((foundFile != null) && foundFile.getBranchId().equals(branch.getBranchId())) { com.qumasoft.server.datamodel.File parentBranchFile = fileDAO.findById(parentBranch.getBranchId(), fileId); if (parentBranchFile != null) { if (!parentBranchFile.getFileName().equals(foundFile.getFileName())) { // The file has in different name on the branch than on the parent branch. We now have to decide whether // that's a result of the file having renamed on the parent. if (parentBranchFile.getUpdateDate().after(projectBranch.getRemoteBranchProperties().getBranchDate())) { // The parent file record has been updated since the branch was created. We need to find the last history // record for the parent branch that was created before the branch was created, and from that get the filename. // If the filename of that history record is different than the filename of the current record, then the file // has been renamed on the parent branch. List<FileHistory> fileHistoryList = fileHistoryDAO.findHistoryForFileId(parentBranch.getBranchId(), fileId); FileHistory foundFileHistory = null; for (FileHistory fileHistory : fileHistoryList) { if (fileHistory.getUpdateDate().before(projectBranch.getRemoteBranchProperties().getBranchDate())) { foundFileHistory = fileHistory; break; } } if (foundFileHistory != null) { if (!foundFileHistory.getFileName().equals(parentBranchFile.getFileName())) { // The parent branch file has a different name than when the branch was created. retFlag = true; } } } } } } else if ((foundFile != null) && foundFile.getBranchId().equals(parentBranch.getBranchId())) { // The file did not have a record on the branch... we just need to see if it was renamed on the parent branch. if (foundFile.getUpdateDate().after(projectBranch.getRemoteBranchProperties().getBranchDate())) { // The parent file record has been updated since the branch was created. We need to find the last history // record for the parent branch that was created before the branch was created, and from that get the filename. // If the filename of that history record is different than the filename of the current record, then the file // has been renamed on the parent branch. List<FileHistory> fileHistoryList = fileHistoryDAO.findHistoryForFileId(parentBranch.getBranchId(), fileId); FileHistory foundFileHistory = null; for (FileHistory fileHistory : fileHistoryList) { if (fileHistory.getUpdateDate().before(projectBranch.getRemoteBranchProperties().getBranchDate())) { foundFileHistory = fileHistory; break; } } if (foundFileHistory != null) { if (!foundFileHistory.getFileName().equals(foundFile.getFileName())) { // The parent branch file has a different name than when the branch was created. retFlag = true; } } } } } return retFlag; } /** * We figure out whether the file has been renamed on the branch. If the file is new to the branch (i.e. it doesn't exist on the * parent), then it <i>cannot</i> have 'renamed' on the branch compared to the parent branch, since it doesn't exist on the * parent. If the file does exist on the parent, then it has been renamed on the branch if its current filename is different * than the filename it had at the time the branch was created. Note that if the file has the same name on the branch as it has * on the parent branch, then we declare that it has not been renamed, meaning that if it has renamed, there was a compensating * (identical) rename on the parent branch, so that we don't need to take the rename into account when we perform the merge -- * i.e. for merge purposes we can ignore the rename. * * @param fileId the file id. * @param parentBranchname the name of the parent branch. * @return true if the file moved on the branch. */ public boolean wasFileRenamedOnBranch(Integer fileId, String parentBranchname) { String schemaName = QVCSEnterpriseServer.getDatabaseManager().getSchemaName(); boolean retFlag = false; ProjectDAO projectDAO = new ProjectDAOImpl(schemaName); BranchDAO branchDAO = new BranchDAOImpl(schemaName); FileDAO fileDAO = new FileDAOImpl(schemaName); FileHistoryDAO fileHistoryDAO = new FileHistoryDAOImpl(schemaName); Project project = projectDAO.findByProjectName(getProjectName()); Branch parentBranch = branchDAO.findByProjectIdAndBranchName(project.getProjectId(), parentBranchname); Branch branch = branchDAO.findByProjectIdAndBranchName(project.getProjectId(), getBranchName()); if ((parentBranch != null) && (branch != null)) { ProjectBranch projectBranch = BranchManager.getInstance().getBranch(getProjectName(), branch.getBranchName()); com.qumasoft.server.datamodel.File foundFile = findFile(branchDAO, fileDAO, branch, project.getProjectId(), fileId); if ((foundFile != null) && foundFile.getBranchId().equals(branch.getBranchId())) { com.qumasoft.server.datamodel.File parentBranchFile = fileDAO.findById(parentBranch.getBranchId(), fileId); if (parentBranchFile != null) { if (!parentBranchFile.getFileName().equals(foundFile.getFileName())) { // The file has a different name on the branch than on the parent branch. We now have to decide whether // that's a result of the file having renamed on the parent. if (parentBranchFile.getUpdateDate().after(projectBranch.getRemoteBranchProperties().getBranchDate())) { // The parent file record has been updated since the branch was created. We need to find the last history // record for the parent branch that was created before the branch was created, and from that get the filename. // If the filename of that history record is different than the filename of the current record, then the file // has been renamed on the parent branch. List<FileHistory> fileHistoryList = fileHistoryDAO.findHistoryForFileId(parentBranch.getBranchId(), fileId); FileHistory foundParentBranchFileHistory = null; for (FileHistory fileHistory : fileHistoryList) { if (fileHistory.getUpdateDate().before(projectBranch.getRemoteBranchProperties().getBranchDate())) { foundParentBranchFileHistory = fileHistory; break; } } if (foundParentBranchFileHistory != null) { if (!foundParentBranchFileHistory.getFileName().equals(foundFile.getFileName())) { // The branch file has a different name than when the branch was created. retFlag = true; } } } else { // The file has not been renamed on the parent branch, ergo, it must have been renamed on the branch. retFlag = true; } } } } } return retFlag; } /** * We figure out whether the file has moved on the branch. If the file is new to the branch (i.e. it doesn't exist on the * parent), then it <i>cannot</i> have 'moved' on the branch compared to the parent branch, since it doesn't exist on the * parent. If the file does exist on the parent, then it has moved on the branch if its current branch directory is different * than the directory where it was located at the time the branch was created. Note that if the file is in the same directory on * the branch as it is on the parent branch, then we declare that it has not moved, meaning that if it has moved, there was a * compensating (identical) move on the parent branch, so that we don't need to take the move into account when we perform the * merge -- i.e. for merge purposes we can ignore the move. * * @param fileId the file id. * @param parentBranchname the name of the parent branch. * @return true if the file moved on the branch. */ public boolean didFileMoveOnBranch(Integer fileId, String parentBranchname) { String schemaName = QVCSEnterpriseServer.getDatabaseManager().getSchemaName(); boolean retFlag = false; ProjectDAO projectDAO = new ProjectDAOImpl(schemaName); BranchDAO branchDAO = new BranchDAOImpl(schemaName); FileDAO fileDAO = new FileDAOImpl(schemaName); FileHistoryDAO fileHistoryDAO = new FileHistoryDAOImpl(schemaName); Project project = projectDAO.findByProjectName(getProjectName()); Branch parentBranch = branchDAO.findByProjectIdAndBranchName(project.getProjectId(), parentBranchname); Branch branch = branchDAO.findByProjectIdAndBranchName(project.getProjectId(), getBranchName()); if ((parentBranch != null) && (branch != null)) { ProjectBranch projectBranch = BranchManager.getInstance().getBranch(getProjectName(), branch.getBranchName()); com.qumasoft.server.datamodel.File foundFile = findFile(branchDAO, fileDAO, branch, project.getProjectId(), fileId); if ((foundFile != null) && foundFile.getBranchId().equals(branch.getBranchId())) { com.qumasoft.server.datamodel.File parentBranchFile = fileDAO.findById(parentBranch.getBranchId(), fileId); if (parentBranchFile != null) { if (!parentBranchFile.getDirectoryId().equals(foundFile.getDirectoryId())) { // The file is in a different directory on the branch than on the parent branch. We now have to decide whether // that's a result of the file having moved on the branch. if (parentBranchFile.getUpdateDate().after(projectBranch.getRemoteBranchProperties().getBranchDate())) { // The parent file record has been updated since the branch was created. We need to find the last history // record for the parent branch that was created before the branch was created, and from that get the directory id. // If the directory id of that history record is different than the directory id of the current branch record, then the file // has been moved on the branch. List<FileHistory> fileHistoryList = fileHistoryDAO.findHistoryForFileId(parentBranch.getBranchId(), fileId); FileHistory foundParentBranchFileHistory = null; for (FileHistory fileHistory : fileHistoryList) { if (fileHistory.getUpdateDate().before(projectBranch.getRemoteBranchProperties().getBranchDate())) { foundParentBranchFileHistory = fileHistory; break; } } if (foundParentBranchFileHistory != null) { if (!foundParentBranchFileHistory.getDirectoryId().equals(foundFile.getDirectoryId())) { // The branch file is in a different directory than it was when the branch was created. retFlag = true; } } } else { // The file has not moved on the parent branch, ergo, it must have moved on the branch. retFlag = true; } } } } } return retFlag; } /** * Did the file move on the parent branch. If the file on the parent is in the same directory as on the child, then we conclude * there was no move for merge purposes at least. * * @param fileId the file id. * @param parentBranchname the name of the parent branch. * @return true if the file moved on the parent branch; false if it did not. */ public boolean didFileMoveOnParentBranch(int fileId, String parentBranchname) { String schemaName = QVCSEnterpriseServer.getDatabaseManager().getSchemaName(); boolean retFlag = false; ProjectDAO projectDAO = new ProjectDAOImpl(schemaName); BranchDAO branchDAO = new BranchDAOImpl(schemaName); FileDAO fileDAO = new FileDAOImpl(schemaName); FileHistoryDAO fileHistoryDAO = new FileHistoryDAOImpl(schemaName); Project project = projectDAO.findByProjectName(getProjectName()); Branch parentBranch = branchDAO.findByProjectIdAndBranchName(project.getProjectId(), parentBranchname); Branch branch = branchDAO.findByProjectIdAndBranchName(project.getProjectId(), getBranchName()); if ((parentBranch != null) && (branch != null)) { ProjectBranch projectBranch = BranchManager.getInstance().getBranch(getProjectName(), branch.getBranchName()); com.qumasoft.server.datamodel.File foundFile = findFile(branchDAO, fileDAO, branch, project.getProjectId(), fileId); if ((foundFile != null) && foundFile.getBranchId().equals(branch.getBranchId())) { com.qumasoft.server.datamodel.File parentBranchFile = fileDAO.findById(parentBranch.getBranchId(), fileId); if (parentBranchFile != null) { if (!parentBranchFile.getDirectoryId().equals(foundFile.getDirectoryId())) { // The file is in a different directory on the branch than on the parent branch. We now have to decide whether // that's a result of the file having moved on the parent. if (parentBranchFile.getUpdateDate().after(projectBranch.getRemoteBranchProperties().getBranchDate())) { // The parent file record has been updated since the branch was created. We need to find the last history // record for the parent branch that was created before the branch was created, and from that get the directory id. // If the directory id of that history record is different than the directory id of the current record, then the file // has been moved on the parent branch. List<FileHistory> fileHistoryList = fileHistoryDAO.findHistoryForFileId(parentBranch.getBranchId(), fileId); FileHistory foundFileHistory = null; for (FileHistory fileHistory : fileHistoryList) { if (fileHistory.getUpdateDate().before(projectBranch.getRemoteBranchProperties().getBranchDate())) { foundFileHistory = fileHistory; break; } } if (foundFileHistory != null) { if (!foundFileHistory.getDirectoryId().equals(parentBranchFile.getDirectoryId())) { // The parent branch file is in a different directory than it was when the branch was created. retFlag = true; } } } } } } else if ((foundFile != null) && foundFile.getBranchId().equals(parentBranch.getBranchId())) { // The file did not have a record on the branch... we just need to see if it moved on the parent branch. if (foundFile.getUpdateDate().after(projectBranch.getRemoteBranchProperties().getBranchDate())) { // The parent file record has been updated since the branch was created. We need to find the last history // record for the parent branch that was created before the branch was created, and from that get the directory id. // If the directory id of that history record is different than the directory id of the current record, then the file // has been moved on the parent branch. List<FileHistory> fileHistoryList = fileHistoryDAO.findHistoryForFileId(parentBranch.getBranchId(), fileId); FileHistory foundFileHistory = null; for (FileHistory fileHistory : fileHistoryList) { if (fileHistory.getUpdateDate().before(projectBranch.getRemoteBranchProperties().getBranchDate())) { foundFileHistory = fileHistory; break; } } if (foundFileHistory != null) { if (!foundFileHistory.getDirectoryId().equals(foundFile.getDirectoryId())) { // The parent branch file is in a different directory than it was when the branch was created. retFlag = true; } } } } } return retFlag; } /** * Was the file created on the branch. If the file doesn't have a record for a parent branch, then it was created on the branch. * * @param fileId the file id. * @param parentBranchname the name of the parent branch. * @return true if the file was created on the branch (i.e. it doesn't exist on any parent branch). */ public boolean wasFileCreatedOnBranch(Integer fileId, String parentBranchname) { String schemaName = QVCSEnterpriseServer.getDatabaseManager().getSchemaName(); boolean retFlag = false; ProjectDAO projectDAO = new ProjectDAOImpl(schemaName); BranchDAO branchDAO = new BranchDAOImpl(schemaName); FileDAO fileDAO = new FileDAOImpl(schemaName); DirectoryDAO directoryDAO = new DirectoryDAOImpl(schemaName); Project project = projectDAO.findByProjectName(getProjectName()); Branch parentBranch = branchDAO.findByProjectIdAndBranchName(project.getProjectId(), parentBranchname); Branch branch = branchDAO.findByProjectIdAndBranchName(project.getProjectId(), getBranchName()); if ((parentBranch != null) && (branch != null)) { com.qumasoft.server.datamodel.File foundFile = findFile(branchDAO, fileDAO, branch, project.getProjectId(), fileId); if ((foundFile != null) && foundFile.getBranchId().equals(branch.getBranchId())) { com.qumasoft.server.datamodel.File foundFileOnParentBranch = findFile(branchDAO, fileDAO, parentBranch, project.getProjectId(), fileId); if (foundFileOnParentBranch == null) { retFlag = true; } else { Directory directory = directoryDAO.findById(parentBranch.getBranchId(), foundFileOnParentBranch.getDirectoryId()); if (directory.getAppendedPath().equals(QVCSConstants.QVCS_BRANCH_ARCHIVES_DIRECTORY)) { retFlag = true; } } } } return retFlag; } /** * Walk up the branch tree until we find the file. <p><b>(This is adapted from the very similar code in * DirectoryContentsManager).</b></p> * * @param branchDAO the branch DAO. * @param fileDAO the file DAO. * @param branch the branch where we'll look. * @param projectId the project id. * @param fileId the file id. * @return the file (from the database). */ private com.qumasoft.server.datamodel.File findFile(BranchDAO branchDAO, FileDAO fileDAO, Branch branch, int projectId, int fileId) { com.qumasoft.server.datamodel.File file = fileDAO.findById(branch.getBranchId(), fileId); if (file == null) { ProjectBranch projectBranch = BranchManager.getInstance().getBranch(getProjectName(), branch.getBranchName()); if (projectBranch.getRemoteBranchProperties().getParentProjectName() != null) { Branch parentBranch = branchDAO.findByProjectIdAndBranchName(projectId, projectBranch.getRemoteBranchProperties().getBranchParent()); file = findFile(branchDAO, fileDAO, parentBranch, projectId, fileId); } } return file; } }
64.293671
152
0.614979
960466717c5f8f3adb3d9f6c605a68e716de67dc
3,198
package com.cy.core.systemsetting.service; import java.rmi.MarshalException; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.cy.base.entity.Message; import com.cy.common.utils.StringUtils; import com.cy.system.Global; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cy.core.systemsetting.dao.SystemSettingMapper; import com.cy.core.systemsetting.entity.SystemSetting; import com.cy.system.GetDictionaryInfo; @Service("systemSettingService") public class SystemSettingServiceImpl implements SystemSettingService { @Autowired private SystemSettingMapper systemSettingMapper; @Override public List<SystemSetting> selectAll() { return systemSettingMapper.selectAll(); } @Override public SystemSetting selectById(long systemId) { SystemSetting systemSetting = systemSettingMapper.selectById(systemId); if(systemSetting !=null && StringUtils.isNotBlank(systemSetting.getSchoolLogo()) ){ systemSetting.setSchoolLogo(Global.URL_DOMAIN + systemSetting.getSchoolLogo()); } return systemSetting; } @Override public void update(SystemSetting systemSetting) { if(systemSetting.getSchoolLogo() != null ){ systemSetting.setSchoolLogo(systemSetting.getSchoolLogo().replace(Global.URL_DOMAIN, "")); } if(systemSetting.getFoundationSignet() != null){ systemSetting.setFoundationSignet(systemSetting.getFoundationSignet().replace(Global.URL_DOMAIN, "")); } if(systemSetting.getFoundationLogo() != null){ systemSetting.setFoundationLogo(systemSetting.getFoundationLogo().replace(Global.URL_DOMAIN, "")); } systemSettingMapper.update(systemSetting); GetDictionaryInfo.getInstance().initSystem(); } @Override public void insert(SystemSetting systemSetting) { if(systemSetting.getSchoolLogo() != null ){ systemSetting.setSchoolLogo(systemSetting.getSchoolLogo().replace(Global.URL_DOMAIN, "")); } if(systemSetting.getFoundationSignet() != null){ systemSetting.setFoundationSignet(systemSetting.getFoundationSignet().replace(Global.URL_DOMAIN, "")); } systemSettingMapper.insert(systemSetting); GetDictionaryInfo.getInstance().initSystem(); } /** * * 查询声明文本的接口 * */ public void findStatement(Message message, String content){ if (StringUtils.isBlank(content)) { message.setMsg("未传入参数"); message.setSuccess(false); return; } Map<String, String> map = JSON.parseObject(content, Map.class); String type = map.get("type"); List<SystemSetting> list = systemSettingMapper.selectAll(); if(list == null || list.size() < 0){ message.setMsg("未查询到系统设置参数"); message.setSuccess(false); return; } if(StringUtils.isBlank(type)){ message.setMsg("请提供查询的声明类型"); message.setSuccess(false); return; } String text; if("1".equals(type)){ text = list.get(0).getSignUpText(); }else if("2".equals(type)){ text = list.get(0).getDonateText(); }else{ message.init(false,"未知的声明类型", null); return; } if(StringUtils.isBlank(text)){ message.init(false,"声明内容不存在哦",null); return; } message.setObj(text); message.setSuccess(true); message.setMsg("查询成功"); } }
27.568966
105
0.74828
e371f1781bbef3827e9f979bde13820061f24b6d
96
package frc.robot.subsystems.arm; public interface IArmOI { public double getArmAngle(); }
16
33
0.75
bf42640cabe15959a4c0daf02e7c206f37032e2f
1,552
package com.camunda.demo.outerspace.wjax.service; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import com.camunda.demo.outerspace.wjax.entity.Article; import com.camunda.demo.outerspace.wjax.entity.StockItem; @Stateless public class StockService { @PersistenceContext private EntityManager entityManager; public void persist(Article a) { entityManager.persist(a); } public void setAmountOnStock(String articleId, int amount) { StockItem stockItem = entityManager.find(StockItem.class, articleId); if (stockItem==null) { stockItem = new StockItem(); stockItem.setId(articleId); entityManager.persist(stockItem); } stockItem.setAmountOnStock(amount); } public int getAmountOnStock(String articleId) { StockItem stockItem = entityManager.find(StockItem.class, articleId); if (stockItem==null) { return 0; } else { return stockItem.getAmountOnStock(); } } public void reserveGoods(String articleId, int amount) { StockItem stockItem = entityManager.find(StockItem.class, articleId); if (stockItem==null) { throw new IllegalStateException("Article " + articleId + " not on stock."); } if (stockItem.getAmountOnStock() < amount) { throw new IllegalStateException("Amount on stock of article " + articleId + " not sufficient ("+stockItem.getAmountOnStock()+"<"+amount+")."); } stockItem.setAmountOnStock(stockItem.getAmountOnStock()-amount); } }
30.431373
148
0.717784