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
3536ab76c9f19a0ae0ed25dd2d40609a070965eb
2,521
/* * Copyright 2012 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.vaadin.training.fundamentals.happening.ui.view; import java.io.Serializable; import org.vaadin.training.fundamentals.happening.domain.entity.Happening; import org.vaadin.training.fundamentals.happening.ui.NoAccessException; import org.vaadin.training.fundamentals.happening.ui.NotAuthenticatedException; import com.vaadin.data.util.BeanItem; import com.vaadin.ui.Component; public interface EditHappeningView<T extends Component> extends VaadinView<T> { public void setDatasource(BeanItem<Happening> item); public void showSaveSuccess(); public void addListener(ItemSavedListener listener); public void removeListener(ItemSavedListener listener); public void addListener(SaveCanceledListener listener); public void removeListener(SaveCanceledListener listener); public interface ItemSavedListener extends Serializable { public void itemSaved(ItemSavedEvent event) throws NotAuthenticatedException, NoAccessException; } public interface SaveCanceledListener extends Serializable { public void saveCanceled(SaveCanceledEvent event); } public static class ItemSavedEvent extends Component.Event { private static final long serialVersionUID = 1L; private BeanItem<?> savedItem; public ItemSavedEvent(Component source, BeanItem<?> savedItem) { super(source); this.savedItem = savedItem; } public BeanItem<?> getSavedItem() { return savedItem; } public Object getBean() { return savedItem.getBean(); } } public static class SaveCanceledEvent extends Component.Event { private static final long serialVersionUID = 1L; public SaveCanceledEvent(Component source) { super(source); } } }
31.5125
81
0.699326
bfaa2ebaa1b11c0f63a6ef47fcc180e691746081
2,458
/* * MIT License * * Copyright (c) 2019-2020 PiggyPiglet * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.piggypiglet.framework.user; import me.piggypiglet.framework.utils.StringUtils; public abstract class User { private final String name; private final String id; /** * Provide basic info to the superclass * @param name Name of the user * @param id ID of the user */ protected User(String name, String id) { this.name = name; this.id = id; } /** * Get the user's name * @return String */ public String getName() { return name; } /** * Get the user's unique identifier * @return String */ public String getId() { return id; } /** * Does the user have a specific permission * @param permission String * @return Boolean */ public abstract boolean hasPermission(String permission); /** * Implementation of sending the user a message * @param message Message to send */ protected abstract void sendMessage(String message); /** * Send the user a message * @param message Message to send * @param concatenations Concatenations to main message &amp; variables */ public void sendMessage(Object message, Object... concatenations) { sendMessage(StringUtils.format(message, concatenations)); } }
30.345679
81
0.683483
7fd77fc548461b1553b0bce0f01f53aad7136ebc
3,360
/* * MIT License * * Copyright (C) 2013 - 2017 Philipp Nowak (https://github.com/xxyy) and contributors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package li.l1t.lanatus.sql.account; import li.l1t.common.exception.DatabaseException; import li.l1t.common.exception.InternalException; import li.l1t.common.sql.sane.SaneSql; import li.l1t.common.sql.sane.result.QueryResult; import li.l1t.lanatus.api.account.LanatusAccount; import java.sql.SQLException; import java.util.Optional; import java.util.UUID; /** * Fetches accounts from an underlying JDBC database. * * @author <a href="http://xxyy.github.io/">xxyy</a> * @since 2016-09-29 */ class JdbcAccountFetcher<T extends LanatusAccount> extends li.l1t.common.sql.sane.util.AbstractJdbcFetcher<T> { private final JdbcAccountCreator<? extends T> creator; public JdbcAccountFetcher(JdbcAccountCreator<? extends T> creator, SaneSql sql) { super(creator, sql); this.creator = creator; } public T fetchOrDefault(UUID playerId) throws InternalException { return fetchOptionally(playerId) .orElseGet(() -> creator.createDefault(playerId)); } public Optional<T> fetchOptionally(UUID playerId) throws InternalException { try (QueryResult qr = fetchSingleAccount(playerId)) { if (proceedToFirstRow(qr)) { return Optional.of(creator.createFromCurrentRow(qr.rs())); } else { return Optional.empty(); } } catch (SQLException e) { throw InternalException.wrap(e); } } private boolean proceedToFirstRow(QueryResult qr) throws SQLException { return qr.rs().next(); } private QueryResult fetchSingleAccount(UUID playerId) throws DatabaseException { return executeSql("player_uuid = ?", playerId.toString()); } private QueryResult executeSql(String whereClause, Object... parameters) throws DatabaseException { return sql().query( buildSelect(whereClause), parameters ); } @Override protected String buildSelect(String whereClause) { return "SELECT player_uuid, melons, lastrank " + "FROM " + SqlAccountRepository.TABLE_NAME + " " + "WHERE " + whereClause; } }
37.333333
111
0.697321
1fe8f43fcf573eeb46599d68caa4ba0ee5fa5ed6
2,238
package com.likc.data.sort; /** * @author likc * @date 2022/3/23 * @description */ public class Sort { /** * 使用递归的二分查找 *title:recursionBinarySearch *@param ints 升序数组 *@param key 待查找关键字 *@return 找到的位置 */ int binarySearch(int[] ints, int key, int low, int high){ if (key < ints[low] || key > ints[high] || low > high){ return -1; } int middle = (low + high) / 2; if (ints[middle] > key){ return binarySearch(ints , key, low, middle-1); } else if (ints[middle] < key){ return binarySearch(ints, key, middle+1, high); } else { return middle; } } /*冒泡排序*/ int[] bubbingSort(int[] nums){ if (nums.length == 0 || nums == null){ return null; } int temp = 0; for (int i = 0; i < nums.length-1; i++){ for (int j = 0; j < nums.length-1-i; j++){ if (nums[j] > nums[j+1]){ temp = nums[j]; nums[j] = nums[j+1]; nums[j+1] = temp; } } } return nums; } /*递归快速排序*/ int[] fastSort(int[] nums, int left, int right){ int i, j, t, temp; if(left > right){ return null; } temp = nums[left]; //temp中存的就是基准数 i = left; j = right; while(i != j) { //顺序很重要,要先从右边开始找 while(nums[j] >= temp && i < j) j--; while(nums[i] <= temp && i < j)//再找右边的 i++; if(i < j)//交换两个数在数组中的位置 { t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } //最终将基准数归位 nums[left] = nums[i]; nums[i] = temp; fastSort(nums, left, i-1); //继续处理左边的,这里是一个递归的过程 fastSort(nums,i+1, right); //继续处理右边的 ,这里是一个递归的过程 return nums; } }
26.963855
67
0.371314
26f6197ef8d2522948559f14bda8592c220dee54
1,440
package victus.table; import pl.zankowski.iextrading4j.api.stocks.Quote; import pl.zankowski.iextrading4j.client.rest.request.stocks.QuoteRequestBuilder; import victus.IEX; import victus.StockQuote; import java.util.ArrayList; import java.util.List; public class Symbol implements Runnable{ private static List<Quote> quotes = new ArrayList<>(); private static int i; public Symbol() { } public static synchronized StockQuote getSymbol(String symbol) { StockQuote stockQuote = new StockQuote(); for (int ii = 0; ii < 2; ii++) { Quote quote = IEX.initiateIEX().executeRequest(new QuoteRequestBuilder().withSymbol(symbol).build()); quotes.add(i, quote); stockQuote.setSymbol(quotes.get(ii).getSymbol()); stockQuote.setChange(quotes.get(ii).getChange().doubleValue()); stockQuote.setName(quotes.get(ii).getSymbol()); stockQuote.setLastPrice(quotes.get(ii).getLatestPrice().doubleValue()); stockQuote.setVolume(quotes.get(ii).getIexVolume().longValue()); System.out.printf("%nResult REST call: %s : %f : %d, %f", stockQuote.getSymbol(), stockQuote.getLastPrice(), stockQuote.getVolume(), stockQuote.getChange()); return stockQuote; } return null; } @Override public void run() { } }
32.727273
121
0.629861
e455648d46e92c5a1865b2370c01aa126710ac77
1,486
package pt.up.hs.linguini.analysis.cooccurrence; import java.util.Objects; /** * Representation of a word-word co-occurrence. * * @author José Carlos Paiva <code>josepaiva94@gmail.com</code> */ public class CoOccurrence { private String firstWord; private String secondWord; private double value; public CoOccurrence() { } public CoOccurrence(String firstWord, String secondWord, double value) { this.firstWord = firstWord; this.secondWord = secondWord; this.value = value; } public String getFirstWord() { return firstWord; } public void setFirstWord(String firstWord) { this.firstWord = firstWord; } public String getSecondWord() { return secondWord; } public void setSecondWord(String secondWord) { this.secondWord = secondWord; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CoOccurrence)) return false; CoOccurrence that = (CoOccurrence) o; return Double.compare(that.value, value) == 0 && Objects.equals(firstWord, that.firstWord) && Objects.equals(secondWord, that.secondWord); } @Override public int hashCode() { return Objects.hash(firstWord, secondWord, value); } }
22.861538
76
0.629206
aece99253e3b7200abcd37a7473a55c0c53d9855
84
package observer; public interface Observer { void update(float temprature); }
14
34
0.75
bc9a4da22c991c26eff6a807706e67733146b3e9
1,141
package org.kin.scheduler.core.worker.transport; import org.kin.kinrpc.message.core.RpcEndpointRef; import org.kin.scheduler.core.worker.domain.WorkerInfo; import java.io.Serializable; /** * 通知master注册worker消息 * * @author huangjianqin * @date 2020-02-07 */ public class RegisterWorker implements Serializable { private static final long serialVersionUID = -9019345657992463377L; /** worker信息 */ private WorkerInfo workerInfo; /** worker client ref */ private RpcEndpointRef workerRef; public static RegisterWorker of(WorkerInfo workerInfo, RpcEndpointRef workerRef) { RegisterWorker message = new RegisterWorker(); message.workerInfo = workerInfo; message.workerRef = workerRef; return message; } //setter && getter public WorkerInfo getWorkerInfo() { return workerInfo; } public void setWorkerInfo(WorkerInfo workerInfo) { this.workerInfo = workerInfo; } public RpcEndpointRef getWorkerRef() { return workerRef; } public void setWorkerRef(RpcEndpointRef workerRef) { this.workerRef = workerRef; } }
25.355556
86
0.701139
66e0cf0b1a98de39f80bcb013941c2a05718e5a5
648
package quiz; /** * @author yuyunlong * @date 2021/6/14 1:19 下午 * @description 微观博弈笔试题 */ public class WeiGBY01 { /** * 旋转字符串 * @param A string字符串 * @param B string字符串 * @return bool布尔型 */ public boolean solve (String A, String B) { // write code here for (int i = 0; i < A.length(); i++) { if (B.equals(revol(A, i))) { return true; } } return false; } private String revol(String s, int x) { //字符串旋转 String l1 = s.substring(0, x); String l2 = s.substring(x, s.length()); return l2 + l1; } }
19.636364
47
0.487654
b78366906f052db36bc41c33d802397cbaa49568
11,203
/* * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eike Stepper - initial API and implementation * Simon McDuff - bug 201266 * Simon McDuff - bug 230832 */ package org.eclipse.emf.cdo.internal.common.revision; import java.lang.ref.Reference; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.eclipse.emf.cdo.common.branch.CDOBranch; import org.eclipse.emf.cdo.common.branch.CDOBranchPoint; import org.eclipse.emf.cdo.common.branch.CDOBranchVersion; import org.eclipse.emf.cdo.common.id.CDOID; import org.eclipse.emf.cdo.common.revision.CDORevision; import org.eclipse.emf.cdo.common.revision.CDORevisionKey; import org.eclipse.emf.cdo.internal.common.bundle.OM; import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevisionCache; import org.eclipse.emf.ecore.EClass; import org.eclipse.net4j.util.CheckUtil; import org.eclipse.net4j.util.om.trace.ContextTracer; /** * @author Eike Stepper */ public class CDORevisionCacheAuditing extends AbstractCDORevisionCache { private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_REVISION, CDORevisionCacheAuditing.class); protected Map<Object, RevisionList> revisionLists = new HashMap<Object, RevisionList>(); public CDORevisionCacheAuditing() { } public InternalCDORevisionCache instantiate(CDORevision revision) { return new CDORevisionCacheAuditing(); } public EClass getObjectType(CDOID id) { synchronized (revisionLists) { RevisionList revisionList = revisionLists.get(id); if (revisionList != null && !revisionList.isEmpty()) { Reference<InternalCDORevision> ref = revisionList.getFirst(); InternalCDORevision revision = ref.get(); if (revision != null) { return revision.getEClass(); } } return null; } } public InternalCDORevision getRevision(CDOID id, CDOBranchPoint branchPoint) { RevisionList revisionList = getRevisionList(id, branchPoint.getBranch()); if (revisionList != null) { return revisionList.getRevision(branchPoint.getTimeStamp()); } return null; } public InternalCDORevision getRevisionByVersion(CDOID id, CDOBranchVersion branchVersion) { RevisionList revisionList = getRevisionList(id, branchVersion.getBranch()); if (revisionList != null) { return revisionList.getRevisionByVersion(branchVersion.getVersion()); } return null; } public List<CDORevision> getCurrentRevisions() { List<CDORevision> currentRevisions = new ArrayList<CDORevision>(); synchronized (revisionLists) { for (RevisionList revisionList : revisionLists.values()) { InternalCDORevision revision = revisionList.getRevision(CDORevision.UNSPECIFIED_DATE); if (revision != null) { currentRevisions.add(revision); } } } return currentRevisions; } public Map<CDOBranch, List<CDORevision>> getAllRevisions() { Map<CDOBranch, List<CDORevision>> result = new HashMap<CDOBranch, List<CDORevision>>(); synchronized (revisionLists) { for (RevisionList list : revisionLists.values()) { list.getAllRevisions(result); } } return result; } public List<CDORevision> getRevisions(CDOBranchPoint branchPoint) { List<CDORevision> result = new ArrayList<CDORevision>(); CDOBranch branch = branchPoint.getBranch(); synchronized (revisionLists) { for (Map.Entry<Object, RevisionList> entry : revisionLists.entrySet()) { if (isKeyInBranch(entry.getKey(), branch)) // if (ObjectUtil.equals(entry.getKey().getBranch(), branch)) { RevisionList list = entry.getValue(); InternalCDORevision revision = list.getRevision(branchPoint.getTimeStamp()); if (revision != null) { result.add(revision); } } } } return result; } public void addRevision(CDORevision revision) { CheckUtil.checkArg(revision, "revision"); CDOID id = revision.getID(); Object key = createKey(id, revision.getBranch()); synchronized (revisionLists) { RevisionList list = revisionLists.get(key); if (list == null) { list = new RevisionList(); revisionLists.put(key, list); } list.addRevision((InternalCDORevision)revision, createReference(revision)); typeRefIncrease(id, revision.getEClass()); } } public InternalCDORevision removeRevision(CDOID id, CDOBranchVersion branchVersion) { Object key = createKey(id, branchVersion.getBranch()); synchronized (revisionLists) { RevisionList list = revisionLists.get(key); if (list != null) { list.removeRevision(branchVersion.getVersion()); if (list.isEmpty()) { revisionLists.remove(key); typeRefDecrease(id); if (TRACER.isEnabled()) { TRACER.format("Removed cache list of {0}", key); //$NON-NLS-1$ } } } } return null; } public void clear() { synchronized (revisionLists) { revisionLists.clear(); typeRefDispose(); } } @Override public String toString() { synchronized (revisionLists) { return revisionLists.toString(); } } protected void typeRefIncrease(CDOID id, EClass type) { // Do nothing } protected void typeRefDecrease(CDOID id) { // Do nothing } protected void typeRefDispose() { // Do nothing } protected Object createKey(CDOID id, CDOBranch branch) { return id; } protected boolean isKeyInBranch(Object key, CDOBranch branch) { return true; } protected RevisionList getRevisionList(CDOID id, CDOBranch branch) { Object key = createKey(id, branch); synchronized (revisionLists) { return revisionLists.get(key); } } /** * @author Eike Stepper */ protected static final class RevisionList extends LinkedList<Reference<InternalCDORevision>> { private static final long serialVersionUID = 1L; public RevisionList() { } public synchronized InternalCDORevision getRevision(long timeStamp) { if (timeStamp == CDORevision.UNSPECIFIED_DATE) { Reference<InternalCDORevision> ref = isEmpty() ? null : getFirst(); if (ref != null) { InternalCDORevision revision = ref.get(); if (revision != null) { if (!revision.isHistorical()) { return revision; } } else { removeFirst(); } } return null; } for (Iterator<Reference<InternalCDORevision>> it = iterator(); it.hasNext();) { Reference<InternalCDORevision> ref = it.next(); InternalCDORevision revision = ref.get(); if (revision != null) { long created = revision.getTimeStamp(); if (created <= timeStamp) { long revised = revision.getRevised(); if (timeStamp <= revised || revised == CDORevision.UNSPECIFIED_DATE) { return revision; } break; } } else { it.remove(); } } return null; } public synchronized InternalCDORevision getRevisionByVersion(int version) { for (Iterator<Reference<InternalCDORevision>> it = iterator(); it.hasNext();) { Reference<InternalCDORevision> ref = it.next(); InternalCDORevision revision = ref.get(); if (revision != null) { int v = revision.getVersion(); if (v == version) { return revision; } else if (v < version) { break; } } else { it.remove(); } } return null; } public synchronized boolean addRevision(InternalCDORevision revision, Reference<InternalCDORevision> reference) { int version = revision.getVersion(); for (ListIterator<Reference<InternalCDORevision>> it = listIterator(); it.hasNext();) { Reference<InternalCDORevision> ref = it.next(); InternalCDORevision foundRevision = ref.get(); if (foundRevision != null) { CDORevisionKey key = (CDORevisionKey)ref; int v = key.getVersion(); if (v == version) { return false; } if (v < version) { it.previous(); it.add(reference); return true; } } else { it.remove(); } } addLast(reference); return true; } public synchronized void removeRevision(int version) { for (Iterator<Reference<InternalCDORevision>> it = iterator(); it.hasNext();) { Reference<InternalCDORevision> ref = it.next(); CDORevisionKey key = (CDORevisionKey)ref; int v = key.getVersion(); if (v == version) { it.remove(); if (TRACER.isEnabled()) { TRACER.format("Removed version {0} from cache list of {1}", version, key.getID()); //$NON-NLS-1$ } break; } else if (v < version) { break; } } } @Override public String toString() { StringBuffer buffer = new StringBuffer(); for (Iterator<Reference<InternalCDORevision>> it = iterator(); it.hasNext();) { Reference<InternalCDORevision> ref = it.next(); InternalCDORevision revision = ref.get(); if (buffer.length() == 0) { buffer.append("{"); } else { buffer.append(", "); } buffer.append(revision); } buffer.append("}"); return buffer.toString(); } public void getAllRevisions(Map<CDOBranch, List<CDORevision>> result) { for (Iterator<Reference<InternalCDORevision>> it = iterator(); it.hasNext();) { Reference<InternalCDORevision> ref = it.next(); InternalCDORevision revision = ref.get(); if (revision != null) { CDOBranch branch = revision.getBranch(); List<CDORevision> resultList = result.get(branch); if (resultList == null) { resultList = new ArrayList<CDORevision>(1); result.put(branch, resultList); } resultList.add(revision); } } } } }
25.346154
115
0.607337
0e69dd6eb8c1898ff70ae855fd4d8314ab522f08
197
package databook.listener; import databook.persistence.rule.rdf.ruleset.Messages; public interface Indexer { void messages(Messages m) throws Exception; void setScheduler(Scheduler s); }
16.416667
54
0.781726
ed329f3f5659673755fccf043f7bd295786eaaa6
28,974
/* * 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.ijmultitemplatematching; import ij.ImagePlus; import ij.gui.Roi; import ij.gui.ShapeRoi; import ij.process.ColorProcessor; import ij.process.ImageProcessor; import org.hkijena.jipipe.JIPipe; import org.hkijena.jipipe.api.JIPipeDocumentation; import org.hkijena.jipipe.api.JIPipeNode; import org.hkijena.jipipe.api.JIPipeProgressInfo; import org.hkijena.jipipe.api.data.JIPipeDataInfo; import org.hkijena.jipipe.api.data.JIPipeDataSlotInfo; import org.hkijena.jipipe.api.data.JIPipeDefaultMutableSlotConfiguration; import org.hkijena.jipipe.api.data.JIPipeSlotType; import org.hkijena.jipipe.api.nodes.*; import org.hkijena.jipipe.api.nodes.categories.ImagesNodeTypeCategory; import org.hkijena.jipipe.api.parameters.JIPipeContextAction; import org.hkijena.jipipe.api.parameters.JIPipeParameter; import org.hkijena.jipipe.extensions.imagejdatatypes.datatypes.ImagePlusData; import org.hkijena.jipipe.extensions.imagejdatatypes.datatypes.ROIListData; import org.hkijena.jipipe.extensions.imagejdatatypes.datatypes.d2.ImagePlus2DData; import org.hkijena.jipipe.extensions.imagejdatatypes.util.ImageJUtils; import org.hkijena.jipipe.extensions.parameters.library.colors.OptionalColorParameter; import org.hkijena.jipipe.extensions.parameters.library.primitives.ranges.IntegerRange; import org.hkijena.jipipe.extensions.parameters.library.references.JIPipeDataInfoRef; import org.hkijena.jipipe.extensions.parameters.library.references.JIPipeDataParameterSettings; import org.hkijena.jipipe.extensions.parameters.library.references.OptionalDataInfoRefParameter; import org.hkijena.jipipe.extensions.tables.datatypes.ResultsTableData; import org.hkijena.jipipe.ui.JIPipeWorkbench; import org.hkijena.jipipe.ui.components.FormPanel; import org.hkijena.jipipe.utils.ParameterUtils; import org.hkijena.jipipe.utils.ResourceUtils; import org.python.core.PyList; import org.python.util.PythonInterpreter; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @JIPipeDocumentation(name = "Multi-Template matching", description = "Template matching is an algorithm that can be used for object-detections in grayscale images. " + "To perform template matching you will need a template image that is searched in the target image.\n" + "The best is to simply crop a typical region of interest from a representative image.\n\n\n\n" + "The algorithm computes the probability to find one (or several) template images provided by the user into a larger image. The algorithm uses the template image as a sliding window translated over the image, and at each position of the template computes a similarity score between the template and the image patch.\n" + "This results in a correlation map, for which the pixel value at position (x,y) is proportional to the similarity between the template and image patch, at this (x,y) position in the image. " + "The computation of the correlation map is followed by extrema detection to list the possible locations of the template in the image. Each extrema corresponds to the possible location of a bounding box of dimensions identical to the template. " + "The extrema detection can list a large number of extrema in the first place. Usually a threshold on the score is then used to limit this number (i.e. returning local extrema with a score above/below the threshold).\n" + "To prevent overlapping detection of the same object, Non-Maxima Supression is performed after extrema detection.\n\n\n\n" + "Please visit https://github.com/multi-template-matching/MultiTemplateMatching-Fiji/wiki for more information about the Multi-Template Matching plugin.") @JIPipeInputSlot(value = ImagePlusData.class, slotName = "Image", autoCreate = true) @JIPipeInputSlot(value = ImagePlus2DData.class, slotName = "Template", autoCreate = true) @JIPipeOutputSlot(value = ROIListData.class, slotName = "ROI", autoCreate = true) @JIPipeOutputSlot(value = ResultsTableData.class, slotName = "Measurements", autoCreate = true) @JIPipeOutputSlot(value = ImagePlusData.class, slotName = "Assembled templates") @JIPipeNode(menuPath = "Analyze", nodeTypeCategory = ImagesNodeTypeCategory.class) public class MultiTemplateMatchingAlgorithm extends JIPipeMergingAlgorithm { private final static String SCRIPT = loadScriptFromResources(); private boolean flipTemplateVertically = true; private boolean flipTemplateHorizontally = true; private IntegerRange rotateTemplate = new IntegerRange(); private TemplateMatchingMethod templateMatchingMethod = TemplateMatchingMethod.NormalizedZeroMeanCrossCorrelation; private int expectedNumberOfObjects = 1; private double multiObjectScoreThreshold = 0.5; private double multiObjectMaximumBoundingBoxOverlap = 0.3; private boolean restrictToROI = false; private boolean assembleTemplates = false; private boolean withNonMaximaSuppression = true; private OptionalColorParameter assembleTemplatesBackground = new OptionalColorParameter(); private OptionalDataInfoRefParameter assembleTemplatesOutput = new OptionalDataInfoRefParameter(); public MultiTemplateMatchingAlgorithm(JIPipeNodeInfo info) { super(info); assembleTemplatesBackground.setContent(Color.BLACK); rotateTemplate.setValue("90,180,270"); assembleTemplatesOutput.setContent(new JIPipeDataInfoRef(JIPipeDataInfo.getInstance(ImagePlusData.class))); } public MultiTemplateMatchingAlgorithm(MultiTemplateMatchingAlgorithm other) { super(other); this.flipTemplateVertically = other.flipTemplateVertically; this.flipTemplateHorizontally = other.flipTemplateHorizontally; this.rotateTemplate = new IntegerRange(other.rotateTemplate); this.templateMatchingMethod = other.templateMatchingMethod; this.expectedNumberOfObjects = other.expectedNumberOfObjects; this.multiObjectScoreThreshold = other.multiObjectScoreThreshold; this.multiObjectMaximumBoundingBoxOverlap = other.multiObjectMaximumBoundingBoxOverlap; this.setAssembleTemplates(other.assembleTemplates); this.assembleTemplatesBackground = new OptionalColorParameter(other.assembleTemplatesBackground); this.setRestrictToROI(other.restrictToROI); this.withNonMaximaSuppression = other.withNonMaximaSuppression; } private static String loadScriptFromResources() { return ResourceUtils.getPluginResourceAsString("extensions/ijmultitemplatematching/template-matching-script.py"); } @Override protected void runIteration(JIPipeMergingDataBatch dataBatch, JIPipeProgressInfo progressInfo) { List<ImagePlus> images = new ArrayList<>(); List<ImagePlus> templates = new ArrayList<>(); ROIListData mergedSearchRois = new ROIListData(); for (ImagePlusData image : dataBatch.getInputData("Image", ImagePlusData.class, progressInfo)) { images.add(image.getImage()); } // Each template has its own index for (ImagePlusData template : dataBatch.getInputData("Template", ImagePlusData.class, progressInfo)) { ImagePlus duplicateImage = template.getDuplicateImage(); duplicateImage.setTitle("" + templates.size()); templates.add(duplicateImage); } if (restrictToROI) { for (ROIListData roi : dataBatch.getInputData("ROI", ROIListData.class, progressInfo)) { mergedSearchRois.addAll(roi); } } Roi searchRoi = mergedSearchRois.isEmpty() ? null : new ShapeRoi(mergedSearchRois.getBounds()); PythonInterpreter pythonInterpreter = new PythonInterpreter(); pythonInterpreter.set("Method", templateMatchingMethod.getIndex()); pythonInterpreter.set("fliph", flipTemplateHorizontally); pythonInterpreter.set("flipv", flipTemplateVertically); pythonInterpreter.set("angles", rotateTemplate.getIntegers(0, 365).stream().map(Object::toString).collect(Collectors.joining(","))); pythonInterpreter.set("n_hit", expectedNumberOfObjects); pythonInterpreter.set("score_threshold", multiObjectScoreThreshold); pythonInterpreter.set("tolerance", 0); pythonInterpreter.set("max_overlap", multiObjectMaximumBoundingBoxOverlap); pythonInterpreter.set("List_Template", new PyList(templates)); pythonInterpreter.set("Bool_SearchRoi", restrictToROI && searchRoi != null); pythonInterpreter.set("searchRoi", searchRoi); pythonInterpreter.set("progress", progressInfo); pythonInterpreter.set("with_nms", withNonMaximaSuppression); for (int i = 0; i < images.size(); i++) { ImagePlus image = images.get(i); ROIListData detectedROIs = new ROIListData(); ResultsTableData measurements = new ResultsTableData(); pythonInterpreter.set("ImpImage", image); pythonInterpreter.set("rm", detectedROIs); pythonInterpreter.set("Table", measurements.getTable()); pythonInterpreter.set("progress", progressInfo.resolve("Image", i, images.size())); pythonInterpreter.exec(SCRIPT); dataBatch.addOutputData("ROI", detectedROIs, progressInfo); dataBatch.addOutputData("Measurements", measurements, progressInfo); if (assembleTemplates) { ImagePlus assembled = assembleTemplates(image, templates, measurements, progressInfo.resolveAndLog("Assemble templates", i, images.size())); dataBatch.addOutputData("Assembled templates", new ImagePlusData(assembled), progressInfo); } } } private ImagePlus assembleTemplates(ImagePlus original, List<ImagePlus> templates, ResultsTableData measurements, JIPipeProgressInfo progressInfo) { // Create a target image of the appropriate type ImagePlus target; if (assembleTemplatesOutput.isEnabled()) { ImagePlusData data = (ImagePlusData) JIPipe.createData(assembleTemplatesOutput.getContent().getInfo().getDataClass(), original); if (data.getImage() == original) target = data.getDuplicateImage(); else target = data.getImage(); } else { target = ImageJUtils.duplicate(original); } // Fill with color if requested target = ImageJUtils.channelsToRGB(target); if (assembleTemplatesBackground.isEnabled()) { if (target.getType() == ImagePlus.COLOR_RGB) { Color color = assembleTemplatesBackground.getContent(); ImageJUtils.forEachSlice(target, ip -> { ColorProcessor colorProcessor = (ColorProcessor) ip; ip.setRoi(0, 0, ip.getWidth(), ip.getHeight()); colorProcessor.setColor(color); ip.fill(); ip.setRoi((Roi) null); }, progressInfo); } else { Color color = assembleTemplatesBackground.getContent(); double value = (color.getRed() + color.getGreen() + color.getBlue()) / 3.0; ImageJUtils.forEachSlice(target, ip -> ip.set(value), progressInfo); } } // Draw the templates ImageProcessor targetProcessor = target.getProcessor(); for (int row = 0; row < measurements.getRowCount(); row++) { String templateName = measurements.getValueAsString(row, "Template"); boolean verticalFlip = templateName.contains("Vertical_Flip"); boolean horizontalFlip = templateName.contains("Horizontal_Flip"); int rotation = 0; for (String s : templateName.split("_")) { if (s.endsWith("degrees")) { rotation = Integer.parseInt(s.substring(0, s.indexOf("degrees"))); } } int templateIndex = Integer.parseInt(templateName.split("_")[0]); ImagePlus template = ImageJUtils.duplicate(templates.get(templateIndex)); ImageProcessor templateProcessor = template.getProcessor(); if (verticalFlip) templateProcessor.flipVertical(); if (horizontalFlip) templateProcessor.flipHorizontal(); if (rotation != 0) { template = ImageJUtils.rotate(template, rotation, true, Color.BLACK, true, progressInfo); templateProcessor = template.getProcessor(); } if (template.getRoi() == null) { template.setRoi(new Rectangle(0, 0, template.getWidth(), template.getHeight())); } Roi templateRoi = template.getRoi(); int locationX = (int) measurements.getValueAsDouble(row, "Xcorner"); int locationY = (int) measurements.getValueAsDouble(row, "Ycorner"); for (int y = 0; y < templateProcessor.getHeight(); y++) { int targetY = y + locationY; if (targetY < 0) continue; if (targetY >= targetProcessor.getHeight()) break; for (int x = 0; x < templateProcessor.getWidth(); x++) { int targetX = x + locationX; if (targetX < 0) continue; if (targetX >= targetProcessor.getWidth()) break; if (!templateRoi.contains(x, y)) continue; targetProcessor.setf(targetX, targetY, templateProcessor.getf(x, y)); } } } return target; } @JIPipeDocumentation(name = "Flip template vertically", description = "Performing additional searches with the transformed template allows to maximize the probability to find the object, if the object is expected to have different orientations in the image.\n" + "This is due to the fact that the template matching only looks for translated version of the templates provided.\n" + "Possible transformations include flipping (also called mirroring), rotation (below). Scaling is not proposed in the interface but several templates at different scale can be provided in the multiple template version of the plugin.\n" + "If vertical and horizontal flipping are selected, then the plugin generates 2 additional templates for the corresponding transformation.") @JIPipeParameter("flip-template-vertically") public boolean isFlipTemplateVertically() { return flipTemplateVertically; } @JIPipeParameter("flip-template-vertically") public void setFlipTemplateVertically(boolean flipTemplateVertically) { this.flipTemplateVertically = flipTemplateVertically; } @JIPipeDocumentation(name = "Flip template horizontally", description = "Performing additional searches with the transformed template allows to maximize the probability to find the object, if the object is expected to have different orientations in the image.\n" + "This is due to the fact that the template matching only looks for translated version of the templates provided.\n" + "Possible transformations include flipping (also called mirroring), rotation (below). Scaling is not proposed in the interface but several templates at different scale can be provided in the multiple template version of the plugin.\n" + "If vertical and horizontal flipping are selected, then the plugin generates 2 additional templates for the corresponding transformation.") @JIPipeParameter("flip-template-horizontally") public boolean isFlipTemplateHorizontally() { return flipTemplateHorizontally; } @JIPipeParameter("flip-template-horizontally") public void setFlipTemplateHorizontally(boolean flipTemplateHorizontally) { this.flipTemplateHorizontally = flipTemplateHorizontally; } @JIPipeDocumentation(name = "Additional template rotations", description = "It is possible to provide a list of clockwise rotations in degrees e.g.: 45,90,180.\n" + "As with flipping, performing searches with rotated version of the template increases the probability to find the object if it is expected to be rotated.\n" + "If flipping is selected, both the original and flipped versions of the template will be rotated.\n\n\n" + "NOTE: The template must be of rectangular shape, i.e. for angles not corresponding to \"square rotations\" (not a multiple of 90°) the rotated template will have some background area which are filled either with the modal gray value of the template (Fiji) or" + " with the pixel at the border in the initial template (KNIME). For higher performance, the non square rotations can be manually generated before calling the plugin and saved as templates.") @JIPipeParameter("template-rotations") public IntegerRange getRotateTemplate() { return rotateTemplate; } @JIPipeParameter("template-rotations") public void setRotateTemplate(IntegerRange rotateTemplate) { this.rotateTemplate = rotateTemplate; } @JIPipeDocumentation(name = "Scoring method", description = "This is the formula used to compute the probability map. " + "The choice is limited to normalised scores to be able to compare different correlation maps when multiple templates are used.\n\n" + "<ul>" + "\n" + "<li>Normalised Square Difference (NSD): The pixels in the probability map are computed as the sum of difference between the gray level of pixels from the image patch and from the template normalised by the square root of the sum of the squared pixel values. " + "Therefore a high probability to find the object corresponds to a low score value (not as good as the correlation scores usually).</li>" + "<li>Normalised Cross-Correlation (NCC) : The pixels in the probability map are computed as the sum of the pixel/pixel product between the template and current image patch, also normalized for the difference. a high probability to find the object corresponds to a high score value.</li>" + "<li>0-mean Normalized Cross-Correlation (0-mean NCC) : The mean value of the template and the image patch is substracted to each pixel value before computing the cross-correlation as above. " + "Like the correlation method, a high probability to find the object corresponds to a high score value. (usually this method is most robust to change of illumination)</li>" + "</ul>" + "\n\nPlease take a look at the OpenCV documentation for more information: https://www.docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html") @JIPipeParameter("template-matching-method") public TemplateMatchingMethod getTemplateMatchingMethod() { return templateMatchingMethod; } @JIPipeParameter("template-matching-method") public void setTemplateMatchingMethod(TemplateMatchingMethod templateMatchingMethod) { this.templateMatchingMethod = templateMatchingMethod; } @JIPipeDocumentation(name = "Enable non-maxima suppression", description = "Enables the non-maxima-suppression algorithm that removes bounding boxes that overlap too much.") @JIPipeParameter("with-non-maxima-suppression") public boolean isWithNonMaximaSuppression() { return withNonMaximaSuppression; } @JIPipeParameter("with-non-maxima-suppression") public void setWithNonMaximaSuppression(boolean withNonMaximaSuppression) { this.withNonMaximaSuppression = withNonMaximaSuppression; } @JIPipeDocumentation(name = "Expected number of objects (N)", description = "This is the expected number of object expected in each image. The plugin will return N or less predicted locations of the object.") @JIPipeParameter("expected-number-of-objects") public int getExpectedNumberOfObjects() { return expectedNumberOfObjects; } @JIPipeParameter("expected-number-of-objects") public boolean setExpectedNumberOfObjects(int expectedNumberOfObjects) { if (expectedNumberOfObjects <= 0) return false; this.expectedNumberOfObjects = expectedNumberOfObjects; return true; } @JIPipeDocumentation(name = "Score threshold (N>1)", description = "Ranges from 0.0 to 1.0. Used for the extrema detection on the score map(s).\n" + "If the difference-score is used, only minima below this threshold are collected before NMS (i.e. increase to evaluate more hits).\n" + "If a correlation-score is used, only maxima above this threshold are collected before NMS (i.e. decrease to evaluate more hits).") @JIPipeParameter("multi-object-score-threshold") public double getMultiObjectScoreThreshold() { return multiObjectScoreThreshold; } @JIPipeParameter("multi-object-score-threshold") public boolean setMultiObjectScoreThreshold(double multiObjectScoreThreshold) { if (multiObjectScoreThreshold < 0 || multiObjectScoreThreshold > 1) return false; this.multiObjectScoreThreshold = multiObjectScoreThreshold; return true; } @JIPipeDocumentation(name = "Maximum overlap (N>1)", description = "Ranges from 0.0 to 1.0. Typically in the range 0.1-0.5.\n" + "This parameter is for the Non-Maxima Suppression (NMS). It must be adjusted to prevent overlapping detections while keeping detections of close objects. " + "This is the maximal value allowed for the ratio of the Intersection Over Union (IoU) area between overlapping bounding boxes.\n" + "If 2 bounding boxes are overlapping above this threshold, then the lower score one is discarded.") @JIPipeParameter("multi-object-max-bounding-box-overlap") public double getMultiObjectMaximumBoundingBoxOverlap() { return multiObjectMaximumBoundingBoxOverlap; } @JIPipeParameter("multi-object-max-bounding-box-overlap") public boolean setMultiObjectMaximumBoundingBoxOverlap(double multiObjectMaximumBoundingBoxOverlap) { if (multiObjectMaximumBoundingBoxOverlap < 0 || multiObjectMaximumBoundingBoxOverlap > 1) return false; this.multiObjectMaximumBoundingBoxOverlap = multiObjectMaximumBoundingBoxOverlap; return true; } @JIPipeDocumentation(name = "Restrict to ROI", description = "If enabled, the template matching is restricted to the bounding box of the supplied ROI.") @JIPipeParameter("restrict-to-roi") public boolean isRestrictToROI() { return restrictToROI; } @JIPipeParameter("restrict-to-roi") public void setRestrictToROI(boolean restrictToROI) { this.restrictToROI = restrictToROI; JIPipeDefaultMutableSlotConfiguration slotConfiguration = (JIPipeDefaultMutableSlotConfiguration) getSlotConfiguration(); if (restrictToROI && !getInputSlotMap().containsKey("ROI")) { slotConfiguration.addSlot("ROI", new JIPipeDataSlotInfo(ROIListData.class, JIPipeSlotType.Input), false); } else if (!restrictToROI && getInputSlotMap().containsKey("ROI")) { slotConfiguration.removeInputSlot("ROI", false); } } @JIPipeContextAction(iconURL = ResourceUtils.RESOURCE_BASE_PATH + "/icons/actions/draw-use-tilt.png", iconDarkURL = ResourceUtils.RESOURCE_BASE_PATH + "/dark/icons/actions/draw-use-tilt.png") @JIPipeDocumentation(name = "Generate angles", description = "Generates additional rotation angles by providing the distance between them.") public void generateRotations(JIPipeWorkbench workbench) { JSpinner startAngle = new JSpinner(new SpinnerNumberModel(0, Integer.MIN_VALUE, Integer.MAX_VALUE, 1)); JSpinner endAngle = new JSpinner(new SpinnerNumberModel(360, Integer.MIN_VALUE, Integer.MAX_VALUE, 1)); JSpinner angleStep = new JSpinner(new SpinnerNumberModel(90, 1, Integer.MAX_VALUE, 1)); FormPanel formPanel = new FormPanel(null, FormPanel.NONE); formPanel.addToForm(startAngle, new JLabel("Start angle"), null); formPanel.addToForm(endAngle, new JLabel("End angle"), null); formPanel.addToForm(angleStep, new JLabel("Increment"), null); int result = JOptionPane.showOptionDialog( workbench.getWindow(), new Object[]{formPanel}, "Generate angles", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (result == JOptionPane.OK_OPTION) { int startAngleValue = ((SpinnerNumberModel) startAngle.getModel()).getNumber().intValue(); int endAngleValue = ((SpinnerNumberModel) endAngle.getModel()).getNumber().intValue(); int step = ((SpinnerNumberModel) angleStep.getModel()).getNumber().intValue(); if (endAngleValue < startAngleValue) { JOptionPane.showMessageDialog(workbench.getWindow(), "The start angle must be less than the end angle!", "Generate angles", JOptionPane.ERROR_MESSAGE); return; } StringBuilder stringBuilder = new StringBuilder(); int angle = startAngleValue; do { if (stringBuilder.length() > 0) stringBuilder.append(","); stringBuilder.append(angle); angle += step; } while (angle < endAngleValue); ParameterUtils.setParameter(this, "template-rotations", new IntegerRange(stringBuilder.toString())); } } @JIPipeDocumentation(name = "Assemble templates", description = "If enabled, all matched templates are put at their matched located within the original image. You can choose to overlay them over the original image or generate an empty image.") @JIPipeParameter("assemble-templates") public boolean isAssembleTemplates() { return assembleTemplates; } @JIPipeParameter("assemble-templates") public void setAssembleTemplates(boolean assembleTemplates) { this.assembleTemplates = assembleTemplates; updateSlots(); } private void updateSlots() { if (assembleTemplates) { if (!hasOutputSlot("Assembled templates")) { JIPipeDefaultMutableSlotConfiguration slotConfiguration = (JIPipeDefaultMutableSlotConfiguration) getSlotConfiguration(); slotConfiguration.addOutputSlot("Assembled templates", "The assembled templates", ImagePlusData.class, null, false); } } else { if (hasOutputSlot("Assembled templates")) { JIPipeDefaultMutableSlotConfiguration slotConfiguration = (JIPipeDefaultMutableSlotConfiguration) getSlotConfiguration(); slotConfiguration.removeOutputSlot("Assembled templates", false); } } } @JIPipeDocumentation(name = "Assemble templates background", description = "If enabled, 'Assemble templates' will be put to an image of the given background. Please note that ") @JIPipeParameter("assemble-templates-background") public OptionalColorParameter getAssembleTemplatesBackground() { return assembleTemplatesBackground; } @JIPipeParameter("assemble-templates-background") public void setAssembleTemplatesBackground(OptionalColorParameter assembleTemplatesBackground) { this.assembleTemplatesBackground = assembleTemplatesBackground; } @JIPipeDocumentation(name = "Assemble templates output", description = "If enabled, override the type of the generated assembly. If disabled, it has the same type as the input image.") @JIPipeParameter("assemble-templates-output") @JIPipeDataParameterSettings(dataBaseClass = ImagePlusData.class) public OptionalDataInfoRefParameter getAssembleTemplatesOutput() { return assembleTemplatesOutput; } @JIPipeParameter("assemble-templates-output") public void setAssembleTemplatesOutput(OptionalDataInfoRefParameter assembleTemplatesOutput) { this.assembleTemplatesOutput = assembleTemplatesOutput; } }
59.740206
327
0.709912
544e3927e8e1f80dfb74f3828e87a4d480484ef2
305
package com.sensiblemetrics.api.alpenidos.pattern.adapter8.model; import java.math.BigDecimal; /** * Standard Account holder cannot have overdraft. */ public class StandardAccount extends AbstractAccount { public StandardAccount(final BigDecimal balance) { super(balance, false); } }
21.785714
65
0.75082
4646f58b8dc94b39212d0f10c8f8e523bbed6144
2,853
package model; import java.io.Serializable; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; /** * The persistent class for the bookingdetails database table. * */ @Entity @Table(name="bookingdetails") @NamedQuery(name="Bookingdetail.findAll", query="SELECT bd FROM Bookingdetail bd") public class Bookingdetail implements Serializable { private static final long serialVersionUID = 1L; @Id private int bookingDetailId; private BigDecimal agencyCommission; private BigDecimal basePrice; private int bookingId; private String classId; @Lob private String description; @Lob private String destination; private String feeId; private double itineraryNo; private int productSupplierId; private String regionId; @Temporal(TemporalType.TIMESTAMP) private Date tripEnd; @Temporal(TemporalType.TIMESTAMP) private Date tripStart; public Bookingdetail() { } public int getBookingDetailId() { return this.bookingDetailId; } public void setBookingDetailId(int bookingDetailId) { this.bookingDetailId = bookingDetailId; } public BigDecimal getAgencyCommission() { return this.agencyCommission; } public void setAgencyCommission(BigDecimal agencyCommission) { this.agencyCommission = agencyCommission; } public BigDecimal getBasePrice() { return this.basePrice; } public void setBasePrice(BigDecimal basePrice) { this.basePrice = basePrice; } public int getBookingId() { return this.bookingId; } public void setBookingId(int bookingId) { this.bookingId = bookingId; } public String getClassId() { return this.classId; } public void setClassId(String classId) { this.classId = classId; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getDestination() { return this.destination; } public void setDestination(String destination) { this.destination = destination; } public String getFeeId() { return this.feeId; } public void setFeeId(String feeId) { this.feeId = feeId; } public double getItineraryNo() { return this.itineraryNo; } public void setItineraryNo(double itineraryNo) { this.itineraryNo = itineraryNo; } public int getProductSupplierId() { return this.productSupplierId; } public void setProductSupplierId(int productSupplierId) { this.productSupplierId = productSupplierId; } public String getRegionId() { return this.regionId; } public void setRegionId(String regionId) { this.regionId = regionId; } public Date getTripEnd() { return this.tripEnd; } public void setTripEnd(Date tripEnd) { this.tripEnd = tripEnd; } public Date getTripStart() { return this.tripStart; } public void setTripStart(Date tripStart) { this.tripStart = tripStart; } }
18.171975
82
0.750088
537e738fb48ff62efe5e2a63d8c87b6b0c522de0
639
package Practise9; /* 编写两个类,TriAngle和TriAnTest,其中Triangle类中声明私有的底边长base和高height, 同时声明公共方法访问私有变量,此外,提供类必要的构造器。 另一个类中使用这些公共方法,计算三角形的面积 */ public class TriAngleTest { public static void main(String[] args) { TriAngle t1=new TriAngle(); t1.setBase(2.0); t1.setHeight(2.4); //不能用t1.base=2.0;t1.height=2.4; System.out.println("base : "+t1.getBase()+"\n"+"height : "+t1.getHeight()+"\n"+"area : "+t1.getBase()*t1.getHeight()/2); TriAngle t2=new TriAngle(5.1,5.6); System.out.println("base : "+t2.getBase()+"\n"+"height : "+t2.getHeight()+"\n"+"area : "+t2.getBase()*t2.getHeight()/2); } }
35.5
128
0.636933
2f6df0c5e2493cbbb95ce6adc80d54c8816b6384
974
package com.github.dockerjava.api.model; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; public class LinkTest { @Test public void parse() { Link link = Link.parse("name:alias"); assertEquals(link.getName(), "name"); assertEquals(link.getAlias(), "alias"); } @Test public void parseWithContainerNames() { Link link = Link.parse("/name:/conatiner/alias"); assertEquals(link.getName(), "name"); assertEquals(link.getAlias(), "alias"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Error parsing Link 'nonsense'") public void parseInvalidInput() { Link.parse("nonsense"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Error parsing Link 'null'") public void parseNull() { Link.parse(null); } @Test public void stringify() { assertEquals(Link.parse("name:alias").toString(), "name:alias"); } }
23.756098
69
0.723819
09dc2d6bc99a9a76c29233ecb57be94b325661bb
3,180
package org.odk.share.services; import com.evernote.android.job.Job; import com.evernote.android.job.JobManager; import com.evernote.android.job.JobRequest; import com.evernote.android.job.util.support.PersistableBundleCompat; import org.odk.share.events.UploadEvent; import org.odk.share.rx.RxEventBus; import org.odk.share.rx.schedulers.BaseSchedulerProvider; import org.odk.share.tasks.UploadJob; import java.util.LinkedList; import java.util.Queue; import javax.inject.Inject; import javax.inject.Singleton; import timber.log.Timber; import static org.odk.share.fragments.ReviewedInstancesFragment.MODE; @Singleton public class SenderService { private final Queue<JobRequest> jobs = new LinkedList<>(); private final RxEventBus rxEventBus; private final BaseSchedulerProvider schedulerProvider; private JobRequest currentJob; @Inject public SenderService(RxEventBus rxEventBus, BaseSchedulerProvider schedulerProvider) { this.rxEventBus = rxEventBus; this.schedulerProvider = schedulerProvider; addUploadJobSubscription(); } private void addUploadJobSubscription() { rxEventBus.register(UploadEvent.class) .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.androidThread()) .doOnNext(uploadEvent -> { switch (uploadEvent.getStatus()) { case CANCELLED: case ERROR: jobs.clear(); currentJob = null; break; case FINISHED: if (jobs.size() > 0) { startJob(jobs.remove()); } else { currentJob = null; } break; } }).subscribe(); } public void startUploading(long[] instancesToSend, int port, int mode) { PersistableBundleCompat extras = new PersistableBundleCompat(); extras.putLongArray(UploadJob.INSTANCES, instancesToSend); extras.putInt(UploadJob.PORT, port); extras.putInt(MODE, mode); // Build request JobRequest request = new JobRequest.Builder(UploadJob.TAG) .addExtras(extras) .startNow() .build(); if (currentJob != null) { jobs.add(request); } else { startJob(request); } } private void startJob(JobRequest request) { request.schedule(); Timber.d("Starting upload job %d : ", request.getJobId()); currentJob = request; } public void cancel() { if (currentJob != null) { Job job = JobManager.instance().getJob(currentJob.getJobId()); if (job != null) { job.cancel(); rxEventBus.post(new UploadEvent(UploadEvent.Status.CANCELLED)); } else { Timber.e("Pending job not found : %s", currentJob); } currentJob = null; } } }
31.176471
90
0.57673
e8b319e104369a173b74fe361f3c685ebb050e75
538
package cn.kiway.mp.ui.fragment; import android.widget.BaseAdapter; import java.util.List; import cn.kiway.mp.adapter.SubjectListAdapter; import cn.kiway.mp.bean.SubjectBean; public class SubjectFragment extends BaseLoadMoreListFragment { private List<SubjectBean> mSubjects; @Override protected void startLoadData() { } @Override protected BaseAdapter onCreateAdapter() { return new SubjectListAdapter(getContext(), mSubjects); } @Override protected void onStartLoadMore() { } }
18.551724
63
0.726766
dc2538acafbf1d7eb5bf89119a74af45dd8a74e2
559
package uk.co.ribot.androidboilerplate.injection.module; import dagger.Module; import dagger.Provides; import uk.co.ribot.androidboilerplate.data.local.PreferencesHelper; /** * Created by mike on 2017/9/28. */ @Module public class PreferenceModule { private PreferencesHelper mPreferencesHelper; public PreferenceModule(PreferencesHelper preferencesHelper) { mPreferencesHelper = preferencesHelper; } @Provides PreferencesHelper providePreferencesHelper() { return mPreferencesHelper; } }
23.291667
68
0.728086
0731c1d097b9a1ceea8a56657804d0dafa34bfd9
424
package org.springframework.security.oauth2.server.authorization.mongodb; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Created on: 9/13/21. * * @author Bjorn Harvold Responsibility: */ @NoArgsConstructor @AllArgsConstructor @Data public class OAuth2ClientSettings { private boolean requireProofKey = false; private boolean requireAuthorizationConsent = false; }
22.315789
73
0.792453
2e702441e0e4fdc0c96f456fb955219d80d10ca5
1,586
package com.intita.forum.config; import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.EnableWebMvcConfiguration; import org.springframework.boot.autoconfigure.web.WebMvcProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc @ComponentScan @Import(EnableWebMvcConfiguration.class) @EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class }) public class CustomWebMvcAutoConfiguration extends WebMvcConfigurerAdapter { private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" }; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!registry.hasMappingForPattern("/getForm/**")) { registry.addResourceHandler("/getForm/**").addResourceLocations( CLASSPATH_RESOURCE_LOCATIONS); } if (!registry.hasMappingForPattern("/**")) { registry.addResourceHandler("/**").addResourceLocations( CLASSPATH_RESOURCE_LOCATIONS); } } }
44.055556
100
0.825977
5433946065e0f8b55b4c254eeb38f3d7dd97a6f3
62
package com.lns.tinydbms.parser; public class Expression { }
12.4
32
0.774194
66ffc73425f354e4edddd34670f1ef2c124a9be6
636
package com.github.tobiasmiosczka.discordstats.persistence.repositories; import com.github.tobiasmiosczka.discordstats.persistence.model.DiscordGuild; import com.github.tobiasmiosczka.discordstats.persistence.model.DiscordUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface DiscordGuildRepository extends JpaRepository<DiscordGuild, Long> { @Query("SELECT g FROM DiscordGuild g, DiscordGuildMember m WHERE g = m.discordUser AND m.discordUser = ?1") List<DiscordGuild> findByDiscordUser(DiscordUser discordUser); }
42.4
111
0.833333
74ae09bf1b784841474c6763e849b5100ea17112
247
package com.example.demo.service; import com.alibaba.fastjson.JSONObject; import org.springframework.stereotype.Service; @Service public interface CourseService { JSONObject course(String id); JSONObject coursesearch(String stuId); }
17.642857
46
0.789474
17423b0db775cf36e763706d1274f3b532daf978
10,424
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: com/google/protobuf/nested_extension_lite.proto package protobuf_unittest; public final class NestedExtensionLite { private NestedExtensionLite() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { registry.add(protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite.recursiveExtensionLite); } public interface MyNestedExtensionLiteOrBuilder extends // @@protoc_insertion_point(interface_extends:protobuf_unittest.MyNestedExtensionLite) com.google.protobuf.MessageLiteOrBuilder { } /** * Protobuf type {@code protobuf_unittest.MyNestedExtensionLite} */ public static final class MyNestedExtensionLite extends com.google.protobuf.GeneratedMessageLite implements // @@protoc_insertion_point(message_implements:protobuf_unittest.MyNestedExtensionLite) MyNestedExtensionLiteOrBuilder { private MyNestedExtensionLite( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { com.google.protobuf.UnknownFieldSetLite.Builder unknownFields = com.google.protobuf.UnknownFieldSetLite.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); } } public static final com.google.protobuf.Parser<MyNestedExtensionLite> PARSER = new com.google.protobuf.AbstractParser<MyNestedExtensionLite>() { public MyNestedExtensionLite parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MyNestedExtensionLite(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<MyNestedExtensionLite> getParserForType() { return PARSER; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); unknownFields.writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return new Builder(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code protobuf_unittest.MyNestedExtensionLite} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite, Builder> implements // @@protoc_insertion_point(builder_implements:protobuf_unittest.MyNestedExtensionLite) protobuf_unittest.NestedExtensionLite.MyNestedExtensionLiteOrBuilder { // Construct using protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite.newBuilder() private Builder() { super(defaultInstance); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } public Builder clear() { super.clear(); return this; } public protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite buildPartial() { protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite result = null; try { result = new protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite( com.google.protobuf.Internal .EMPTY_CODED_INPUT_STREAM, com.google.protobuf.ExtensionRegistryLite .getEmptyRegistry()); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw new RuntimeException(e); } result.unknownFields = this.unknownFields; return result; } public Builder mergeFrom(protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite other) { if (other == protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); return this; } public final boolean isInitialized() { return true; } // @@protoc_insertion_point(builder_scope:protobuf_unittest.MyNestedExtensionLite) } // @@protoc_insertion_point(class_scope:protobuf_unittest.MyNestedExtensionLite) private static final protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite defaultInstance;static { try { defaultInstance = new MyNestedExtensionLite( com.google.protobuf.Internal .EMPTY_CODED_INPUT_STREAM, com.google.protobuf.ExtensionRegistryLite .getEmptyRegistry()); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw new ExceptionInInitializerError(e); } } public static protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite getDefaultInstance() { return defaultInstance; } public protobuf_unittest.NestedExtensionLite.MyNestedExtensionLite getDefaultInstanceForType() { return defaultInstance; } public static final int RECURSIVEEXTENSIONLITE_FIELD_NUMBER = 3; /** * <code>extend .protobuf_unittest.MessageLiteToBeExtended { ... }</code> */ public static final com.google.protobuf.GeneratedMessageLite.GeneratedExtension< protobuf_unittest.NonNestedExtensionLite.MessageLiteToBeExtended, protobuf_unittest.NonNestedExtensionLite.MessageLiteToBeExtended> recursiveExtensionLite = com.google.protobuf.GeneratedMessageLite .newSingularGeneratedExtension( protobuf_unittest.NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), protobuf_unittest.NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), protobuf_unittest.NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), null, 3, com.google.protobuf.WireFormat.FieldType.MESSAGE, protobuf_unittest.NonNestedExtensionLite.MessageLiteToBeExtended.class); } static { } // @@protoc_insertion_point(outer_class_scope) }
41.03937
139
0.717959
88363df42b11ce960968622be040540e9b940ab9
457
package net.minestom.server.command.builder.parser; import net.minestom.server.command.builder.CommandSyntax; import net.minestom.server.command.builder.arguments.Argument; import java.util.Map; /** * Holds the data of a validated syntax. */ public record ValidSyntaxHolder(String commandString, CommandSyntax syntax, Map<Argument<?>, ArgumentParser.ArgumentResult> argumentResults) { }
28.5625
98
0.691466
e5ef3590481adceabee19918681a2a8e7779408f
3,865
package org.openstreetmap.atlas.tags.annotations.extraction; import java.util.Optional; import org.openstreetmap.atlas.tags.annotations.Tag; import org.openstreetmap.atlas.tags.annotations.validation.LengthValidator; import org.openstreetmap.atlas.utilities.collections.StringList; import org.openstreetmap.atlas.utilities.scalars.Distance; /** * Extracts a {@link Distance} from a value. Can be used on tag values such as * {@link org.openstreetmap.atlas.tags.WidthTag}. * * @author bbreithaupt */ public class LengthExtractor implements TagExtractor { private static final LengthValidator VALIDATOR = new LengthValidator(); private static final String SINGLE_SPACE = " "; /** * Validates and converts a value to a {@link Distance}. * * @param value * {@link String} value. * @return {@link Optional} of a {@link Distance} */ public static Optional<Distance> validateAndExtract(final String value) { final String uppercaseValue = value.toUpperCase(); if (VALIDATOR.isValid(uppercaseValue)) { if (uppercaseValue.endsWith(SINGLE_SPACE + Distance.UnitAbbreviations.M)) { return Optional.of(Distance.meters(Double.valueOf(uppercaseValue.substring(0, uppercaseValue.lastIndexOf(SINGLE_SPACE + Distance.UnitAbbreviations.M))))); } else if (uppercaseValue.endsWith(SINGLE_SPACE + Distance.UnitAbbreviations.KM)) { return Optional.of(Distance .kilometers(Double.valueOf(uppercaseValue.substring(0, uppercaseValue .lastIndexOf(SINGLE_SPACE + Distance.UnitAbbreviations.KM))))); } else if (uppercaseValue.endsWith(SINGLE_SPACE + Distance.UnitAbbreviations.MI)) { return Optional .of(Distance.miles(Double.valueOf(uppercaseValue.substring(0, uppercaseValue .lastIndexOf(SINGLE_SPACE + Distance.UnitAbbreviations.MI))))); } else if (uppercaseValue.endsWith(SINGLE_SPACE + Distance.UnitAbbreviations.NMI)) { return Optional.of(Distance .nauticalMiles(Double.valueOf(uppercaseValue.substring(0, uppercaseValue .lastIndexOf(SINGLE_SPACE + Distance.UnitAbbreviations.NMI))))); } else if (uppercaseValue.contains(Distance.INCHES_NOTATION)) { final StringList split = StringList.split(uppercaseValue, Distance.FEET_NOTATION); if (split.size() == 2) { return Optional.of(Distance.feetAndInches(Double.valueOf(split.get(0)), Double.valueOf(split.get(1).substring(0, split.get(1).lastIndexOf(Distance.INCHES_NOTATION))))); } else if (split.size() == 1) { return Optional.of(Distance.inches(Double.valueOf(split.get(0).substring(0, split.get(0).lastIndexOf(Distance.INCHES_NOTATION))))); } } else if (uppercaseValue.contains(Distance.FEET_NOTATION)) { return Optional.of(Distance.feet(Double.valueOf(uppercaseValue.substring(0, uppercaseValue.lastIndexOf(Distance.FEET_NOTATION))))); } else { return Optional.of(Distance.meters(Double.valueOf(uppercaseValue))); } } return Optional.empty(); } @Override public Optional<Distance> validateAndExtract(final String value, final Tag tag) { return LengthExtractor.validateAndExtract(value); } }
42.944444
100
0.602587
80dfe650e2dbf83d06facfd119d900c12555b01f
2,954
package com.example.activiti.demo.config; import lombok.extern.slf4j.Slf4j; import org.activiti.engine.*; import org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration; import org.activiti.engine.repository.DeploymentBuilder; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourcePatternResolver; import javax.annotation.PostConstruct; import javax.sql.DataSource; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Configuration @EnableConfigurationProperties(ActivitiProperties.class) @Slf4j public class ActivitiConfig { @Autowired private DataSource dataSource; @Autowired private ResourcePatternResolver resourceLoader; @Autowired private ActivitiProperties properties; @Bean public StandaloneProcessEngineConfiguration processEngineConfiguration() { StandaloneProcessEngineConfiguration configuration = new StandaloneProcessEngineConfiguration(); configuration.setDataSource(dataSource); configuration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE); configuration.setAsyncExecutorActivate(true); return configuration; } @Bean public ProcessEngine processEngine() { return processEngineConfiguration().buildProcessEngine(); } @Bean public RepositoryService repositoryService() { return processEngine().getRepositoryService(); } @Bean public RuntimeService runtimeService() { return processEngine().getRuntimeService(); } @Bean public TaskService taskService() { return processEngine().getTaskService(); } /** * 部署流程 */ @PostConstruct public void initProcess() throws IOException { DeploymentBuilder builder = repositoryService().createDeployment().enableDuplicateFiltering().name("activitiAutoDeploy"); List<Resource> resourceList = new ArrayList<>(); //读资源 for (String suffix : properties.getProcessDefinitionLocationSuffixes()) { Resource[] resources = resourceLoader.getResources(properties.getProcessDefinitionLocationPrefix() + suffix); resourceList.addAll(Arrays.asList(resources)); } if (CollectionUtils.isEmpty(resourceList)) { log.info("there no process file to deploy"); return; } for (Resource resource : resourceList) { builder.addInputStream(resource.getFilename(), resource.getInputStream()); } builder.deploy(); log.info("deploy success"); } }
33.191011
129
0.739675
1ec8cce00ad156474acc1838da021c57a6b90676
1,523
package org.tdl.vireo.export; import java.io.File; import java.io.IOException; import java.util.zip.ZipOutputStream; import org.tdl.vireo.search.SearchFilter; /** * Export service. This service's purpose is to contain all the nitty details of * generating an export. The client is only responsible for reading the * ChunkStream and writing the result to a file somewhere. The generation of the * export will occur on a background thread, but the caller needs to handle the * output generated. This probably means delievering it to the clients browser * using an algorithm like: * * ChunkStream stream = exportService.export(package,filter); * * response.contentType = stream.getContentType(); * response.setHeader("Content-Disposition", stream.getContentDisposition()); * * while(stream.hasNextChunk()) { Promise<byte[]> nextChunk = * stream.nextChunk(); byte[] chunk = await(nextChunk); * response.writeChunk(chunk); } * * @author <a href="http://www.scottphillips.com">Scott Phillips</a> * */ public interface ExportService { /** * Generate an export. * * Exports may take a substantial amount of time, and they are not stored on * the server. So it is imperative that the caller handle the ChunkStream * and send it to the user's browser. * * @param packager * The packager format. * @param filter * The filter to select submissions. * @return A stream of the export. */ public ChunkStream export(Packager packager, SearchFilter filter); }
32.404255
80
0.721602
08cc1b603d169f17d3051410df9cfe402540da7a
478
package com.milos.config; import com.milos.domain.util.Validator; public class ServerIp { private String value; public ServerIp(String value) { if (!Validator.validIP(value)) { throw new IllegalArgumentException("The given value '" + value + "' is not a valid IP"); } this.value = value; } public String getValue() { return value; } @Override public String toString() { return value; } }
19.12
100
0.598326
d41525e3885f9ecda5aa35cccee4034020334a2f
1,844
package remonsinnema.blog.scmlog.html; import java.io.PrintWriter; import java.io.Writer; import remonsinnema.blog.scmlog.log.ChangeHunk; import remonsinnema.blog.scmlog.log.Line; public class ToHtml { private static final String SPACE = "&nbsp;"; private static final String GREEN = "eaffea"; private static final String RED = "ffecec"; private static final String YELLOW = "fffacd"; private final ChangeHunk chunk; public ToHtml(ChangeHunk chunk) { this.chunk = chunk; } public void writeTo(Writer output) { PrintWriter writer = new PrintWriter(output); writer.println("<table style='border: hidden; border-collapse: collapse; font-size: 10pt;'>"); chunk.getLines().forEachOrdered(line -> writeLine(line, writer)); writer.println("</table>"); } private void writeLine(Line line, PrintWriter writer) { writer.print("<tr style='border: hidden;'><td style='font-family: Lucida Console; padding: 0;"); writeBackgroundColor(line, writer); writer.print("'>"); writeText(line.getType() + " ", writer); writeText(line.getText(), writer); writer.println("</td></tr>"); } private void writeBackgroundColor(Line line, PrintWriter writer) { switch (line.getType()) { case ADDITION: writeBackgroudColor(GREEN, writer); break; case DELETION: writeBackgroudColor(RED, writer); break; case COMMENT: writeBackgroudColor(YELLOW, writer); default: break; } } private void writeBackgroudColor(String color, PrintWriter writer) { writer.write(" background-color: #"); writer.write(color); writer.write(';'); } private void writeText(String text, PrintWriter writer) { writer.print(text.replace("&", "&amp;").replace(" ", SPACE).replace("<", "&lt;").replace(">", "&gt;")); } }
28.369231
107
0.667028
d820d3a4ca5eba53c213fb858789f2a85016b5e6
1,011
package com.cyfxr.basicdata.service; import com.cyfxr.basicdata.domain.DIC_ZD; import com.cyfxr.basicdata.domain.DIC_ZMK; import java.util.List; public interface BasicDataService { public List<DIC_ZMK> getZmk(String dbm); public DIC_ZMK getZmkById(String id); public int addZm(DIC_ZMK zmk); public int updateZm(DIC_ZMK zmk); public int deleteZm(String id); /** * 站段信息增删改查 */ public List<DIC_ZD> getZdInfo(String dbm); public DIC_ZD getZdByDbm(String dbm); public int addZdInfo(DIC_ZD zd); public int updateZdInfo(DIC_ZD zd); public int deleteZdInfo(String id); /** * 分类型车站字典信息加载 * 0集团所有站 1货运中心的站 2 公司的站 3全路的站 */ public List<DIC_ZMK> getZMZD(String lx, String dm); public List<DIC_ZMK> getCZ(String lx, String dm); /** * 检查站名、电报码是否唯一 * * @return */ public String checkZMUnique(String zm); public String checkDBMUnique(String dbm); }
20.22
56
0.636993
457f1b53e55671086205acd08d3571f66a3e309d
2,714
package com.mango.jtt.springSecurity; import java.io.IOException; import java.util.Collection; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SavedRequest; import com.mango.jtt.po.MangoUser; import com.mango.jtt.service.IUserService; /** * 登录授权成功后操作控制,如果是直接点击登录的情况下,根据授权权限跳转不同页面; 否则跳转到原请求页面 * * @author HHL * @date * */ public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { private Map<String, String> authDispatcherMap; private RequestCache requestCache = new HttpSessionRequestCache(); @Autowired private IUserService userService; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // 获取用户权限 Collection<? extends GrantedAuthority> authCollection = authentication .getAuthorities(); if (authCollection.isEmpty()) { return; } // 认证成功后,获取用户信息并添加到session中 UserDetails userDetails = (UserDetails) authentication.getPrincipal(); MangoUser user = userService.getUserByName(userDetails.getUsername()); request.getSession().setAttribute("user", user); String url = null; // 从别的请求页面跳转过来的情况,savedRequest不为空 SavedRequest savedRequest = requestCache.getRequest(request, response); if (savedRequest != null) { url = savedRequest.getRedirectUrl(); } // 直接点击登录页面,根据登录用户的权限跳转到不同的页面 if (url == null) { for (GrantedAuthority auth : authCollection) { url = authDispatcherMap.get(auth.getAuthority()); } getRedirectStrategy().sendRedirect(request, response, url); } super.onAuthenticationSuccess(request, response, authentication); } public RequestCache getRequestCache() { return requestCache; } public void setRequestCache(RequestCache requestCache) { this.requestCache = requestCache; } public Map<String, String> getAuthDispatcherMap() { return authDispatcherMap; } public void setAuthDispatcherMap(Map<String, String> authDispatcherMap) { this.authDispatcherMap = authDispatcherMap; } }
29.5
101
0.795505
62a934d8a0b039be4e5649d32bc15c76c014438e
9,399
/** * Copyright (c) 2016, Oliver Kleine, Institute of Telematics, University of Luebeck * All rights reserved * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * - Redistributions of source messageCode must retain the above copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * - Neither the name of the University of Luebeck nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package de.uzl.itm.ncoap.linkformat; import de.uzl.itm.ncoap.application.client.ClientCallback; import de.uzl.itm.ncoap.application.client.CoapClient; import de.uzl.itm.ncoap.application.linkformat.LinkParam; import de.uzl.itm.ncoap.application.linkformat.LinkValueList; import de.uzl.itm.ncoap.application.server.CoapServer; import de.uzl.itm.ncoap.application.server.resource.Webresource; import de.uzl.itm.ncoap.communication.AbstractCoapCommunicationTest; import de.uzl.itm.ncoap.endpoints.server.NotObservableTestWebresource; import de.uzl.itm.ncoap.endpoints.server.ObservableTestWebresource; import de.uzl.itm.ncoap.message.*; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.net.InetSocketAddress; import java.net.URI; import java.util.Collection; /** * Created by olli on 09.05.16. */ public class WellKnownCoreResourceTests extends AbstractCoapCommunicationTest { private static Logger LOG = Logger.getLogger(WellKnownCoreResourceTests.class.getName()); private static CoapServer server; private static Webresource[] webresources; private static CoapClient client; private static WkcCallback[] wkcCallbacks; private static URI wkcUri; @Override public void setupComponents() throws Exception { server = new CoapServer(); webresources = new Webresource[3]; webresources[0] = new NotObservableTestWebresource("/res1", "1", 60, 0, server.getExecutor()); webresources[1] = new NotObservableTestWebresource("/res2", "2", 60, 0, server.getExecutor()); webresources[2] = new ObservableTestWebresource("/res3", 3, 60, 0, server.getExecutor()); client = new CoapClient(); wkcCallbacks = new WkcCallback[7]; wkcCallbacks[0] = new WkcCallback(); wkcCallbacks[1] = new WkcCallback(); wkcCallbacks[2] = new WkcCallback(); wkcCallbacks[3] = new WkcCallback(); wkcCallbacks[4] = new WkcCallback(); wkcCallbacks[5] = new WkcCallback(); wkcCallbacks[6] = new WkcCallback(); wkcUri = new URI("coap", "localhost", "/.well-known/core", null); } @Override public void createTestScenario() throws Exception { InetSocketAddress serverSocket = new InetSocketAddress("localhost", server.getPort()); // register resources /res1, /res2, and /res3 and send a request to /.well-known/core after each registration for (int i = 0; i < 3; i++) { server.registerWebresource(webresources[i]); Thread.sleep(500); CoapRequest coapRequest = new CoapRequest(MessageType.CON, MessageCode.GET, wkcUri); client.sendCoapRequest(coapRequest, serverSocket, wkcCallbacks[i]); Thread.sleep(500); } // add link param to /res3 and send a request to to /.well-known/core { webresources[2].setLinkParam(LinkParam.createLinkParam(LinkParam.Key.CT, "30")); Thread.sleep(500); CoapRequest coapRequest = new CoapRequest(MessageType.CON, MessageCode.GET, wkcUri); client.sendCoapRequest(coapRequest, serverSocket, wkcCallbacks[3]); Thread.sleep(500); } // shutdown resources /res1, /res2, and /res3 and send a request to /.well-known/core after each shutdown for (int i = 0; i < 3; i++) { server.shutdownWebresource(webresources[i].getUriPath()); Thread.sleep(500); CoapRequest coapRequest = new CoapRequest(MessageType.CON, MessageCode.GET, wkcUri); client.sendCoapRequest(coapRequest, serverSocket, wkcCallbacks[i+4]); Thread.sleep(500); } Thread.sleep(1000); } @Override public void shutdownComponents() throws Exception { server.shutdown(); client.shutdown(); } @Override public void setupLogging() throws Exception { Logger.getLogger(WellKnownCoreResourceTests.class.getName()).setLevel(Level.DEBUG); } @Test public void testFirstResponseContainsTwoUriReferences() { assertEquals("Wrong number of resources", 2, wkcCallbacks[0].getNumberOfResources()); } @Test public void testSecondResponseContainsThreeUriReferences() { assertEquals("Wrong number of resources", 3, wkcCallbacks[1].getNumberOfResources()); } @Test public void testThirdResponseContainsFourUriReferences() { assertEquals("Wrong number of resources", 4, wkcCallbacks[2].getNumberOfResources()); } @Test public void testThirdResponseContainsObsParamForRes3() { Collection<LinkParam> linkParams = wkcCallbacks[2].getLinkValueList().getLinkParams("/res3"); boolean contained = false; for (LinkParam linkParam : linkParams) { if (linkParam.getKey() == LinkParam.Key.OBS) { contained = true; break; } } assertTrue("No link param 'obs' for /res3", contained); } @Test public void testThirdResponseDoesNotContainCtParamForRes3() { Collection<LinkParam> linkParams = wkcCallbacks[2].getLinkValueList().getLinkParams("/res3"); boolean contained = false; for (LinkParam linkParam : linkParams) { if (linkParam.getKey() == LinkParam.Key.CT) { contained = true; break; } } assertFalse("Unexpected link param 'ct' for /res3", contained); } @Test public void testFourthResponseContainsFourUriReferences() { assertEquals("Wrong number of resources", 4, wkcCallbacks[3].getNumberOfResources()); } @Test public void testFourthResponseContainsCt30ParamForRes3() { Collection<LinkParam> linkParams = wkcCallbacks[3].getLinkValueList().getLinkParams("/res3"); boolean contained = false; for (LinkParam linkParam : linkParams) { if (linkParam.getKey() == LinkParam.Key.CT && "30".equals(linkParam.getValue())) { contained = true; break; } } assertTrue("No link param 'ct=\"30\"' for /res3", contained); } @Test public void testFifthResponseContainsThreeUriReferences() { assertEquals("Wrong number of resources", 3, wkcCallbacks[4].getNumberOfResources()); } @Test public void testSixthResponseContainsTwoUriReferences() { assertEquals("Wrong number of resources", 2, wkcCallbacks[5].getNumberOfResources()); } @Test public void testSeventhResponseContainsOneUriReferences() { assertEquals("Wrong number of resources", 1, wkcCallbacks[6].getNumberOfResources()); } private class WkcCallback extends ClientCallback { private LinkValueList linkValueList2; //private int numberOfResources = 0; @Override public void processCoapResponse(CoapResponse coapResponse) { LinkValueList linkValueList = LinkValueList.decode( new String(coapResponse.getContentAsByteArray(), CoapMessage.CHARSET) ); LOG.debug("Received: " + linkValueList); this.linkValueList2 = linkValueList; //this.numberOfResources = linkValueList.getUriReferences().size(); } public int getNumberOfResources() { if (this.linkValueList2 == null) { return 0; } else { return this.linkValueList2.getUriReferences().size(); } } public LinkValueList getLinkValueList() { return this.linkValueList2; } } }
39.826271
125
0.681881
d67e4af7dda3410d21e1151fde8454b5826142e2
1,336
package com.uwork.happymoment.mvp.social.chat.model; import android.content.Context; import com.uwork.happymoment.BuildConfig; import com.uwork.happymoment.api.ApiService; import com.uwork.happymoment.mvp.social.chat.bean.NewFriendResponseBean; import com.uwork.happymoment.mvp.social.chat.contract.IGetNewFriendContract; import com.uwork.librx.mvp.model.IBaseModelImpl; import com.uwork.librx.rx.http.ApiServiceFactory; import com.uwork.librx.rx.http.CustomResourceSubscriber; import com.uwork.librx.rx.http.HttpResultFunc; import com.uwork.librx.rx.http.ServerResultFunc; import com.uwork.librx.rx.interfaces.OnModelCallBack; import io.reactivex.subscribers.ResourceSubscriber; /** * Created by jie on 2018/5/18. */ public class IGetNewFriendModel extends IBaseModelImpl implements IGetNewFriendContract.Model { public IGetNewFriendModel(Context context) { super(context); } @Override public ResourceSubscriber getNewFriend(OnModelCallBack<NewFriendResponseBean> callBack) { return startObservable(ApiServiceFactory.INSTANCE .create(mContext, BuildConfig.API_BASE_URL, ApiService.class) .getNewFriend() .map(new ServerResultFunc<>()) .onErrorResumeNext(new HttpResultFunc<>()), new CustomResourceSubscriber<>(callBack)); } }
36.108108
102
0.767216
d6b43bca9db696edca10460f37aa3681446fbbdf
300
package com.tokenplay.ue4.www.api; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = true) public class CurrencyResponse extends JSONResponse { @JsonProperty("Currency") final double currency; }
21.428571
53
0.796667
41abe8ce0a66067943e45f548ce20dd13dda537c
346
package me.irfen.algorithm.ch08; public class ArraySortTest { public static void main(String[] args) { int[] array1 = {1, -2, -4, 5, 9, -3, -8, 6}; int[] array2 = {1, -2, -4, 5, 9, -3, -8, 6}; int[] array3 = {1, -2, -4, 5, 9, -3, -8, 6}; ArraySort.sort1(array1); ArraySort.sort2(array2); ArraySort.sort3(array3); } }
24.714286
47
0.554913
9bd983d6a0d685c171152abd71cb7128b5716abd
517
package org.jcodings.specific; import static org.junit.Assert.assertEquals; import org.jcodings.specific.EmacsMuleEncoding; import org.junit.Test; public class TestEmacsMule { @Test public void testRightAdjustCharHeadAscii() { byte[] str = new byte[]{(byte)'a', (byte)'b', (byte)'c', (byte)',', (byte)'d', (byte)'e', (byte)'f'}; int t = EmacsMuleEncoding.INSTANCE.rightAdjustCharHead(str, 0, 3, 7); assertEquals("rightAdjustCharHead did not adjust properly", 3, t); } }
32.3125
109
0.667311
bf37d2f19042275d384cbf8265de25419b4b96b3
243
package com.lee.demo.service; import com.lee.demo.entity.UserInfo; /** * * @author min */ public interface UserInfoService { /** * findByUsername * @param username * @return */ UserInfo findByUsername(String username); }
13.5
43
0.666667
360bb89da6c9d96583352604b28f6b94b4368952
2,155
/** * * Copyright 2021 Modelware Solutions and CAE-LIST. * * 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.opencaesar.ecore2oml.preprocessors; import java.util.HashSet; import java.util.Set; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClassifier; import io.opencaesar.oml.Aspect; import io.opencaesar.oml.ScalarProperty; public class CollisionInfo { public Set<EAttribute> members = new HashSet<EAttribute>(); public Set<EClassifier> types = new HashSet<EClassifier>(); private EClassifier baseType = null; public ScalarProperty baseProperty = null; public Aspect baseConcept = null; private String name = ""; public CollisionInfo(String name) { this.name = name; } public String getName() { return name; } public boolean sameType() { return types.size() == 1; } public int size() { return members.size(); } public void add(EAttribute attr) { members.add(attr); types.add(attr.getEType()); } public void setName(String name) { this.name = name; } public void finish() { // deal with type if (!sameType()) { for (EClassifier type : types) { if (baseType == null) { baseType = type; } } } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(" Size = "); builder.append(size()); builder.append(" - One Type = " + sameType() + " : "); types.forEach(e -> { builder.append(e.getName() + " - "); }); builder.append("++ Memebrs : "); members.forEach(e -> { builder.append(e.getEContainingClass().getName() + " - "); }); return builder.toString(); } }
23.944444
75
0.683527
5b1e97ee350a6b12b31b5a031cbf0ab5aef0cd60
1,562
/* * 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 controle.academico.model; import java.io.Serializable; /** * * @author home */ public class Disciplina implements Serializable { private String codDisciplina; private String nome; private int carga; private int creditos; private String periodo; public Disciplina(String codDisciplina, String nome, int carga, int creditos, String periodo) { this.codDisciplina = codDisciplina; this.nome = nome; this.carga = carga; this.creditos = creditos; this.periodo = periodo; } public String getCodDisciplina() { return codDisciplina; } public void setCodDisciplina(String codDisciplina) { this.codDisciplina = codDisciplina; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public int getCarga() { return carga; } public void setCarga(int carga) { this.carga = carga; } public int getCreditos() { return creditos; } public void setCreditos(int creditos) { this.creditos = creditos; } public String getPeriodo() { return periodo; } public void setPeriodo(String periodo) { this.periodo = periodo; } }
21.694444
100
0.601793
6cf0e5a99ad59e6adddca7060c983d927085838c
3,744
/* * Copyright (c) 2015 EMC Corporation * All Rights Reserved */ package com.emc.storageos.computesystemcontroller.impl; import java.net.URI; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.emc.storageos.db.client.DbClient; import com.emc.storageos.db.client.model.ActionableEvent; import com.emc.storageos.db.client.model.Initiator; import com.emc.storageos.db.client.model.Operation.Status; import com.emc.storageos.db.client.util.NullColumnValueGetter; import com.emc.storageos.exceptions.DeviceControllerException; import com.emc.storageos.svcs.errorhandling.model.ServiceCoded; public class InitiatorCompleter extends ComputeSystemCompleter { private static final Logger _logger = LoggerFactory.getLogger(InitiatorCompleter.class); private static final long serialVersionUID = 1L; private final URI eventId; private final InitiatorOperation op; public enum InitiatorOperation { ADD, REMOVE; } public InitiatorCompleter(URI eventId, URI id, InitiatorOperation op, String opId) { super(Initiator.class, id, opId); this.op = op; this.eventId = eventId; } public InitiatorCompleter(URI eventId, List<URI> ids, InitiatorOperation op, String opId) { super(Initiator.class, ids, opId); this.op = op; this.eventId = eventId; } @Override protected void complete(DbClient dbClient, Status status, ServiceCoded coded) throws DeviceControllerException { super.complete(dbClient, status, coded); for (URI id : getIds()) { switch (status) { case error: dbClient.error(Initiator.class, this.getId(), getOpId(), coded); if (!NullColumnValueGetter.isNullURI(eventId)) { ActionableEvent event = dbClient.queryObject(ActionableEvent.class, eventId); if (event != null) { event.setEventStatus(ActionableEvent.Status.failed.name()); dbClient.updateObject(event); } } // If this completer is part of an add initiator operation and the operation // is NOT successful, we want to remove the initiator. The initiator should only // be removed if it is no longer in use. if (op == InitiatorOperation.ADD) { removeInitiator(id, dbClient); } break; default: dbClient.ready(Initiator.class, this.getId(), getOpId()); // If this completer is part of a remove initiator operation and the operation // is successful, we want to remove the initiator. The initiator should only // be removed if it is no longer in use. if (op == InitiatorOperation.REMOVE) { removeInitiator(id, dbClient); } } } } /** * Removes an initiator if it is no longer in use. * * @param initiatorUri the initiator to remove * @param dbClient the DB client */ private void removeInitiator(URI initiatorUri, DbClient dbClient) { if (!ComputeSystemHelper.isInitiatorInUse(dbClient, initiatorUri.toString()) && (op == InitiatorOperation.REMOVE || NullColumnValueGetter.isNullURI(eventId))) { Initiator initiator = dbClient.queryObject(Initiator.class, initiatorUri); dbClient.markForDeletion(initiator); _logger.info("Initiator marked for deletion: " + this.getId()); } } }
39.829787
116
0.620994
71577339b6ba9375f8c145836e20027e6de8d36d
4,268
/* * Copyright (c) 2011-2019, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.filter.binary.impl; import boofcv.concurrency.BoofConcurrency; import boofcv.struct.image.GrayS32; import boofcv.struct.image.GrayU8; /** * Implementation for all operations which are not seperated by inner and outer algorithms */ public class ImplBinaryImageOps_MT { public static void logicAnd(GrayU8 inputA , GrayU8 inputB , GrayU8 output ) { BoofConcurrency.loopFor(0, inputA.height, y -> { int indexA = inputA.startIndex + y*inputA.stride; int indexB = inputB.startIndex + y*inputB.stride; int indexOut = output.startIndex + y*output.stride; int end = indexA + inputA.width; for( ; indexA < end; indexA++,indexB++,indexOut++) { int valA = inputA.data[indexA]; output.data[indexOut] = valA == 1 && valA == inputB.data[indexB] ? (byte)1 : (byte)0; } }); } public static void logicOr(GrayU8 inputA , GrayU8 inputB , GrayU8 output ) { BoofConcurrency.loopFor(0, inputA.height, y -> { int indexA = inputA.startIndex + y*inputA.stride; int indexB = inputB.startIndex + y*inputB.stride; int indexOut = output.startIndex + y*output.stride; int end = indexA + inputA.width; for( ; indexA < end; indexA++,indexB++,indexOut++) { output.data[indexOut] = inputA.data[indexA] == 1 || 1 == inputB.data[indexB] ? (byte)1 : (byte)0; } }); } public static void logicXor(GrayU8 inputA , GrayU8 inputB , GrayU8 output ) { BoofConcurrency.loopFor(0, inputA.height, y -> { int indexA = inputA.startIndex + y*inputA.stride; int indexB = inputB.startIndex + y*inputB.stride; int indexOut = output.startIndex + y*output.stride; int end = indexA + inputA.width; for( ; indexA < end; indexA++,indexB++,indexOut++) { output.data[indexOut] = inputA.data[indexA] != inputB.data[indexB] ? (byte)1 : (byte)0; } }); } public static void invert(GrayU8 input , GrayU8 output) { BoofConcurrency.loopFor(0, input.height, y -> { int index = input.startIndex + y*input.stride; int indexOut = output.startIndex + y*output.stride; int end = index + input.width; for( ; index < end; index++,indexOut++) { output.data[indexOut] = input.data[index] == 0 ? (byte)1 : (byte)0; } }); } public static void relabel(GrayS32 input , int labels[] ) { BoofConcurrency.loopFor(0, input.height, y -> { int index = input.startIndex + y*input.stride; int end = index+input.width; for( ; index < end; index++ ) { int val = input.data[index]; input.data[index] = labels[val]; } }); } public static void labelToBinary(GrayS32 labelImage , GrayU8 binaryImage ) { BoofConcurrency.loopFor(0, labelImage.height, y -> { int indexIn = labelImage.startIndex + y*labelImage.stride; int indexOut = binaryImage.startIndex + y*binaryImage.stride; int end = indexIn + labelImage.width; for( ; indexIn < end; indexIn++, indexOut++ ) { if( 0 == labelImage.data[indexIn] ) { binaryImage.data[indexOut] = 0; } else { binaryImage.data[indexOut] = 1; } } }); } public static void labelToBinary(GrayS32 labelImage , GrayU8 binaryImage , boolean selectedBlobs[] ) { BoofConcurrency.loopFor(0, labelImage.height, y -> { int indexIn = labelImage.startIndex + y*labelImage.stride; int indexOut = binaryImage.startIndex + y*binaryImage.stride; int end = indexIn + labelImage.width; for( ; indexIn < end; indexIn++, indexOut++ ) { int val = labelImage.data[indexIn]; if( selectedBlobs[val] ) { binaryImage.data[indexOut] = 1; } else { binaryImage.data[indexOut] = 0; } } }); } }
31.382353
102
0.673149
36cf9903487c7658a2f4ab946748a0f60e2432f8
12,947
/* * Copyright (c) 2002-2012 Alibaba Group Holding Limited. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.citrus.turbine.util; import static com.alibaba.citrus.test.TestUtil.*; import static org.easymock.EasyMock.*; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.not; import static org.junit.Assert.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import com.alibaba.citrus.service.requestcontext.util.RequestContextUtil; import com.alibaba.citrus.turbine.util.CsrfToken.DefaultGenerator; import com.alibaba.citrus.util.StringUtil; import com.meterware.httpunit.WebRequest; import org.junit.Before; import org.junit.Test; public class CsrfTokenTests extends AbstractPullToolTests<CsrfToken> { private HttpServletRequest request; private HttpSession session; @Before public void initMock() { request = createMock(HttpServletRequest.class); session = createMock(HttpSession.class); expect(request.getSession()).andReturn(session).anyTimes(); expect(session.getId()).andReturn("aaa").anyTimes(); expect(session.getCreationTime()).andReturn(1234L).anyTimes(); } @Override protected String toolName() { return "csrfToken"; } @Test public void checkScope() throws Exception { assertSame(tool, getTool()); // global scope } @Test public void getConfiguration() throws Exception { tool = new CsrfToken(newRequest); // default values assertEquals(CsrfToken.DEFAULT_TOKEN_KEY, CsrfToken.getKey()); assertEquals(CsrfToken.DEFAULT_MAX_TOKENS, CsrfToken.getMaxTokens()); // thread context key CsrfToken.setContextTokenConfiguration(" testKey ", -1); assertEquals("testKey", CsrfToken.getKey()); assertEquals(CsrfToken.DEFAULT_MAX_TOKENS, CsrfToken.getMaxTokens()); CsrfToken.setContextTokenConfiguration(" testKey ", 2); assertEquals("testKey", CsrfToken.getKey()); assertEquals(2, CsrfToken.getMaxTokens()); // reset CsrfToken.resetContextTokenConfiguration(); assertEquals(CsrfToken.DEFAULT_TOKEN_KEY, CsrfToken.getKey()); assertEquals(CsrfToken.DEFAULT_MAX_TOKENS, CsrfToken.getMaxTokens()); } @Test public void generateLongLiveToken() throws InterruptedException { replay(session); DefaultGenerator g1 = new DefaultGenerator(); DefaultGenerator g2 = new DefaultGenerator(); String token1 = g1.generateLongLiveToken(session); String token2 = g2.generateLongLiveToken(session); assertEquals(token1, token2); assertNotNull(token1); } @Test public void getLongLiveTokenInSession() { replay(session); try { CsrfToken.getLongLiveTokenInSession(null); fail(); } catch (IllegalArgumentException e) { assertThat(e, exception("session")); } String token = CsrfToken.getLongLiveTokenInSession(session); assertNotNull(token); assertTrue(StringUtil.containsOnly(token, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray())); } @Test @Deprecated public void getLongLiveToken() throws Exception { // ----------------------- // 请求1,取得token String token = tool.getLongLiveToken(); assertNotNull(token); assertThat(tool.getHiddenField(true).toString(), containsString("<input name='_csrf_token' type='hidden' value='")); assertThat(tool.getLongLiveHiddenField().toString(), containsString(token)); assertEquals("_csrf_token", CsrfToken.getKey()); // 同一个请求,再次取得token assertEquals(token, tool.getLongLiveToken()); assertEquals(null, newRequest.getSession().getAttribute("_csrf_token")); commitRequestContext(); // ----------------------- // 请求2,再次取得token getInvocationContext("http://localhost/app1/1.html"); initRequestContext(); assertEquals(token, tool.getLongLiveToken()); assertThat(tool.getHiddenField(true).toString(), containsString("<input name='_csrf_token' type='hidden' value='")); assertThat(tool.getLongLiveHiddenField().toString(), containsString(token)); assertEquals("_csrf_token", CsrfToken.getKey()); // 和unique token混用 String token2 = tool.getUniqueToken(); assertNotNull(token2); assertThat(tool.getHiddenField(false).toString(), containsString("<input name='_csrf_token' type='hidden' value='")); assertThat(tool.getUniqueHiddenField().toString(), containsString(token2)); assertEquals("_csrf_token", CsrfToken.getKey()); assertEquals(token2, newRequest.getSession().getAttribute("_csrf_token")); commitRequestContext(); // ----------------------- // 请求3,取得token getInvocationContext("http://localhost/app1/1.html"); initRequestContext(); assertEquals(token, tool.getLongLiveToken()); assertThat(tool.getHiddenField(true).toString(), containsString("<input name='_csrf_token' type='hidden' value='")); assertThat(tool.getLongLiveHiddenField().toString(), containsString(token)); assertEquals("_csrf_token", CsrfToken.getKey()); assertEquals(token2, newRequest.getSession().getAttribute("_csrf_token")); // 让session过期,但保持sessionId final String sessionId = newRequest.getSession().getId(); newRequest.getSession().invalidate(); commitRequestContext(); // ----------------------- // 请求4,再次取得token assertEquals("", client.getCookieValue("JSESSIONID")); assertTrue(client.getCookieDetails("JSESSIONID").isExpired()); Thread.sleep(10); // 确保创建时间改变 getInvocationContext("http://localhost/app1/1.html", new WebRequestCallback() { public void process(WebRequest wr) { wr.setHeaderField("Cookie", "JSESSIONID=" + sessionId); } }); initRequestContext(); assertTrue(newRequest.getSession().isNew()); // 新session assertEquals(sessionId, newRequest.getSession().getId()); // id不变 String token3 = tool.getLongLiveToken(); assertFalse(token.equals(token3)); // token由id和时间共同生成,因此即使id不变,token也改变 assertNotNull(token3); assertThat(tool.getHiddenField(true).toString(), containsString("<input name='_csrf_token' type='hidden' value='")); assertThat(tool.getLongLiveHiddenField().toString(), containsString(token3)); assertEquals("_csrf_token", CsrfToken.getKey()); commitRequestContext(); } @Test public void getUniqueToken() throws Exception { // ----------------------- // 请求1,取得token String token = tool.getUniqueToken(); assertNotNull(token); assertThat(tool.getUniqueHiddenField().toString(), containsString("<input name='_csrf_token' type='hidden' value='")); assertThat(tool.getUniqueHiddenField().toString(), containsString(token)); assertEquals("_csrf_token", CsrfToken.getKey()); // 同一个请求,再次取得token assertEquals(token, tool.getUniqueToken()); assertEquals(token, newRequest.getSession().getAttribute("_csrf_token")); commitRequestContext(); // ----------------------- // 请求2,再次取得token getInvocationContext("http://localhost/app1/1.html"); initRequestContext(); String token2 = tool.getUniqueToken(); assertNotNull(token2); assertThat(tool.getUniqueHiddenField().toString(), containsString("<input name='_csrf_token' type='hidden' value='")); assertThat(tool.getUniqueHiddenField().toString(), containsString(token2)); assertEquals("_csrf_token", CsrfToken.getKey()); // 同一个请求,再次取得token assertEquals(token2, tool.getUniqueToken()); assertEquals(token + "/" + token2, newRequest.getSession().getAttribute("_csrf_token")); commitRequestContext(); // ----------------------- // 请求3-8,取得token String tokens = token + "/" + token2; for (int i = 2; i < 8; i++) { getInvocationContext("http://localhost/app1/1.html"); initRequestContext(); String token_i = tool.getUniqueToken(); assertNotNull(token_i); assertThat(tool.getUniqueHiddenField().toString(), containsString("<input name='_csrf_token' type='hidden' value='")); assertThat(tool.getUniqueHiddenField().toString(), containsString(token_i)); assertEquals("_csrf_token", CsrfToken.getKey()); // 同一个请求,再次取得token assertEquals(token_i, tool.getUniqueToken()); assertEquals(tokens += "/" + token_i, newRequest.getSession().getAttribute("_csrf_token")); commitRequestContext(); } // ----------------------- // 请求9,取得token,抛弃第一个token getInvocationContext("http://localhost/app1/1.html"); initRequestContext(); String token_9 = tool.getUniqueToken(); assertEquals(token_9, tool.getUniqueToken()); tokens += "/" + token_9; tokens = tokens.substring(tokens.indexOf("/") + 1); assertEquals(tokens, newRequest.getSession().getAttribute("_csrf_token")); commitRequestContext(); // ----------------------- // 请求10,取得token,设置maxTokens=3 getInvocationContext("http://localhost/app1/1.html"); initRequestContext(); CsrfToken.setContextTokenConfiguration(null, 3); String token_10 = tool.getUniqueToken(); assertEquals(token_10, tool.getUniqueToken()); tokens += "/" + token_10; tokens = tokens.substring(indexOf(tokens, "/", 6) + 1); assertEquals(tokens, newRequest.getSession().getAttribute("_csrf_token")); CsrfToken.resetContextTokenConfiguration(); commitRequestContext(); } private int indexOf(String str, String strToFind, int count) { int index = -1; for (int i = 0; i < count; i++) { index = str.indexOf(strToFind, index + 1); } return index; } @Test public void check_defaultKey_succ() { expect(request.getParameter("_csrf_token")).andReturn("any"); replay(request); assertTrue(CsrfToken.check(request)); verify(request); } @Test public void check_defaultKey_failed() { expect(request.getParameter("_csrf_token")).andReturn(null); replay(request); assertFalse(CsrfToken.check(request)); verify(request); } @Test public void check_contextKey_succ() { CsrfToken.setContextTokenConfiguration("contextKey", -1); expect(request.getParameter("contextKey")).andReturn("any"); replay(request); assertTrue(CsrfToken.check(request)); CsrfToken.resetContextTokenConfiguration(); verify(request); } @Test public void check_contextKey_failed() { CsrfToken.setContextTokenConfiguration("contextKey", -1); expect(request.getParameter("contextKey")).andReturn(null); replay(request); assertFalse(CsrfToken.check(request)); CsrfToken.resetContextTokenConfiguration(); verify(request); } @Test public void toString_() { // in request String token = tool.getUniqueToken(); assertNotNull(token); assertThat(tool.toString(), not(equalTo("<No thread-bound request>"))); // not in request requestContexts.commitRequestContext(RequestContextUtil.getRequestContext(newRequest)); assertEquals("<No thread-bound request>", tool.toString()); } }
35.568681
125
0.620066
4def4dc9ec66a8db82b6ad52367ef1e0dbae1ba5
1,182
package Lesson6.FullBST; import java.util.ArrayList; import java.util.Random; public class TestBST { public static void main(String[] args) { ArrayList<BST<Integer, Integer>> treeList = new ArrayList<>(); int treeCount = 100_000; int notBalanced = 0; for (int i = 1; i <= treeCount; i++) { treeList.add(new BST<>()); //System.out.println("Добавили " + i + " дерево в список"); } for (BST<Integer, Integer> aTreeList : treeList) { while (aTreeList.height() < 6) { aTreeList.put(new Random().nextInt(101) - new Random().nextInt(101), new Random().nextInt(101) - new Random().nextInt(101)); } if (!aTreeList.isBalanced()) { notBalanced++; } } for (BST<Integer, Integer> aTreeList : treeList) { //System.out.println("сбалансированное " + aTreeList.isBalanced() + ", высота " + aTreeList.height() + ", размер " + aTreeList.size()); } System.out.println(notBalanced); System.out.println("Процент несбалансированных " + (((notBalanced * 1.0) / treeCount) * 100.0)); } }
33.771429
147
0.563452
6dac9503d936ed2ea40f0e6f53f211a9484e258a
8,283
/* * Copyright 2017 Confluent Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package io.confluent.ksql.structured; import com.google.common.collect.ImmutableList; import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient; import io.confluent.ksql.GenericRow; import io.confluent.ksql.function.FunctionRegistry; import io.confluent.ksql.parser.tree.Expression; import io.confluent.ksql.util.KsqlConfig; import io.confluent.ksql.util.Pair; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.connect.data.Field; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.kstream.KGroupedTable; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.KTable; import org.apache.kafka.streams.kstream.Produced; import org.apache.kafka.streams.kstream.Serialized; import org.apache.kafka.streams.kstream.Windowed; import org.apache.kafka.streams.kstream.WindowedSerdes; // CHECKSTYLE_RULES.OFF: ClassDataAbstractionCoupling public class SchemaKTable extends SchemaKStream { // CHECKSTYLE_RULES.ON: ClassDataAbstractionCoupling private final KTable<?, GenericRow> ktable; private final boolean isWindowed; public SchemaKTable( final Schema schema, final KTable<?, GenericRow> ktable, final Field keyField, final List<SchemaKStream> sourceSchemaKStreams, final boolean isWindowed, final Type type, final KsqlConfig ksqlConfig, final FunctionRegistry functionRegistry, final SchemaRegistryClient schemaRegistryClient ) { super( schema, null, keyField, sourceSchemaKStreams, type, ksqlConfig, functionRegistry, schemaRegistryClient ); this.ktable = ktable; this.isWindowed = isWindowed; } @SuppressWarnings("unchecked") @Override public SchemaKTable into( final String kafkaTopicName, final Serde<GenericRow> topicValueSerDe, final Set<Integer> rowkeyIndexes ) { if (isWindowed) { final Serde<Windowed<String>> windowedSerde = WindowedSerdes.timeWindowedSerdeFrom(String.class); ((KTable<Windowed<String>, GenericRow>)ktable).toStream() .mapValues( row -> { if (row == null) { return null; } final List<Object> columns = new ArrayList<>(); for (int i = 0; i < row.getColumns().size(); i++) { if (!rowkeyIndexes.contains(i)) { columns.add(row.getColumns().get(i)); } } return new GenericRow(columns); } ).to(kafkaTopicName, Produced.with(windowedSerde, topicValueSerDe)); } else { ((KTable<String, GenericRow>)ktable).toStream() .mapValues(row -> { if (row == null) { return null; } final List<Object> columns = new ArrayList<>(); for (int i = 0; i < row.getColumns().size(); i++) { if (!rowkeyIndexes.contains(i)) { columns.add(row.getColumns().get(i)); } } return new GenericRow(columns); }).to(kafkaTopicName, Produced.with(Serdes.String(), topicValueSerDe)); } return this; } @Override public QueuedSchemaKStream toQueue() { return new QueuedSchemaKStream(this); } @SuppressWarnings("unchecked") @Override public SchemaKTable filter(final Expression filterExpression) { final SqlPredicate predicate = new SqlPredicate( filterExpression, schema, isWindowed, ksqlConfig, functionRegistry ); final KTable filteredKTable = ktable.filter(predicate.getPredicate()); return new SchemaKTable( schema, filteredKTable, keyField, Collections.singletonList(this), isWindowed, Type.FILTER, ksqlConfig, functionRegistry, schemaRegistryClient ); } @SuppressWarnings("unchecked") @Override public SchemaKTable select(final List<Pair<String, Expression>> expressionPairList) { final Selection selection = new Selection(expressionPairList, functionRegistry, this); return new SchemaKTable( selection.getSchema(), ktable.mapValues(selection.getSelectValueMapper()), selection.getKey(), Collections.singletonList(this), isWindowed, Type.PROJECT, ksqlConfig, functionRegistry, schemaRegistryClient ); } @SuppressWarnings("unchecked") // needs investigating @Override public KStream getKstream() { return ktable.toStream(); } public KTable getKtable() { return ktable; } public boolean isWindowed() { return isWindowed; } @Override public SchemaKGroupedStream groupBy( final Serde<String> keySerde, final Serde<GenericRow> valSerde, final List<Expression> groupByExpressions) { final String aggregateKeyName = keyNameForGroupBy(groupByExpressions); final List<Integer> newKeyIndexes = keyIndexesForGroupBy(getSchema(), groupByExpressions); final KGroupedTable kgroupedTable = ktable.filter((key, value) -> value != null).groupBy( (key, value) -> new KeyValue<>(buildGroupByKey(newKeyIndexes, value), value), Serialized.with(keySerde, valSerde)); final Field newKeyField = new Field(aggregateKeyName, -1, Schema.OPTIONAL_STRING_SCHEMA); return new SchemaKGroupedTable( schema, kgroupedTable, newKeyField, Collections.singletonList(this), ksqlConfig, functionRegistry, schemaRegistryClient); } @SuppressWarnings("unchecked") public SchemaKTable join( final SchemaKTable schemaKTable, final Schema joinSchema, final Field joinKey ) { final KTable joinedKTable = ktable.join( schemaKTable.getKtable(), new KsqlValueJoiner(this.getSchema(), schemaKTable.getSchema()) ); return new SchemaKTable( joinSchema, joinedKTable, joinKey, ImmutableList.of(this, schemaKTable), false, Type.JOIN, ksqlConfig, functionRegistry, schemaRegistryClient ); } @SuppressWarnings("unchecked") public SchemaKTable leftJoin( final SchemaKTable schemaKTable, final Schema joinSchema, final Field joinKey ) { final KTable joinedKTable = ktable.leftJoin( schemaKTable.getKtable(), new KsqlValueJoiner(this.getSchema(), schemaKTable.getSchema()) ); return new SchemaKTable( joinSchema, joinedKTable, joinKey, ImmutableList.of(this, schemaKTable), false, Type.JOIN, ksqlConfig, functionRegistry, schemaRegistryClient ); } @SuppressWarnings("unchecked") public SchemaKTable outerJoin( final SchemaKTable schemaKTable, final Schema joinSchema, final Field joinKey ) { final KTable joinedKTable = ktable.outerJoin( schemaKTable.getKtable(), new KsqlValueJoiner(this.getSchema(), schemaKTable.getSchema()) ); return new SchemaKTable( joinSchema, joinedKTable, joinKey, ImmutableList.of(this, schemaKTable), false, Type.JOIN, ksqlConfig, functionRegistry, schemaRegistryClient ); } }
29.476868
94
0.656767
ffa787011442c712c9d0d3ec0d149313424661ee
16,367
package com.noah.solutions.system.appcontroller; import com.alibaba.fastjson.JSONObject; import com.noah.solutions.common.BaseController; import com.noah.solutions.common.JsonResult; import com.noah.solutions.common.ProjectConfig; import com.noah.solutions.common.exception.CodeAndMsg; import com.noah.solutions.common.exception.CustormException; import com.noah.solutions.common.shiro.ShiroSessionManager; import com.noah.solutions.common.utils.StringUtil; import com.noah.solutions.common.utils.UserAgentGetter; import com.noah.solutions.system.entity.*; import com.noah.solutions.system.service.*; import io.swagger.annotations.*; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import static com.noah.solutions.common.exception.CodeAndMsg.*; @RestController @RequestMapping("/app/user") @Api(value = "用户api", tags = "user") public class AppUserController extends BaseController { /* * 图片命名格式 */ private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMddHHmmss"; @Autowired private UserService userService; @Autowired private LoginRecordService loginRecordService; @Autowired private ReceAddresService receAddresService; @Autowired private RechargeRecordService rechargeRecordService; @Autowired private StaffService staffService; @PostMapping("/userInfo.do") @ApiOperation(value = "獲取用戶信息", notes = "") public JSONObject getUserInfo(){ return SUCESS.getJSON(userService.getById(getUserId())); } /** * 註冊用戶 * @param phone * @param passWord * @param verificationCode * @return * @throws Exception */ @PostMapping("/registUser.do") @ApiOperation(value = " 註冊用戶") @ApiImplicitParams({ @ApiImplicitParam(name = "areaCode", value = "區號", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "phone", value = "電話號碼", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "nickname", value = "昵称", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "passWord", value = "密码", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "verificationCode", value = "验证码", required = true, dataType = "String", paramType = "query"), }) public JSONObject registUser(String areaCode,String phone,String passWord,String nickname,String verificationCode)throws Exception{ userService.registerUser(areaCode,phone,verificationCode,nickname,passWord); return SUCESS.getJSON(); } /** * 修改密码 * @param phone * @param passWord * @param verificationCode * @return * @throws Exception */ @PostMapping("/modifyPassword.do") @ApiOperation(value = " 修改密码(通過驗證碼)") @ApiImplicitParams({ @ApiImplicitParam(name = "phone", value = "電話號碼", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "passWord", value = "新密码", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "verificationCode", value = "验证码",required = true, dataType = "String", paramType = "query"), }) public JSONObject modifyPassword(@RequestParam("phone") String phone,@RequestParam("passWord")String passWord,@RequestParam("verificationCode")String verificationCode)throws Exception{ userService.modifyPassword(phone,verificationCode,passWord); return HANDLESUCESS.getJSON(); } /** * 修改密码 * @param oldPassWord * @param newPassWord * @return * @throws Exception */ @PostMapping("/modifyPasswordByOld.do") @ApiOperation(value = " 修改密码(通過舊密碼)") @ApiImplicitParams({ @ApiImplicitParam(name = "oldPassWord", value = "舊密碼", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "newPassWord", value = "新密码", required = true, dataType = "String", paramType = "query"), }) public JSONObject modifyPassword(@RequestParam("oldPassWord") String oldPassWord,@RequestParam("newPassWord")String newPassWord)throws Exception{ userService.modifyPassword(oldPassWord,newPassWord,getUser()); return HANDLESUCESS.getJSON(); } /** * 修改暱稱 * @param nickName * @return * @throws Exception */ @PostMapping("/modifyNick.do") @ApiOperation(value = " 修改暱稱") @ApiImplicitParams({ @ApiImplicitParam(name = "nickName", value = "昵称", required = true, dataType = "String", paramType = "query"), }) public JSONObject modifyNick(String nickName)throws Exception{ userService.modifyNick(nickName); return HANDLESUCESS.getJSON(); } /* * 上传头像图片 */ @PostMapping(value = "/uploadImage.do",consumes = "multipart/*",headers = "content-type=multipart/form-data") @ApiOperation(value = "上传头像") public JSONObject uploadImg(@ApiParam(value = "上传头像",required = true) MultipartFile uploadFile, HttpServletRequest request) throws Exception{ String fileName = null; try { if (uploadFile == null) { request.setCharacterEncoding("UTF-8"); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; //** 页面控件的文件流* *//* List<MultipartFile> multipartFiles = new ArrayList<MultipartFile>(); Map map =multipartRequest.getFileMap(); for (Iterator i = map.keySet().iterator(); i.hasNext();) { Object obj = i.next(); multipartFiles.add((MultipartFile) map.get(obj)); } uploadFile = multipartFiles.get(0); } fileName = uploadFile.getOriginalFilename(); if(fileName.contains("/")){ fileName = fileName.substring(fileName.lastIndexOf("/")); } DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO); fileName = df.format(new Date()) +"_@"+fileName.replace("&"," "); File file = new File(ProjectConfig.FILE_IMAGE_DIRECTORY , fileName); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (!file.exists()) { file.createNewFile(); } uploadFile.transferTo(file); } catch (Exception e) { System.out.println("上傳失敗"); System.out.println(e.getMessage()); throw new CustormException(CodeAndMsg.ERRORUPLOAD); } userService.savHeadPortrait(fileName); return new JSONObject().fluentPut("code", CodeAndMsg.SUCESSUPLOAD.getCode()) .fluentPut("msg", CodeAndMsg.SUCESSUPLOAD.getMsg()) .fluentPut("fileName",fileName) .fluentPut("url", "image/" +fileName); } /** * 獲取驗證碼 * @param phone * @return * @throws Exception */ @PostMapping("/getCaptcha.do") @ApiOperation(value = "獲取手機驗證碼") @ApiImplicitParams({ @ApiImplicitParam(name = "phone", value = "電話號碼", required = true, dataType = "String", paramType = "query"), }) public JSONObject getCaptcha(String phone)throws Exception{ userService.getCaptcha(phone); return HANDLESUCESS.getJSON(); } /** * 添加收货地址 */ @PostMapping("/addReceAddres.do") @ApiOperation(value = "添加收货地址") @ApiImplicitParams({ @ApiImplicitParam(name = "recName", value = "收件人", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "recPhone", value = "电话", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "placeId", value = "地区id(备注:与提货点id不能同时为空)", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "pickUpStationId", value = "提货点id(备注:与地区id不能同时为空)", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "recDetailedAddr", value = "详细地址", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "recRemarks", value = "备注", dataType = "String", paramType = "query"), }) public JSONObject addReceAddres(String recName, String recPhone,String placeId,String pickUpStationId,String recDetailedAddr,String recRemarks) { receAddresService.add(recName,recPhone,placeId,pickUpStationId,recDetailedAddr,recRemarks,getUserId()+""); return HANDLESUCESS.getJSON(); } /** * 修改收货地址 */ @PostMapping("/editReceAddres.do") @ApiOperation(value = "修改收货地址") @ApiImplicitParams({ @ApiImplicitParam(name = "recId", value = "地址id", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "recName", value = "收件人", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "recPhone", value = "电话", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "placeId", value = "地区id(备注:与提货点id不能同时为空)", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "pickUpStationId", value = "提货点id(备注:与地区id不能同时为空)", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "recDetailedAddr", value = "详细地址", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "recRemarks", value = "备注", dataType = "String", paramType = "query"), }) public JSONObject editReceAddres(String recId, String recName, String recPhone,String placeId,String pickUpStationId,String recDetailedAddr,String recRemarks)throws Exception { receAddresService.edit(new ReceAddres(recId,recName,recPhone,placeId,pickUpStationId,recDetailedAddr,recRemarks,getUserId()+"")); return EDITSUCESS.getJSON(); } /** * 修改收货地址 */ @PostMapping("/deleteReceAddres.do") @ApiOperation(value = "刪除收货地址") @ApiImplicitParams({ @ApiImplicitParam(name = "recId", value = "地址id", required = true, dataType = "String", paramType = "query"), }) public JSONObject deleteReceAddres(String recId) throws Exception { receAddresService.delete(recId,getUserId()+""); return HANDLESUCESS.getJSON(); } /** * 保存appId */ @PostMapping("/updateAppId.do") @ApiOperation(value = "保存appId") @ApiImplicitParams({ @ApiImplicitParam(name = "appId", value = "極光集成註冊id", required = true, dataType = "String", paramType = "query"), }) public JSONObject updateAppId(String appId) throws Exception { userService.updateAppId(appId); return HANDLESUCESS.getJSON(); } /** * 查询收货地址信息 */ @ApiOperation(value = "获取当前用户收货地址") @PostMapping("/getAllReceAddres.do") @ApiImplicitParams({ @ApiImplicitParam(name = "recMode", value = "地址类型(1.自提,2.送货上门.null.所有)", required = false, dataType = "int", paramType = "query"), @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "int", paramType = "query"), @ApiImplicitParam(name = "limit", value = "条数", required = true, dataType = "int", paramType = "query"), }) public JSONObject getAllReceAddres(Integer recMode,Integer page,Integer limit) { return SUCESS.getJSON(receAddresService.listPage(recMode,getUserId()+"", PageRequest.of(page-1,limit, Sort.by(Sort.Direction.DESC,"recUpdateTime")))); } /** * 登录 */ @PostMapping("/login") @ApiOperation(value = "用户登录") @ApiImplicitParams({ @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"), }) public JSONObject doLogin(String username, String password,HttpServletRequest request) { if (StringUtil.isBlank(username, password)) { return CodeAndMsg.PARAM_ERROR.getJSON(); } try { UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password); SecurityUtils.getSubject().login(usernamePasswordToken); User user = getUser(); user.setUserType(user.getType()); if(user.getUserType().equals(ProjectConfig.UserType.STAFF.getValue())){ user.setUserType(staffService.getUserType(user.getUserId())); } addLoginRecord(user.getUserId(), request); return USER_LOGIN_SUCESS.getJSON(user).fluentPut(ShiroSessionManager.getAUTHORIZATION(),SecurityUtils.getSubject().getSession().getId()); } catch (IncorrectCredentialsException ice) { return CodeAndMsg.USER_PASSWORDERROR.getJSON(); } catch (UnknownAccountException uae) { return CodeAndMsg.USER_NOTFINDUSERNAME.getJSON(); } catch (LockedAccountException e) { return CodeAndMsg.USER_BANNED.getJSON(); } catch (ExcessiveAttemptsException eae) { return CodeAndMsg.ERROR.getJSON(); } } @RequiresPermissions("member:addTokenRecord") @ApiOperation(value = "用户充值") @PostMapping("/addTokenRecord") @ApiImplicitParams({ @ApiImplicitParam(name = "rechargeAmount", value = "充值數量", required = true, dataType = "Integer", paramType = "query"), @ApiImplicitParam(name = "rechargeMode", value = "充值方式(1:轉賬,2:現金)", required = true, dataType = "Integer", paramType = "query"), @ApiImplicitParam(name = "userId", value = "用戶id", required = true, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "rechargeComments", value = "描述", required = false, dataType = "String", paramType = "query"), }) public JSONObject addRecord(@RequestParam("rechargeAmount") Integer rechargeAmount, @RequestParam("rechargeMode") Integer rechargeMode, @RequestParam("userId") String userId, @RequestParam(value = "rechargeComments",required = false)String rechargeComments) { RechargeRecord rechargeRecord = new RechargeRecord(Double.valueOf(rechargeAmount),Integer.valueOf(userId),getUserId(),rechargeMode,rechargeComments); rechargeRecordService.add(rechargeRecord); return SUCESS.getJSON(); } /** * 退出登錄 */ @PostMapping("/logout.do") @ApiOperation(value = "退出登錄") public JSONObject logout() throws Exception { loginOut(); return HANDLESUCESS.getJSON(); } // /** // * 领取包裹 // **/ // @RequiresPermissions("user:edit") // @ResponseBody // @RequestMapping("/pickUpParts.do") // public JsonResult pickUpParts(Integer userId) { // User byId = userService.getById(userId); // if (userService.updatePsw(userId, byId.getUsername(), "123456")) { // return JsonResult.ok("重置成功"); // } else { // return JsonResult.error("重置失败"); // } // } /** * 添加登录日志 */ private void addLoginRecord(Integer userId, HttpServletRequest request) { UserAgentGetter agentGetter = new UserAgentGetter(request); // 添加到登录日志 LoginRecord loginRecord = new LoginRecord(); loginRecord.setUserId(userId); loginRecord.setOsName(agentGetter.getOS()); loginRecord.setDevice(agentGetter.getDevice()); loginRecord.setBrowserType(agentGetter.getBrowser()); loginRecord.setIpAddress(agentGetter.getIpAddr()); loginRecordService.add(loginRecord); } }
43.298942
188
0.646484
237288e194270a14ecac98dc776d163471e6a41d
1,944
package ch.rasc.sbjooqflyway; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.time.LocalDate; import java.util.List; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import ch.rasc.sbjooqflyway.db.tables.pojos.Employee; public class Client { public static void main(String[] args) throws IOException, InterruptedException { var objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); var client = HttpClient.newHttpClient(); HttpResponse<String> response = client.send( HttpRequest.newBuilder().GET() .uri(URI.create("http://localhost:8080/listEmployees")).build(), BodyHandlers.ofString()); List<Employee> employees = objectMapper.readValue(response.body(), new TypeReference<List<Employee>>() { // nothing here }); System.out.println(employees); Employee newEmployee = new Employee(); newEmployee.setGender("M"); newEmployee.setFirstName("John"); newEmployee.setLastName("Doe"); newEmployee.setUserName("jdoe3"); newEmployee.setBirthDate(LocalDate.of(1986, 12, 11)); newEmployee.setHireDate(LocalDate.of(2014, 1, 1)); String json = objectMapper.writeValueAsString(newEmployee); response = client.send( HttpRequest.newBuilder().POST(BodyPublishers.ofString(json)) .header("Content-Type", "application/json") .uri(URI.create("http://localhost:8080/newEmployee")).build(), BodyHandlers.ofString()); Employee insertedEmployee = objectMapper.readValue(response.body(), Employee.class); System.out.println(insertedEmployee); } }
34.714286
89
0.701132
e770681b8a8b6c9345a1636dc4f6a3c18316f2da
747
package com.estafet.blockchain.demo.currency.converter.ms.service; import com.estafet.blockchain.demo.currency.converter.ms.model.ExchangeRate; import com.estafet.blockchain.demo.messages.lib.bank.BankPaymentBlockChainMessage; import com.estafet.blockchain.demo.messages.lib.bank.BankPaymentCurrencyConverterMessage; import java.util.List; public interface CurrencyConverterService { ExchangeRate getExchangeRate(String currency); List<ExchangeRate> getExchangeRates(); ExchangeRate newExchangeRate(ExchangeRate exchangeRate); ExchangeRate updateExchangeRate(ExchangeRate exchangeRate); void deleteAll(); BankPaymentBlockChainMessage convert(BankPaymentCurrencyConverterMessage bankToCurrencyConvMessage); }
31.125
102
0.828648
7c060ff8ac328cedbb31b015a65788cbd2026a52
8,999
// ============================================================================ // // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.sqlbuilder.actions.explain; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import net.sourceforge.squirrel_sql.fw.sql.SQLConnection; import org.eclipse.core.runtime.Preferences; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.talend.repository.model.RepositoryNode; import org.talend.sqlbuilder.IConstants; import org.talend.sqlbuilder.Messages; import org.talend.sqlbuilder.SqlBuilderPlugin; import org.talend.sqlbuilder.actions.AbstractEditorAction; import org.talend.sqlbuilder.actions.IResultDisplayer; import org.talend.sqlbuilder.dbstructure.SessionTreeNodeManager; import org.talend.sqlbuilder.sessiontree.model.SessionTreeNode; import org.talend.sqlbuilder.ui.editor.ISQLEditor; import org.talend.sqlbuilder.util.ImageUtil; import org.talend.sqlbuilder.util.QueryTokenizer; /** * DOC dev class global comment. Detailled comment <br/> * * $Id: talend-code-templates.xml 1 2006-09-29 17:06:40 +0000 (Fri, 29 Sep 2006) nrousseau $ * */ public class OracleExplainPlanAction extends AbstractEditorAction { private ImageDescriptor img = ImageUtil.getDescriptor("Images.Explain"); //$NON-NLS-1$ static String createPlanTableScript = "CREATE TABLE PLAN_TABLE (" //$NON-NLS-1$ + " STATEMENT_ID VARCHAR2(30)," + " TIMESTAMP DATE," //$NON-NLS-1$ //$NON-NLS-2$ + " REMARKS VARCHAR2(80)," + " OPERATION VARCHAR2(30)," //$NON-NLS-1$ //$NON-NLS-2$ + " OPTIONS VARCHAR2(30)," + " OBJECT_NODE VARCHAR2(128)," //$NON-NLS-1$ //$NON-NLS-2$ + " OBJECT_OWNER VARCHAR2(30)," + " OBJECT_NAME VARCHAR2(30)," //$NON-NLS-1$ //$NON-NLS-2$ + " OBJECT_INSTANCE NUMBER(38)," + " OBJECT_TYPE VARCHAR2(30)," //$NON-NLS-1$ //$NON-NLS-2$ + " OPTIMIZER VARCHAR2(255)," + " SEARCH_COLUMNS NUMBER," //$NON-NLS-1$ //$NON-NLS-2$ + " ID NUMBER(38)," + " PARENT_ID NUMBER(38)," //$NON-NLS-1$ //$NON-NLS-2$ + " POSITION NUMBER(38)," + " COST NUMBER(38)," //$NON-NLS-1$ //$NON-NLS-2$ + " CARDINALITY NUMBER(38)," + " BYTES NUMBER(38)," //$NON-NLS-1$ //$NON-NLS-2$ + " OTHER_TAG VARCHAR2(255)," + " PARTITION_START VARCHAR2(255)," //$NON-NLS-1$ //$NON-NLS-2$ + " PARTITION_STOP VARCHAR2(255)," + " PARTITION_ID NUMBER(38)," //$NON-NLS-1$ //$NON-NLS-2$ + " OTHER LONG," + " DISTRIBUTION VARCHAR2(30)" + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ private ISQLEditor editor; private IResultDisplayer resultDisplayer; /** * DOC dev ExplainPlanAction constructor comment. */ public OracleExplainPlanAction(IResultDisplayer resultDisplayer, ISQLEditor editor) { super(); this.editor = editor; this.resultDisplayer = resultDisplayer; this.setImageDescriptor(img); } /* * (non-Javadoc) * * @see org.talend.sqlbuilder.actions.AbstractEditorAction#getText() */ @Override public String getText() { return Messages.getString("oracle.editor.actions.explain"); //$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.talend.sqlbuilder.actions.AbstractEditorAction#run() */ @SuppressWarnings("unchecked")//$NON-NLS-1$ @Override public void run() { RepositoryNode node = editor.getRepositoryNode(); SessionTreeNodeManager nodeManager = new SessionTreeNodeManager(); SessionTreeNode runNode = null; try { runNode = nodeManager.getSessionTreeNode(node, editor.getDialog().getSelectedContext()); } catch (Exception e) { MessageDialog.openError(null, Messages.getString("AbstractSQLExecution.Executing.Error"), e.getMessage()); //$NON-NLS-1$ SqlBuilderPlugin.log(Messages.getString("OracleExplainPlanAction.logMessage1"), e); //$NON-NLS-1$ return; } Preferences prefs = SqlBuilderPlugin.getDefault().getPluginPreferences(); String queryDelimiter = prefs.getString(IConstants.QUERY_DELIMITER); String alternateDelimiter = prefs.getString(IConstants.ALTERNATE_DELIMITER); String commentDelimiter = prefs.getString(IConstants.COMMENT_DELIMITER); QueryTokenizer qt = new QueryTokenizer(getSQLToBeExecuted(), queryDelimiter, alternateDelimiter, commentDelimiter); List queryStrings = new ArrayList(); while (qt.hasQuery()) { final String querySql = qt.nextQuery(); // ignore commented lines. if (!querySql.startsWith("--")) { //$NON-NLS-1$ queryStrings.add(querySql); } } // check if we can run explain plans try { Statement st = runNode.getInteractiveConnection().createStatement(); boolean createPlanTable = false; boolean notFoundTable = true; try { ResultSet rs = st.executeQuery("select statement_id from plan_table"); //$NON-NLS-1$ notFoundTable = false; rs.close(); } catch (Throwable e) { createPlanTable = MessageDialog.openQuestion(null, Messages.getString("oracle.editor.actions.explain.notFound.Title"), //$NON-NLS-1$ Messages.getString("oracle.editor.actions.explain.notFound")); //$NON-NLS-1$ } finally { try { st.close(); } catch (Throwable e) { SqlBuilderPlugin.log(Messages.getString("OracleExplainPlanAction.logMessage2"), e); //$NON-NLS-1$ } } if (notFoundTable && !createPlanTable) { return; } if (notFoundTable && createPlanTable) { SQLConnection conn = runNode.getInteractiveConnection(); st = conn.createStatement(); try { st.execute(createPlanTableScript); if (!conn.getAutoCommit()) { conn.commit(); } } catch (Throwable e) { SqlBuilderPlugin.log(Messages.getString("OracleExplainPlanAction.logMessage2"), e); //$NON-NLS-1$ MessageDialog.openError(null, Messages.getString("oracle.editor.actions.explain.createError.Title"), //$NON-NLS-1$ Messages.getString("oracle.editor.actions.explain.createError")); //$NON-NLS-1$ try { st.close(); } catch (Throwable e1) { SqlBuilderPlugin.log(Messages.getString("OracleExplainPlanAction.logMessage3"), e1); //$NON-NLS-1$ } return; } try { st.close(); } catch (Throwable e) { SqlBuilderPlugin.log(Messages.getString("OracleExplainPlanAction.logMessage3"), e); //$NON-NLS-1$ } } } catch (Exception e) { SqlBuilderPlugin.log(Messages.getString("OracleExplainPlanAction.logMessage4"), e); //$NON-NLS-1$ } // execute explain plan for all statements try { while (!queryStrings.isEmpty()) { String querySql = (String) queryStrings.remove(0); if (querySql != null) { resultDisplayer.addSQLExecution(new OracleExplainPlanExecution(querySql, runNode)); } } } catch (Exception e) { SqlBuilderPlugin.log(Messages.getString("OracleExplainPlanAction.logMessage5"), e); //$NON-NLS-1$ } } /** * Gets sql for executing. * * @return string */ public String getSQLToBeExecuted() { String sql = editor.getSQLToBeExecuted(); return sql; } }
43.684466
155
0.559618
4b76093e37524c0b325bcdfb48393d2156848d13
14,222
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.solutions.autotokenize.pipeline; import static com.google.common.truth.Truth.assertThat; import com.google.cloud.solutions.autotokenize.AutoTokenizeMessages.FlatRecord; import com.google.cloud.solutions.autotokenize.testing.TestResourceLoader; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.privacy.dlp.v2.Value; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public final class RandomColumnarSamplerTest { @Rule public TestPipeline testPipeline = TestPipeline.create(); private final String testCondition; private final int sampleSize; private final ImmutableList<FlatRecord> flatRecords; private final ImmutableMap<String, ImmutableSet<Value>> expectedSplits; public RandomColumnarSamplerTest( String testCondition, int sampleSize, ImmutableList<FlatRecord> flatRecords, ImmutableMap<String, ImmutableSet<Value>> expectedSplits) { this.testCondition = testCondition; this.sampleSize = sampleSize; this.flatRecords = flatRecords; this.expectedSplits = expectedSplits; } @Test public void expand_valid() { PCollection<KV<String, Iterable<Value>>> sampledColumns = testPipeline.apply(Create.of(flatRecords)).apply(RandomColumnarSampler.any(sampleSize)); PAssert.that(sampledColumns).satisfies(new ColumnValuesChecker(expectedSplits, sampleSize)); testPipeline.run(); } private static class ColumnValuesChecker implements SerializableFunction<Iterable<KV<String, Iterable<Value>>>, Void> { private final ImmutableMap<String, ImmutableSet<Value>> expectedValues; private final int maxSamples; public ColumnValuesChecker( ImmutableMap<String, ImmutableSet<Value>> expectedValues, int maxSamples) { this.expectedValues = expectedValues; this.maxSamples = maxSamples; } @Override public Void apply(Iterable<KV<String, Iterable<Value>>> columnValuesPcollection) { columnValuesPcollection.forEach( column -> { ImmutableSet<Value> values = ImmutableSet.copyOf(column.getValue()); assertThat(values.size()).isAtMost(maxSamples); assertThat(Sets.difference(values, expectedValues.get(column.getKey()))).isEmpty(); }); return null; } } @Parameters(name = "{0}") public static ImmutableList<Object[]> testParameters() { return ImmutableList.<Object[]>builder() .add( new Object[] { /*testCondition=*/ "ArrayElementsAreMerged", /*sampleSize=*/ 100, /*flatRecords=*/ ImmutableList.of( FlatRecord.newBuilder() .putFlatKeySchema("$.cc[0]", "$.cc") .putFlatKeySchema("$.cc[1]", "$.cc") .putFlatKeySchema("$.cc[2]", "$.cc") .putValues("$.cc[0]", Value.newBuilder().setIntegerValue(1234567890L).build()) .putValues("$.cc[1]", Value.newBuilder().setIntegerValue(9876543210L).build()) .putValues( "$.cc[2]", Value.newBuilder().setIntegerValue(1212343456567878L).build()) .build()), /*expectedSplits=*/ ImmutableMap.<String, ImmutableSet<Value>>builder() .put( "$.cc", ImmutableSet.of( Value.newBuilder().setIntegerValue(1234567890L).build(), Value.newBuilder().setIntegerValue(9876543210L).build(), Value.newBuilder().setIntegerValue(1212343456567878L).build())) .build() }) .add( new Object[] { /*testCondition=*/ "EmptyEmailFieldRemoved", /*sampleSize=*/ 100, /*flatRecords=*/ ImmutableList.of( FlatRecord.newBuilder() .putFlatKeySchema("$.cc[0]", "$.cc") .putFlatKeySchema("$.cc[1]", "$.cc") .putFlatKeySchema("$.email", "$.email") .putValues("$.cc[0]", Value.newBuilder().setIntegerValue(1234567890L).build()) .putValues("$.cc[1]", Value.newBuilder().setIntegerValue(9876543210L).build()) .putValues("$.email", Value.getDefaultInstance()) .build()), /*expectedSplits=*/ ImmutableMap.<String, ImmutableSet<Value>>builder() .put( "$.cc", ImmutableSet.of( Value.newBuilder().setIntegerValue(1234567890L).build(), Value.newBuilder().setIntegerValue(9876543210L).build())) .build() }) .add( new Object[] { /*testCondition=*/ "ElementsReduced", /*sampleSize=*/ 5, /*flatRecords=*/ ImmutableList.of( FlatRecord.newBuilder() .putFlatKeySchema("$.cc[0]", "$.cc") .putFlatKeySchema("$.cc[1]", "$.cc") .putFlatKeySchema("$.cc[2]", "$.cc") .putFlatKeySchema("$.cc[3]", "$.cc") .putFlatKeySchema("$.cc[4]", "$.cc") .putFlatKeySchema("$.cc[5]", "$.cc") .putFlatKeySchema("$.cc[6]", "$.cc") .putFlatKeySchema("$.cc[7]", "$.cc") .putFlatKeySchema("$.cc[8]", "$.cc") .putFlatKeySchema("$.cc[9]", "$.cc") .putValues("$.cc[0]", Value.newBuilder().setIntegerValue(123).build()) .putValues("$.cc[1]", Value.newBuilder().setIntegerValue(456).build()) .putValues("$.cc[2]", Value.newBuilder().setIntegerValue(789).build()) .putValues("$.cc[3]", Value.newBuilder().setIntegerValue(987).build()) .putValues("$.cc[4]", Value.newBuilder().setIntegerValue(654).build()) .putValues("$.cc[5]", Value.newBuilder().setIntegerValue(321).build()) .putValues("$.cc[6]", Value.newBuilder().setIntegerValue(1234).build()) .putValues("$.cc[7]", Value.newBuilder().setIntegerValue(5678).build()) .putValues("$.cc[8]", Value.newBuilder().setIntegerValue(91011).build()) .putValues("$.cc[9]", Value.newBuilder().setIntegerValue(111213).build()) .build()), /*expectedSplits=*/ ImmutableMap.<String, ImmutableSet<Value>>builder() .put( "$.cc", ImmutableSet.of( Value.newBuilder().setIntegerValue(123).build(), Value.newBuilder().setIntegerValue(456).build(), Value.newBuilder().setIntegerValue(789).build(), Value.newBuilder().setIntegerValue(987).build(), Value.newBuilder().setIntegerValue(654).build(), Value.newBuilder().setIntegerValue(321).build(), Value.newBuilder().setIntegerValue(1234).build(), Value.newBuilder().setIntegerValue(5678).build(), Value.newBuilder().setIntegerValue(91011).build(), Value.newBuilder().setIntegerValue(111213).build())) .build() }) .add( new Object[] { /*testCondition=*/ "numItemsLessThanSampleSize", /*sampleSize=*/ 100, /*flatRecords=*/ TestResourceLoader.classPath() .forProto(FlatRecord.class) .loadAllTextFiles( ImmutableList.of( "flat_records/userdata_avro/record-1.textpb", "flat_records/userdata_avro/record-2.textpb", "flat_records/userdata_avro/record-cc-null.textpb")), /*expectedSplits=*/ ImmutableMap.<String, ImmutableSet<Value>>builder() .put( "$.kylosample.ip_address", ImmutableSet.of( Value.newBuilder().setStringValue("1.197.201.2").build(), Value.newBuilder().setStringValue("7.161.136.94").build(), Value.newBuilder().setStringValue("218.111.175.34").build())) .put( "$.kylosample.comments", ImmutableSet.of( Value.newBuilder().setStringValue("1E+02").build(), Value.newBuilder().setStringValue("").build(), Value.newBuilder().setStringValue("").build())) .put( "$.kylosample.email", ImmutableSet.of( Value.newBuilder().setStringValue("afreeman1@is.gd").build(), Value.newBuilder().setStringValue("ajordan0@com.com").build(), Value.newBuilder().setStringValue("emorgan2@altervista.org").build())) .put( "$.kylosample.birthdate", ImmutableSet.of( Value.newBuilder().setStringValue("1/16/1968").build(), Value.newBuilder().setStringValue("3/8/1971").build(), Value.newBuilder().setStringValue("2/1/1960").build())) .put( "$.kylosample.title", ImmutableSet.of( Value.newBuilder().setStringValue("Accountant IV").build(), Value.newBuilder().setStringValue("Internal Auditor").build(), Value.newBuilder().setStringValue("Structural Engineer").build())) .put( "$.kylosample.gender", ImmutableSet.of( Value.newBuilder().setStringValue("Female").build(), Value.newBuilder().setStringValue("Male").build(), Value.newBuilder().setStringValue("Female").build())) .put( "$.kylosample.registration_dttm", ImmutableSet.of( Value.newBuilder().setStringValue("2016-02-03T07:55:29Z").build(), Value.newBuilder().setStringValue("2016-02-03T01:09:31Z").build(), Value.newBuilder().setStringValue("2016-02-03T17:04:03Z").build())) .put( "$.kylosample.cc", ImmutableSet.of( Value.newBuilder().setIntegerValue(6759521864920116L).build(), Value.newBuilder().setIntegerValue(6767119071901597L).build())) .put( "$.kylosample.salary", ImmutableSet.of( Value.newBuilder().setFloatValue(49756.53).build(), Value.newBuilder().setFloatValue(150280.17).build(), Value.newBuilder().setFloatValue(144972.51).build())) .put( "$.kylosample.first_name", ImmutableSet.of( Value.newBuilder().setStringValue("Amanda").build(), Value.newBuilder().setStringValue("Evelyn").build(), Value.newBuilder().setStringValue("Albert").build())) .put( "$.kylosample.last_name", ImmutableSet.of( Value.newBuilder().setStringValue("Freeman").build(), Value.newBuilder().setStringValue("Jordan").build(), Value.newBuilder().setStringValue("Morgan").build())) .put( "$.kylosample.country", ImmutableSet.of( Value.newBuilder().setStringValue("Indonesia").build(), Value.newBuilder().setStringValue("Canada").build(), Value.newBuilder().setStringValue("Russia").build())) .put( "$.kylosample.id", ImmutableSet.of( Value.newBuilder().setIntegerValue(1).build(), Value.newBuilder().setIntegerValue(2).build(), Value.newBuilder().setIntegerValue(3).build())) .build() }) // .add(new Object[] { // /*testCondition=*/ "test1", // /*sampleSize=*/ 100, // /*flatRecordTextFiles=*/ null, // /*expectedSplits=*/ ImmutableMap.<String, Iterable<Value>>builder() // .build() // }) .build(); } }
49.381944
100
0.535508
3b78fe206d272717a60e71c4763ff58c4ca22499
3,477
package org.apache.jetspeed.services.jsp.tags; /* * Copyright 2000-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Date; import java.text.DateFormat; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; // Turbine Classes import org.apache.turbine.util.RunData; import org.apache.turbine.services.jsp.JspService; // Jetspeed classes import org.apache.jetspeed.services.logging.JetspeedLogFactoryService; import org.apache.jetspeed.services.logging.JetspeedLogger; /** * Supporting class for the info tag. * Sends the screens ecs element's content to the output stream. * * @author <a href="mailto:ingo@raleigh.ibm.com">Ingo Schuster</a> * @author <a href="mailto:paulsp@apache.org">Paul Spencer</a> */ public class InfoTag extends TagSupport { /** * Static initialization of the logger for this class */ private static final JetspeedLogger logger = JetspeedLogFactoryService.getLogger(InfoTag.class.getName()); /** * requestedInfo parameter defines type of Info that is being requested */ private String requestedInfo; /** * The setter for requestedInfo parameter */ public void setRequestedInfo(String requestedInfo) { this.requestedInfo = requestedInfo; } public int doStartTag() throws JspException { RunData data = (RunData)pageContext.getAttribute(JspService.RUNDATA, PageContext.REQUEST_SCOPE); try { String result = "jetspeed-InfoTag: unknown parameter >" + requestedInfo +"<"; /* Server Date */ if (requestedInfo.equalsIgnoreCase("ServerDate")) { result = DateFormat.getDateTimeInstance().format( new Date()); } /* User Name */ if (requestedInfo.equalsIgnoreCase("UserName")) { result = data.getUser().getUserName(); } /* First Name */ if (requestedInfo.equalsIgnoreCase("FirstName")) { result = data.getUser().getFirstName(); } /* Last Name */ if (requestedInfo.equalsIgnoreCase("LastName")) { result = data.getUser().getLastName(); } /* EMail */ if (requestedInfo.equalsIgnoreCase("EMail")) { result = data.getUser().getEmail(); } pageContext.getOut().print(result); } catch (Exception e) { String message = "Error processing info-tag, parameter: "+ requestedInfo; logger.error(message, e); try { data.getOut().print("Error processing info-tag, parameter: "+ requestedInfo); } catch(java.io.IOException ioe) {} } return EVAL_BODY_INCLUDE; } }
31.899083
110
0.631291
ea64403f3c78ccf8bec8dd73d44088a4c6f2ef5b
9,699
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.server.wifi.nan; import android.net.wifi.nan.IWifiNanSessionListener; import android.net.wifi.nan.PublishData; import android.net.wifi.nan.PublishSettings; import android.net.wifi.nan.SubscribeData; import android.net.wifi.nan.SubscribeSettings; import android.net.wifi.nan.WifiNanSessionListener; import android.os.RemoteException; import android.util.Log; import android.util.SparseArray; import libcore.util.HexEncoding; import java.io.FileDescriptor; import java.io.PrintWriter; public class WifiNanSessionState { private static final String TAG = "WifiNanSessionState"; private static final boolean DBG = false; private static final boolean VDBG = false; // STOPSHIP if true private final SparseArray<String> mMacByRequestorInstanceId = new SparseArray<>(); private int mSessionId; private IWifiNanSessionListener mListener; private int mEvents; private boolean mPubSubIdValid = false; private int mPubSubId; private static final int SESSION_TYPE_NOT_INIT = 0; private static final int SESSION_TYPE_PUBLISH = 1; private static final int SESSION_TYPE_SUBSCRIBE = 2; private int mSessionType = SESSION_TYPE_NOT_INIT; public WifiNanSessionState(int sessionId, IWifiNanSessionListener listener, int events) { mSessionId = sessionId; mListener = listener; mEvents = events; } public void destroy() { stop(WifiNanStateManager.getInstance().createNextTransactionId()); if (mPubSubIdValid) { mMacByRequestorInstanceId.clear(); mListener = null; mPubSubIdValid = false; } } public int getSessionId() { return mSessionId; } public boolean isPubSubIdSession(int pubSubId) { return mPubSubIdValid && mPubSubId == pubSubId; } public void publish(short transactionId, PublishData data, PublishSettings settings) { if (mSessionType == SESSION_TYPE_SUBSCRIBE) { throw new IllegalStateException("A SUBSCRIBE session is being used for publish"); } mSessionType = SESSION_TYPE_PUBLISH; WifiNanNative.getInstance().publish(transactionId, mPubSubIdValid ? mPubSubId : 0, data, settings); } public void subscribe(short transactionId, SubscribeData data, SubscribeSettings settings) { if (mSessionType == SESSION_TYPE_PUBLISH) { throw new IllegalStateException("A PUBLISH session is being used for publish"); } mSessionType = SESSION_TYPE_SUBSCRIBE; WifiNanNative.getInstance().subscribe(transactionId, mPubSubIdValid ? mPubSubId : 0, data, settings); } public void sendMessage(short transactionId, int peerId, byte[] message, int messageLength, int messageId) { if (!mPubSubIdValid) { Log.e(TAG, "sendMessage: attempting to send a message on a non-live session " + "(no successful publish or subscribe"); onMessageSendFail(messageId, WifiNanSessionListener.FAIL_REASON_NO_MATCH_SESSION); return; } String peerMacStr = mMacByRequestorInstanceId.get(peerId); if (peerMacStr == null) { Log.e(TAG, "sendMessage: attempting to send a message to an address which didn't " + "match/contact us"); onMessageSendFail(messageId, WifiNanSessionListener.FAIL_REASON_NO_MATCH_SESSION); return; } byte[] peerMac = HexEncoding.decode(peerMacStr.toCharArray(), false); WifiNanNative.getInstance().sendMessage(transactionId, mPubSubId, peerId, peerMac, message, messageLength); } public void stop(short transactionId) { if (!mPubSubIdValid || mSessionType == SESSION_TYPE_NOT_INIT) { Log.e(TAG, "sendMessage: attempting to stop pub/sub on a non-live session (no " + "successful publish or subscribe"); return; } if (mSessionType == SESSION_TYPE_PUBLISH) { WifiNanNative.getInstance().stopPublish(transactionId, mPubSubId); } else if (mSessionType == SESSION_TYPE_SUBSCRIBE) { WifiNanNative.getInstance().stopSubscribe(transactionId, mPubSubId); } } public void onPublishSuccess(int publishId) { mPubSubId = publishId; mPubSubIdValid = true; } public void onPublishFail(int status) { mPubSubIdValid = false; try { if (mListener != null && (mEvents & WifiNanSessionListener.LISTEN_PUBLISH_FAIL) != 0) { mListener.onPublishFail(status); } } catch (RemoteException e) { Log.w(TAG, "onPublishFail: RemoteException (FYI): " + e); } } public void onPublishTerminated(int status) { mPubSubIdValid = false; try { if (mListener != null && (mEvents & WifiNanSessionListener.LISTEN_PUBLISH_TERMINATED) != 0) { mListener.onPublishTerminated(status); } } catch (RemoteException e) { Log.w(TAG, "onPublishTerminated: RemoteException (FYI): " + e); } } public void onSubscribeSuccess(int subscribeId) { mPubSubId = subscribeId; mPubSubIdValid = true; } public void onSubscribeFail(int status) { mPubSubIdValid = false; try { if (mListener != null && (mEvents & WifiNanSessionListener.LISTEN_SUBSCRIBE_FAIL) != 0) { mListener.onSubscribeFail(status); } } catch (RemoteException e) { Log.w(TAG, "onSubscribeFail: RemoteException (FYI): " + e); } } public void onSubscribeTerminated(int status) { mPubSubIdValid = false; try { if (mListener != null && (mEvents & WifiNanSessionListener.LISTEN_SUBSCRIBE_TERMINATED) != 0) { mListener.onSubscribeTerminated(status); } } catch (RemoteException e) { Log.w(TAG, "onSubscribeTerminated: RemoteException (FYI): " + e); } } public void onMessageSendSuccess(int messageId) { try { if (mListener != null && (mEvents & WifiNanSessionListener.LISTEN_MESSAGE_SEND_SUCCESS) != 0) { mListener.onMessageSendSuccess(messageId); } } catch (RemoteException e) { Log.w(TAG, "onMessageSendSuccess: RemoteException (FYI): " + e); } } public void onMessageSendFail(int messageId, int status) { try { if (mListener != null && (mEvents & WifiNanSessionListener.LISTEN_MESSAGE_SEND_FAIL) != 0) { mListener.onMessageSendFail(messageId, status); } } catch (RemoteException e) { Log.w(TAG, "onMessageSendFail: RemoteException (FYI): " + e); } } public void onMatch(int requestorInstanceId, byte[] peerMac, byte[] serviceSpecificInfo, int serviceSpecificInfoLength, byte[] matchFilter, int matchFilterLength) { String prevMac = mMacByRequestorInstanceId.get(requestorInstanceId); mMacByRequestorInstanceId.put(requestorInstanceId, new String(HexEncoding.encode(peerMac))); if (DBG) Log.d(TAG, "onMatch: previous peer MAC replaced - " + prevMac); try { if (mListener != null && (mEvents & WifiNanSessionListener.LISTEN_MATCH) != 0) { mListener.onMatch(requestorInstanceId, serviceSpecificInfo, serviceSpecificInfoLength, matchFilter, matchFilterLength); } } catch (RemoteException e) { Log.w(TAG, "onMatch: RemoteException (FYI): " + e); } } public void onMessageReceived(int requestorInstanceId, byte[] peerMac, byte[] message, int messageLength) { String prevMac = mMacByRequestorInstanceId.get(requestorInstanceId); mMacByRequestorInstanceId.put(requestorInstanceId, new String(HexEncoding.encode(peerMac))); if (DBG) { Log.d(TAG, "onMessageReceived: previous peer MAC replaced - " + prevMac); } try { if (mListener != null && (mEvents & WifiNanSessionListener.LISTEN_MESSAGE_RECEIVED) != 0) { mListener.onMessageReceived(requestorInstanceId, message, messageLength); } } catch (RemoteException e) { Log.w(TAG, "onMessageReceived: RemoteException (FYI): " + e); } } public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { pw.println("NanSessionState:"); pw.println(" mSessionId: " + mSessionId); pw.println(" mSessionType: " + mSessionType); pw.println(" mEvents: " + mEvents); pw.println(" mPubSubId: " + (mPubSubIdValid ? Integer.toString(mPubSubId) : "not valid")); pw.println(" mMacByRequestorInstanceId: [" + mMacByRequestorInstanceId + "]"); } }
37.886719
100
0.638623
3ee701dcf71727720b378aee46a07523735f537d
149
package com.estproject.core.dao; import com.estproject.common.domain.UserVO; public interface UserDao { UserVO queryUserById(Long id); }
16.555556
44
0.744966
f802ed412cff82c8ad3fd8979a0cdd0cb130b858
26,438
package au.com.museumvictoria.fieldguide.vic.ui; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.util.zip.CRC32; import android.app.PendingIntent; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Messenger; import android.os.SystemClock; import android.provider.Settings; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import au.com.museumvictoria.fieldguide.vic.R; import au.com.museumvictoria.fieldguide.vic.db.FieldGuideDatabase; import au.com.museumvictoria.fieldguide.vic.service.FieldGuideDownloaderService; import au.com.museumvictoria.fieldguide.vic.util.Utilities; import com.actionbarsherlock.app.SherlockActivity; import com.android.vending.expansion.zipfile.ZipResourceFile; import com.android.vending.expansion.zipfile.ZipResourceFile.ZipEntryRO; import com.google.android.vending.expansion.downloader.Constants; import com.google.android.vending.expansion.downloader.DownloadProgressInfo; import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller; import com.google.android.vending.expansion.downloader.DownloaderServiceMarshaller; import com.google.android.vending.expansion.downloader.Helpers; import com.google.android.vending.expansion.downloader.IDownloaderClient; import com.google.android.vending.expansion.downloader.IDownloaderService; import com.google.android.vending.expansion.downloader.IStub; public class SplashActivity extends SherlockActivity implements IDownloaderClient { private static final String TAG = "SplashScreenActivity"; private TextView mProgressText; private ProgressBar mProgress; private int mProgressStatus = 0; private Handler mHandler = new Handler(); FieldGuideDatabase mDatabase; Cursor mCursor; private ProgressBar mPB; private TextView mStatusText; private TextView mProgressFraction; private TextView mProgressPercent; private TextView mAverageSpeed; private TextView mTimeRemaining; private View mDashboard; private View progressDashboard; private View mCellMessage; private Button mPauseButton; private Button mWiFiSettingsButton; private boolean mStatePaused; private int mState; private IDownloaderService mRemoteService; private IStub mDownloaderClientStub; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); // overridePendingTransition(R.anim.fragment_slide_left_enter, // R.anim.fragment_slide_left_exit); // Check if expansion files are available before going any further if (!expansionFilesDelivered()) { try { Utilities.cleanUpOldData(getApplicationContext()); // Build an Intent to start this activity from the Notification Intent notifierIntent = new Intent(this, SplashActivity.this.getClass()); notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT); // Start the download service (if required) int startResult = DownloaderClientMarshaller .startDownloadServiceIfRequired(this, pendingIntent, FieldGuideDownloaderService.class); // If download has started, initialize this activity to show // download progress if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) { // Instantiate a member instance of IStub // mDownloaderClientStub = // DownloaderClientMarshaller.CreateStub(this, // FieldGuideDownloaderService.class); // Inflate layout that shows download progress // setContentView(R.layout.downloader_ui); /** * Both downloading and validation make use of the * "download" UI */ initializeDownloadUI(); return; } // If the download wasn't necessary, fall through to start the // app } catch (NameNotFoundException e) { Log.e(TAG, "Cannot find own package! MAYDAY!"); e.printStackTrace(); } } startApp(); } @Override protected void onResume() { if (null != mDownloaderClientStub) { mDownloaderClientStub.connect(this); } super.onResume(); } @Override protected void onStop() { if (null != mDownloaderClientStub) { mDownloaderClientStub.disconnect(this); } super.onStop(); } @Override protected void onDestroy() { this.mCancelValidation = true; super.onDestroy(); } /** * Load up the acitivity after 2 seconds of splash screen * */ private void startFieldGuide() { Log.d(TAG, "Starting Field Guide"); Intent home = new Intent(getApplicationContext(), MainActivity.class); home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(home); SharedPreferences settings = getSharedPreferences(Utilities.PREFS_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("firstRun", false); editor.putInt("currentVersion", Utilities.MAIN_VERSION); // Commit the edits! editor.commit(); finish(); } private void startApp() { setContentView(R.layout.activity_splash); mProgress = (ProgressBar) findViewById(R.id.progressBar); mProgressText = (TextView) findViewById(R.id.textProgress); // Restore preferences SharedPreferences settings = getSharedPreferences(Utilities.PREFS_NAME, MODE_PRIVATE); boolean isFirstRun = settings.getBoolean("firstRun", true); int currentVersion = settings.getInt("currentVersion", 1); Log.d(TAG, "From settings:\n\tisFirstRun: " + isFirstRun + "\n\tcurrentVersion: " + currentVersion); // if not the first run, check that the data isn't updated. // the MAIN_VERSION should be higher than the saved option if (!isFirstRun) { if (currentVersion < Utilities.MAIN_VERSION) { isFirstRun = true; } } Log.w(TAG, "Is first run? " + isFirstRun); if (isFirstRun) { // initialise the database for first run mProgress.setVisibility(View.VISIBLE); mProgressText.setVisibility(View.VISIBLE); Log.w(TAG, "About to start loading data for first run..."); // Start lengthy operation in a background thread new Thread(new Runnable() { public void run() { Log.d(TAG, "Getting Expansion files"); String[] expfiles = Utilities.getAPKExpansionFiles(getApplicationContext()); File dataDir = Utilities.getExternalDataPath(getApplicationContext()); if (!dataDir.exists()) { mProgress.setIndeterminate(true); mProgressText.setText("Expanding data... "); dataDir.mkdirs(); Log.d(TAG, "Unzipping main expansion file to: " + dataDir.toString()); Utilities.unzipExpansionFile(expfiles[0], dataDir); mProgress.setIndeterminate(false); // mProgressText.setText("Expanding data... done"); } // mDatabase = new // FieldGuideDatabase(getApplicationContext()); mDatabase = FieldGuideDatabase .getInstance(getApplicationContext()); mCursor = mDatabase.getSpeciesGroups(); while (mProgressStatus < 100) { mProgressStatus = doLoadDatabase(); // Update the progress bar mHandler.post(new Runnable() { public void run() { mProgress.setProgress(mProgressStatus); if (mProgressStatus == -9999) { mProgressText .setText("Reading in field guide data..."); } else if (mProgressStatus == 0) { mProgressText .setText("Loading field guide data..."); } else if (mProgressStatus == 100) { mProgressText .setText("Loading species: Completed"); } else { mProgressText.setText("Loading species: " + mProgressStatus + "% done"); } } }); } // database now populated. Let's start if (mProgressStatus >= 100) { if (mCursor != null) { mCursor.close(); } mDatabase.close(); startFieldGuide(); } } }).start(); } else { Log.w(TAG, "Data has already been loaded..."); mProgress.setVisibility(View.INVISIBLE); mProgressText.setVisibility(View.INVISIBLE); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { startFieldGuide(); } }, 1000); } } /** * Load the database * * @return int Progress */ private int doLoadDatabase() { double currCount = mDatabase.getCurrCount(); double totalCount = mDatabase.getTotalCount(); int percentage = 0; try { double dd = (currCount / totalCount); percentage = (int) (dd * 100); } catch (ArithmeticException ae) { // TODO: catch divide by 0 } catch (Exception e) { // TODO: handle exception } if (totalCount == 0) { return -9999; } else { return percentage; } } private void setState(int newState) { if (mState != newState) { mState = newState; mStatusText.setText(Helpers.getDownloaderStringResourceIDFromState(newState)); } } private void setButtonPausedState(boolean paused) { mStatePaused = paused; int stringResourceID = paused ? R.string.text_button_resume : R.string.text_button_pause; mPauseButton.setText(stringResourceID); } /** * This is a little helper class that demonstrates simple testing of an * Expansion APK file delivered by Market. You may not wish to hard-code * things such as file lengths into your executable... and you may wish to * turn this code off during application development. */ private static class XAPKFile { public final boolean mIsMain; public final int mFileVersion; public final long mFileSize; XAPKFile(boolean isMain, int fileVersion, long fileSize) { mIsMain = isMain; mFileVersion = fileVersion; mFileSize = fileSize; } } /** * Here is where you place the data that the validator will use to determine * if the file was delivered correctly. This is encoded in the source code * so the application can easily determine whether the file has been * properly delivered without having to talk to the server. If the * application is using LVL for licensing, it may make sense to eliminate * these checks and to just rely on the server. */ private static final XAPKFile[] xAPKS = { new XAPKFile(true, // true signifies a main file Utilities.MAIN_VERSION, // the version of the APK that the file was uploaded against Utilities.EXP_FILE_SIZE // the length of the file in bytes ) }; /** * Go through each of the APK Expansion files defined in the structure above * and determine if the files are present and match the required size. Free * applications should definitely consider doing this, as this allows the * application to be launched for the first time without having a network * connection present. Paid applications that use LVL should probably do at * least one LVL check that requires the network to be present, so this is * not as necessary. * * @return true if they are present. */ boolean expansionFilesDelivered() { for (XAPKFile xf : xAPKS) { String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsMain, xf.mFileVersion); if (!Helpers.doesFileExist(this, fileName, xf.mFileSize, false)) return false; } return true; } /** * Calculating a moving average for the validation speed so we don't get * jumpy calculations for time etc. */ static private final float SMOOTHING_FACTOR = 0.005f; /** * Used by the async task */ private boolean mCancelValidation; /** * Go through each of the Expansion APK files and open each as a zip file. * Calculate the CRC for each file and return false if any fail to match. * * @return true if XAPKZipFile is successful */ void validateXAPKZipFiles() { AsyncTask<Object, DownloadProgressInfo, Boolean> validationTask = new AsyncTask<Object, DownloadProgressInfo, Boolean>() { @Override protected void onPreExecute() { mDashboard.setVisibility(View.VISIBLE); mCellMessage.setVisibility(View.GONE); mStatusText.setText(R.string.text_verifying_download); mPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mCancelValidation = true; } }); mPauseButton.setText(R.string.text_button_cancel_verify); super.onPreExecute(); } @Override protected Boolean doInBackground(Object... params) { for (XAPKFile xf : xAPKS) { String fileName = Helpers.getExpansionAPKFileName( SplashActivity.this, xf.mIsMain, xf.mFileVersion); if (!Helpers.doesFileExist(SplashActivity.this, fileName, xf.mFileSize, false)) return false; fileName = Helpers .generateSaveFileName(SplashActivity.this, fileName); ZipResourceFile zrf; byte[] buf = new byte[1024 * 256]; try { zrf = new ZipResourceFile(fileName); ZipEntryRO[] entries = zrf.getAllEntries(); /** * First calculate the total compressed length */ long totalCompressedLength = 0; for (ZipEntryRO entry : entries) { totalCompressedLength += entry.mCompressedLength; } float averageVerifySpeed = 0; long totalBytesRemaining = totalCompressedLength; long timeRemaining; /** * Then calculate a CRC for every file in the Zip file, * comparing it to what is stored in the Zip directory. * Note that for compressed Zip files we must extract * the contents to do this comparison. */ for (ZipEntryRO entry : entries) { if (-1 != entry.mCRC32) { long length = entry.mUncompressedLength; CRC32 crc = new CRC32(); DataInputStream dis = null; try { dis = new DataInputStream( zrf.getInputStream(entry.mFileName)); long startTime = SystemClock.uptimeMillis(); while (length > 0) { int seek = (int) (length > buf.length ? buf.length : length); dis.readFully(buf, 0, seek); crc.update(buf, 0, seek); length -= seek; long currentTime = SystemClock.uptimeMillis(); long timePassed = currentTime - startTime; if (timePassed > 0) { float currentSpeedSample = (float) seek / (float) timePassed; if (0 != averageVerifySpeed) { averageVerifySpeed = SMOOTHING_FACTOR * currentSpeedSample + (1 - SMOOTHING_FACTOR) * averageVerifySpeed; } else { averageVerifySpeed = currentSpeedSample; } totalBytesRemaining -= seek; timeRemaining = (long) (totalBytesRemaining / averageVerifySpeed); this.publishProgress( new DownloadProgressInfo( totalCompressedLength, totalCompressedLength - totalBytesRemaining, timeRemaining, averageVerifySpeed) ); } startTime = currentTime; if (mCancelValidation) return true; } if (crc.getValue() != entry.mCRC32) { Log.e(Constants.TAG, "CRC does not match for entry: " + entry.mFileName); Log.e(Constants.TAG, "In file: " + entry.getZipFileName()); return false; } } finally { if (null != dis) { dis.close(); } } } } } catch (IOException e) { e.printStackTrace(); return false; } } return true; } @Override protected void onProgressUpdate(DownloadProgressInfo... values) { onDownloadProgress(values[0]); super.onProgressUpdate(values); } @Override protected void onPostExecute(Boolean result) { if (result) { mDashboard.setVisibility(View.VISIBLE); mCellMessage.setVisibility(View.GONE); mStatusText.setText(R.string.text_validation_complete); mPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); mPauseButton.setText(android.R.string.ok); progressDashboard.setVisibility(View.GONE); } else { mDashboard.setVisibility(View.VISIBLE); mCellMessage.setVisibility(View.GONE); mStatusText.setText(R.string.text_validation_failed); mPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); mPauseButton.setText(android.R.string.cancel); } super.onPostExecute(result); } }; validationTask.execute(new Object()); } /** * If the download isn't present, we initialize the download UI. This ties * all of the controls into the remote service calls. */ private void initializeDownloadUI() { mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this, FieldGuideDownloaderService.class); setContentView(R.layout.downloader_ui); mPB = (ProgressBar) findViewById(R.id.progressBar); mStatusText = (TextView) findViewById(R.id.statusText); mProgressFraction = (TextView) findViewById(R.id.progressAsFraction); mProgressPercent = (TextView) findViewById(R.id.progressAsPercentage); mAverageSpeed = (TextView) findViewById(R.id.progressAverageSpeed); mTimeRemaining = (TextView) findViewById(R.id.progressTimeRemaining); mDashboard = findViewById(R.id.downloaderDashboard); progressDashboard = findViewById(R.id.progressDashboard); mCellMessage = findViewById(R.id.approveCellular); mPauseButton = (Button) findViewById(R.id.pauseButton); mWiFiSettingsButton = (Button) findViewById(R.id.wifiSettingsButton); mPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mStatePaused) { mRemoteService.requestContinueDownload(); } else { mRemoteService.requestPauseDownload(); } setButtonPausedState(!mStatePaused); } }); mWiFiSettingsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); } }); Button resumeOnCell = (Button) findViewById(R.id.resumeOverCellular); resumeOnCell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mRemoteService.setDownloadFlags(IDownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR); mRemoteService.requestContinueDownload(); mCellMessage.setVisibility(View.GONE); } }); } @Override public void onServiceConnected(Messenger m) { mRemoteService = DownloaderServiceMarshaller.CreateProxy(m); mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger()); } @Override public void onDownloadStateChanged(int newState) { setState(newState); boolean showDashboard = true; boolean showCellMessage = false; boolean paused; boolean indeterminate; switch (newState) { case IDownloaderClient.STATE_IDLE: // STATE_IDLE means the service is listening, so it's // safe to start making calls via mRemoteService. paused = false; indeterminate = true; break; case IDownloaderClient.STATE_CONNECTING: case IDownloaderClient.STATE_FETCHING_URL: showDashboard = true; paused = false; indeterminate = true; break; case IDownloaderClient.STATE_DOWNLOADING: paused = false; showDashboard = true; indeterminate = false; break; case IDownloaderClient.STATE_FAILED_CANCELED: case IDownloaderClient.STATE_FAILED: case IDownloaderClient.STATE_FAILED_FETCHING_URL: case IDownloaderClient.STATE_FAILED_UNLICENSED: paused = true; showDashboard = false; indeterminate = false; break; case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION: case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION: showDashboard = false; paused = true; indeterminate = false; showCellMessage = true; break; case IDownloaderClient.STATE_PAUSED_BY_REQUEST: paused = true; indeterminate = false; break; case IDownloaderClient.STATE_PAUSED_ROAMING: case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE: paused = true; indeterminate = false; break; case IDownloaderClient.STATE_COMPLETED: showDashboard = false; paused = false; indeterminate = false; validateXAPKZipFiles(); return; default: paused = true; indeterminate = true; showDashboard = true; } int newDashboardVisibility = showDashboard ? View.VISIBLE : View.GONE; if (mDashboard.getVisibility() != newDashboardVisibility) { mDashboard.setVisibility(newDashboardVisibility); } int cellMessageVisibility = showCellMessage ? View.VISIBLE : View.GONE; if (mCellMessage.getVisibility() != cellMessageVisibility) { mCellMessage.setVisibility(cellMessageVisibility); } mPB.setIndeterminate(indeterminate); setButtonPausedState(paused); } @Override public void onDownloadProgress(DownloadProgressInfo progress) { mAverageSpeed.setText(getString(R.string.kilobytes_per_second, Helpers.getSpeedString(progress.mCurrentSpeed))); mTimeRemaining.setText(getString(R.string.time_remaining, Helpers.getTimeRemaining(progress.mTimeRemaining))); progress.mOverallTotal = progress.mOverallTotal; mPB.setMax((int) (progress.mOverallTotal >> 8)); mPB.setProgress((int) (progress.mOverallProgress >> 8)); mProgressPercent.setText(Long.toString(progress.mOverallProgress * 100 / progress.mOverallTotal) + "%"); mProgressFraction.setText(Helpers.getDownloadProgressString (progress.mOverallProgress, progress.mOverallTotal)); } }
36.821727
130
0.586466
8b9689b20e00a1b0f9f4f1d8b4deb589f8e2a3a5
470
package com.floreysoft.jmte.token; public abstract class AbstractToken implements Token { protected final int line; protected final int column; public AbstractToken(int line, int column) { this.line = line; this.column = column; } public abstract String getText(); public int getLine() { return line; } public int getColumn() { return column; } @Override public String toString() { return getText(); } }
17.407407
55
0.653191
0cdc32198ceb014d9ede7b2b542cbadabbaf86f2
1,645
package com.ruoyi.projectApproval.AppxNgReq.mapper; import java.util.List; import com.ruoyi.projectApproval.AppxNgReq.domain.AppxNgReq; /** * 事前审批Mapper接口 * * @author Mu * @date 2020-12-09 */ public interface AppxNgReqMapper { /** * 查询事前审批 * * @param id 事前审批ID * @return 事前审批 */ public AppxNgReq selectAppxNgReqById(String id); /** * @Title: IAppxNgReqService.java * @Description: 根据事前审批主表ID获取事前审批信息 * @Author M.Mu * @Date 2020-12-09 */ public AppxNgReq selectAppxNgReqByBid(String id); /** * 查询事前审批列表 * * @param appxNgReq 事前审批 * @return 事前审批集合 */ public List<AppxNgReq> selectAppxNgReqList(AppxNgReq appxNgReq); /** * 新增事前审批 * * @param appxNgReq 事前审批 * @return 结果 */ public int insertAppxNgReq(AppxNgReq appxNgReq); /** * 修改事前审批 * * @param appxNgReq 事前审批 * @return 结果 */ public int updateAppxNgReq(AppxNgReq appxNgReq); /** * 删除事前审批 * * @param id 事前审批ID * @return 结果 */ public int deleteAppxNgReqById(String id); /** * 批量删除事前审批 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteAppxNgReqByIds(String[] ids); /** * @Title: AppxNgReqMapper.java * @Description: 根据事前审批主表ID逻辑删除事前审批信息 * @Author M.Mu * @Date 2020-12-09 */ public int deleteAppxNgReqByBid(String id); /** * @Title: AppxNgReqMapper.java * @Description: 传入时间获取对应时间段内的集客审批数量 * @Author M.Mu * @Date 2020-12-16 */ public Integer findNumsByData(AppxNgReq appxNgReq); }
19.127907
68
0.593921
590afa24691c74e7b3290627eecbc689ac1708d8
2,781
package com.IceMetalPunk.amethystic.commands; import java.util.ArrayList; import java.util.List; import java.util.Set; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.CommandResultStats.Type; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.command.WrongUsageException; import net.minecraft.entity.Entity; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; public class CommandClearTags extends CommandBase implements ICommand { private final List<String> aliases = new ArrayList<String>(); public CommandClearTags() { aliases.add("cleartags"); } @Override public int compareTo(ICommand o) { return 0; } @Override public String getCommandName() { return "cleartags"; } @Override public String getCommandUsage(ICommandSender sender) { return "commands.cleartags.usage"; } @Override public List<String> getCommandAliases() { return this.aliases; } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (args.length > 2) { throw new WrongUsageException("commands.cleartags.usage", new Object[0]); } List<Entity> ents = new ArrayList<Entity>(); if (args.length <= 0) { ents.add(sender.getCommandSenderEntity()); } else { ents = getEntityList(server, sender, args[0]); } if (ents == null || ents.isEmpty()) { throw new CommandException("commands.cleartags.noentity", new Object[0]); } int number = 0; // Prefix-matched removal List<String> toRemove = new ArrayList<String>(); if (args.length > 1) { String prefix = args[1]; for (Entity ent : ents) { Set<String> tags = ent.getTags(); for (String tag : tags) { if (tag.startsWith(prefix)) { toRemove.add(tag); } } for (String tag : toRemove) { tags.remove(tag); ++number; } } } // Generic removal else { for (Entity ent : ents) { Set<String> tags = ent.getTags(); number += tags.size(); tags.clear(); } } sender.setCommandStat(Type.SUCCESS_COUNT, number); if (number <= 0) { throw new CommandException("commands.cleartags.notags", new Object[0]); } notifyCommandListener(sender, this, "commands.cleartags.success", new Object[] { number, ents.size() }); } @Override public boolean checkPermission(MinecraftServer server, ICommandSender sender) { return true; } @Override public List<String> getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos) { return new ArrayList<String>(); } @Override public boolean isUsernameIndex(String[] args, int index) { return false; } }
24.182609
108
0.708019
e5c31be414a89b486cdda524e50816c47760ecc9
766
package com.lbh.friendcircledemo.views; import android.content.Context; import android.util.AttributeSet; import android.widget.ListView; public class UserDataItemNoScrollView extends ListView { public UserDataItemNoScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UserDataItemNoScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public UserDataItemNoScrollView(Context context) { super(context); } /** * 屏蔽listview的滑动 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, mExpandSpec); } }
23.9375
72
0.778068
78abac3f83b93d4fffd656f4f6f46efa9954506f
393
package com.whoiszxl.command; import com.whoiszxl.command.cmd.FollowMemberCommand; import com.whoiszxl.model.ddd.ApplicationService; /** * 关注应用服务接口 * * @author whoiszxl * @date 2022/1/27 */ public interface FollowerApplicationService extends ApplicationService { /** * 关注用户 * @param followMemberCommand */ void follow(FollowMemberCommand followMemberCommand); }
19.65
72
0.735369
250b557e56dd1701228db29d7eb97aee53086e6e
556
package net.anzix.spark; import org.apache.spark.storage.StorageLevel; import org.apache.spark.streaming.receiver.Receiver; public class DataGenerator extends Receiver<String> { public DataGenerator() { super(StorageLevel.MEMORY_AND_DISK_2()); } @Override public void onStart() { new Thread(this::generate).start(); } private void generate() { for (int i = 0; i < 100; i++) { store("" + i); } stop("Stream is ended"); } @Override public void onStop() { } }
19.172414
53
0.597122
4a8b0a64484b0ac310f2e87e9cdce971ac71a10a
429
package com.github.shoothzj.distribute.job.impl.common.service; import com.github.shoothzj.distribute.job.api.module.CronJob; import com.github.shoothzj.distribute.job.api.module.JobCallbackDto; /** * @author hezhangjian */ public interface ICronJobService { void addJob(String jobId, String context, CronJob cronJob, JobCallbackDto jobCallbackDto) throws Exception; void delJob(String jobId) throws Exception; }
26.8125
112
0.79021
eb56451a37cbe4f45fe377bcdc7239499300610e
2,484
package com.vidnyan.javaspringbootjwtautontication.config; import javax.servlet.Filter; import com.vidnyan.javaspringbootjwtautontication.filter.JwtRequestFilter; import com.vidnyan.javaspringbootjwtautontication.service.UserService; import org.hibernate.query.criteria.internal.expression.ConcatExpression; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired UserService userService; @Autowired private Filter jwtRequestFilter; protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().antMatchers("/authonticate").permitAll().anyRequest().authenticated() .and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } @Bean public PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
45.163636
119
0.833333
2df4d0ebb3186b14e97b52ab527036e3020cbfc7
4,052
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.repositoryservices.auditlog; import com.fasterxml.jackson.databind.ObjectMapper; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import static org.testng.Assert.*; import static org.testng.Assert.assertNotNull; /** * Validate the methods of OMRSAuditCode */ public class TestOMRSAuditCode { private final static String messageIdPrefix = "OMRS-AUDIT-"; private List<String> existingMessageIds = new ArrayList<>(); /** * Validate that a supplied ordinal is unique. * * @param ordinal value to test * @return boolean result */ private boolean isUniqueOrdinal(String ordinal) { if (existingMessageIds.contains(ordinal)) { return false; } else { existingMessageIds.add(ordinal); return true; } } private void testSingleErrorCodeValues(OMRSAuditCode testValue) { String testInfo; assertTrue(isUniqueOrdinal(testValue.getLogMessageId())); assertTrue(testValue.getLogMessageId().contains(messageIdPrefix)); assertNotNull(testValue.getSeverity()); testInfo = testValue.getFormattedLogMessage("Field1", "Field2", "Field3", "Field4", "Field5", "Field6"); assertNotNull(testInfo); assertFalse(testInfo.isEmpty()); testInfo = testValue.getSystemAction(); assertNotNull(testInfo); assertFalse(testInfo.isEmpty()); testInfo = testValue.getUserAction(); assertNotNull(testInfo); assertFalse(testInfo.isEmpty()); } /** * Validated the values of the enum. */ @Test public void testAllAuditCodeValues() { for (OMRSAuditCode errorCode : OMRSAuditCode.values()) { testSingleErrorCodeValues(errorCode); testErrorCodeMethods(errorCode); } } /** * Validate that an object generated from a JSON String has the same content as the object used to * create the JSON String. */ @Test public void testJSON() { ObjectMapper objectMapper = new ObjectMapper(); String jsonString = null; try { jsonString = objectMapper.writeValueAsString(OMRSAuditCode.NULL_EVENT_TO_PROCESS); } catch (Throwable exc) { fail("Exception: " + exc.getMessage()); } try { assertSame(objectMapper.readValue(jsonString, OMRSAuditCode.class), OMRSAuditCode.NULL_EVENT_TO_PROCESS); } catch (Throwable exc) { fail("Exception: " + exc.getMessage()); } } /** * Test that equals is working. */ @Test public void testEquals() { assertEquals(OMRSAuditCode.NEW_ENTERPRISE_CONNECTOR, OMRSAuditCode.NEW_ENTERPRISE_CONNECTOR); assertFalse(OMRSAuditCode.NEW_ENTERPRISE_CONNECTOR.equals(OMRSAuditCode.DISCONNECTING_ENTERPRISE_CONNECTOR)); } /** * Test that hashcode is working. */ @Test public void testHashcode() { assertEquals(OMRSAuditCode.OMRS_AUDIT_LOG_READY.hashCode(), OMRSAuditCode.OMRS_AUDIT_LOG_READY.hashCode()); assertFalse(OMRSAuditCode.OMRS_AUDIT_LOG_READY.hashCode() == OMRSAuditCode.NEW_ENTERPRISE_CONNECTOR.hashCode()); } private void testErrorCodeMethods(OMRSAuditCode testObject) { assertNotNull(testObject.getLogMessageId()); assertNotNull(testObject.getSeverity()); assertNotNull(testObject.getFormattedLogMessage()); assertNotNull(testObject.getSystemAction()); assertNotNull(testObject.getUserAction()); } /** * Test that toString is overridden. */ @Test public void testToString() { assertTrue(OMRSAuditCode.NEW_TYPE_ADDED.toString().contains("OMRSAuditCode")); } }
27.753425
120
0.643633
84dd57724cb5c7c3d81388b1f0dfbe4e195ffef5
1,194
public List<List<Integer>> XXX(int[] nums) { List<List<Integer>> res = new ArrayList<>(); Set<List<Integer>> set = new HashSet<>(); if(nums.length < 3) return res; Arrays.sort(nums); if(nums[0] > 0 || nums[nums.length - 1] < 0) return res; Map<Integer, Integer> map = new LinkedHashMap<>(); for(int i = 0;i < nums.length;i++) { if(nums[i] > 0) { break; } if (i > 0 && nums[i] == nums[i -1]){ continue; } int target = -nums[i]; //nums[j]需要target - nums[j]才能凑出target for(int j = i + 1;j < nums.length;j++) { if(map.containsKey(nums[j])) { //System.out.println("nums[i]:"+nums[i]+", " + "nums[j]:"+nums[j]+", " + "nums[j] - target):"+ (nums[j] - target)); set.add(Arrays.asList(nums[i],nums[map.get(nums[j])], nums[j])); }else{ map.put(target - nums[j], j); } } map.clear(); } for(List<Integer> list : set) { res.add(list); } return res; }
36.181818
135
0.422111
ca6cc959e684e636e045346b6082ac2100c75c1a
3,377
package net.secknv.scomp.item; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItemFrame; import net.minecraft.init.Items; import net.minecraft.item.IItemPropertyGetter; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.*; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; public class SCCompassOverride { public static void override() { Items.COMPASS.addPropertyOverride(new ResourceLocation("angle"), new IItemPropertyGetter() { @SideOnly(Side.CLIENT) double rotation; @SideOnly(Side.CLIENT) double rota; @SideOnly(Side.CLIENT) long lastUpdateTick; @SideOnly(Side.CLIENT) public float apply(ItemStack stack, @Nullable World worldIn, @Nullable EntityLivingBase entityIn) { if (entityIn == null && !stack.isOnItemFrame()) { return 0.0F; } else { //true if compass in player's hand boolean flag = entityIn != null; //entity becomes either the player(EntityLivingBase) or the ItemFrame(EntityItemFrame) Entity entity = flag ? entityIn : stack.getItemFrame(); if (worldIn == null) { worldIn = entity.worldObj; } //this is the float returned double d0; if (worldIn.provider.isSurfaceWorld()) { double d1 = flag ? (double)entity.rotationYaw : this.getFrameRotation((EntityItemFrame)entity); d1 = (double)MathHelper.positiveModulo( (float)d1 / 360F, 1.0F ); //this adds an offset because of how compass textures are saved. #justmojangthings d0 = 0.5D - d1; } else { d0 = Math.random(); } if (flag) { d0 = this.wobble(worldIn, d0); } return MathHelper.positiveModulo((float)d0, 1.0F); } } @SideOnly(Side.CLIENT) private double wobble(World worldIn, double num) { if (worldIn.getTotalWorldTime() != this.lastUpdateTick) { this.lastUpdateTick = worldIn.getTotalWorldTime(); double d0 = num - this.rotation; d0 = (double)MathHelper.positiveModulo( (float)d0 + 0.5F, 1.0F ) - 0.5D; this.rota += d0 * 0.1D; this.rota *= 0.8D; this.rotation += this.rota; this.rotation = (double)MathHelper.positiveModulo( (float)this.rotation, 1.0F ); } return this.rotation; } @SideOnly(Side.CLIENT) private double getFrameRotation(EntityItemFrame entFrame) { return (double)MathHelper.clampAngle(180 + entFrame.facingDirection.getHorizontalIndex() * 90); } }); } }
33.435644
119
0.543678
028f534be7221563d22c6872c6cadc570c40a8b4
2,415
package com.github.ksokol.mailsink.websocket; import com.github.ksokol.mailsink.entity.Mail; import com.github.ksokol.mailsink.repository.MailRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.messaging.simp.SimpMessagingTemplate; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; /** * @author Kamill Sokol */ @RunWith(MockitoJUnitRunner.class) public class IncomingMessageListenerTest { @Mock private MailRepository mailRepository; @Mock private SimpMessagingTemplate template; @InjectMocks private IncomingMessageListener listener; @Captor private ArgumentCaptor<String> destinationCaptor; @Captor private ArgumentCaptor<Map<String, Long>> payloadCaptor; @Captor private ArgumentCaptor<Mail> mailCaptor; private Mail mail; @Before public void setUp() { mail = new Mail(); mail.setId(999L); listener.handleIncomingEvent(new IncomingEvent(mail)); } @Test public void shouldSaveIncomingMail() { verify(mailRepository).save(mailCaptor.capture()); assertThat(mailCaptor.getValue()).isEqualTo(mail); } @Test public void shouldPublishMail() { verify(template).convertAndSend(destinationCaptor.capture(), payloadCaptor.capture()); assertThat(payloadCaptor.getValue()).containsExactly(entry("id", 999L)); } @Test public void shouldPublishInProperTopic() { verify(template).convertAndSend(destinationCaptor.capture(), payloadCaptor.capture()); assertThat(destinationCaptor.getValue()).isEqualTo("/topic/incoming-mail"); } @Test public void shouldSaveMailBeforePublish() { InOrder callOrder = inOrder(mailRepository, template); callOrder.verify(mailRepository).save(any(Mail.class)); callOrder.verify(template).convertAndSend(anyString(), any(Map.class)); } }
28.75
94
0.742029
f6d7283d25e8152b2af09d7aa26bd50379769e97
4,500
/* * InformationMachineAPILib * * */ package co.iamdata.api.models; import java.util.*; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; public class UserPurchase implements java.io.Serializable { private static final long serialVersionUID = 5172307608518895349L; private String date; private Integer id; private String orderNumber; private List<PurchaseItemData> purchaseItems; private String receiptId; private String receiptImageUrl; private Double tax; private Double total; private Double totalWithoutTax; private UserStore userStore; /** GETTER * TODO: Write general description for this method */ @JsonGetter("date") public String getDate ( ) { return this.date; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("date") public void setDate (String value) { this.date = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("id") public Integer getId ( ) { return this.id; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("id") public void setId (Integer value) { this.id = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("order_number") public String getOrderNumber ( ) { return this.orderNumber; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("order_number") public void setOrderNumber (String value) { this.orderNumber = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("purchase_items") public List<PurchaseItemData> getPurchaseItems ( ) { return this.purchaseItems; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("purchase_items") public void setPurchaseItems (List<PurchaseItemData> value) { this.purchaseItems = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("receipt_id") public String getReceiptId ( ) { return this.receiptId; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("receipt_id") public void setReceiptId (String value) { this.receiptId = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("receipt_image_url") public String getReceiptImageUrl ( ) { return this.receiptImageUrl; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("receipt_image_url") public void setReceiptImageUrl (String value) { this.receiptImageUrl = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("tax") public Double getTax ( ) { return this.tax; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("tax") public void setTax (Double value) { this.tax = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("total") public Double getTotal ( ) { return this.total; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("total") public void setTotal (Double value) { this.total = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("total_without_tax") public Double getTotalWithoutTax ( ) { return this.totalWithoutTax; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("total_without_tax") public void setTotalWithoutTax (Double value) { this.totalWithoutTax = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("user_store") public UserStore getUserStore ( ) { return this.userStore; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("user_store") public void setUserStore (UserStore value) { this.userStore = value; } }
24.193548
70
0.614222
d63e86d6c6deb5cfa6a81f70eb5f31165bc4eb0f
3,621
package org.dynmap; import java.util.concurrent.ConcurrentHashMap; import org.dynmap.servlet.ClientUpdateServlet; import org.json.simple.JSONObject; public class InternalClientUpdateComponent extends ClientUpdateComponent { /** * Interval (in milliseconds) on which a client update snapshot should be gathered. */ protected final long jsonInterval; protected long currentTimestamp = 0; protected long lastTimestamp = 0; protected long lastChatTimestamp = 0; private long last_confighash; private ConcurrentHashMap<String, JSONObject> updates = new ConcurrentHashMap<String, JSONObject>(); private JSONObject clientConfiguration = null; private static InternalClientUpdateComponent singleton; public InternalClientUpdateComponent(final DynmapCore dcore, final ConfigurationNode configuration) { super(dcore, configuration); dcore.addServlet("/up/world/*", new ClientUpdateServlet(dcore)); jsonInterval = (long)(configuration.getFloat("writeinterval", 1) * 1000); final long intervalTicks = jsonInterval / 50; core.getServer().scheduleServerTask(new Runnable() { @Override public void run() { currentTimestamp = System.currentTimeMillis(); if(last_confighash != core.getConfigHashcode()) { writeConfiguration(); } writeUpdates(); lastTimestamp = currentTimestamp; core.getServer().scheduleServerTask(this, intervalTicks); }}, intervalTicks); core.events.addListener("initialized", new Event.Listener<Object>() { @Override public void triggered(Object t) { writeConfiguration(); writeUpdates(); /* Make sure we stay in sync */ } }); core.events.addListener("worldactivated", new Event.Listener<DynmapWorld>() { @Override public void triggered(DynmapWorld t) { writeConfiguration(); writeUpdates(); /* Make sure we stay in sync */ } }); /* Initialize */ writeConfiguration(); writeUpdates(); singleton = this; } @SuppressWarnings("unchecked") protected void writeUpdates() { if(core.mapManager == null) return; //Handles Updates for (DynmapWorld dynmapWorld : core.mapManager.getWorlds()) { JSONObject update = new JSONObject(); update.put("timestamp", currentTimestamp); ClientUpdateEvent clientUpdate = new ClientUpdateEvent(currentTimestamp - 30000, dynmapWorld, update); clientUpdate.include_all_users = true; core.events.trigger(InternalEvents.BUILD_CLIENT_UPDATE, clientUpdate); updates.put(dynmapWorld.getName(), update); } } protected void writeConfiguration() { JSONObject clientConfiguration = new JSONObject(); core.events.trigger(InternalEvents.BUILD_CLIENT_CONFIG, clientConfiguration); this.clientConfiguration = clientConfiguration; last_confighash = core.getConfigHashcode(); } public static JSONObject getWorldUpdate(String wname) { if(singleton != null) { return singleton.updates.get(wname); } return null; } public static JSONObject getClientConfig() { if(singleton != null) return singleton.clientConfiguration; return null; } }
36.21
114
0.626622
f6c7e501dba43be4ca2f22d953d8638f87110bfb
1,294
package com.ess.utils; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; public class ThreadedHandler extends Handler { private static final String TAG = ThreadedHandler.class.getSimpleName(); /* default handler */ public static final ThreadedHandler createHandler() { return createHandler(TAG); } /* handler callback associated with posted messages and runnables */ public static final ThreadedHandler createHandler(final Callback callback) { return createHandler(TAG, callback); } private static final ThreadedHandler createHandler(final String name) { Looper looper = createLooper(name); return new ThreadedHandler(looper); } private static final ThreadedHandler createHandler(final String name, final Callback callback) { Looper looper = createLooper(name); return new ThreadedHandler(looper, callback); } private static final Looper createLooper(final String name) { final HandlerThread handlerThread = new HandlerThread(name); handlerThread.start(); return handlerThread.getLooper(); } private ThreadedHandler(final Looper looper) { super(looper); } private ThreadedHandler(final Looper looper, final Callback callback) { super(looper, callback); } }
28.130435
97
0.74575
26c6e8dada334ba72351dbc3b8ae5e6794b2727a
2,561
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.merge; import com.intellij.diff.util.DiffUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; public class ErrorMergeTool implements MergeTool { public static final ErrorMergeTool INSTANCE = new ErrorMergeTool(); @NotNull @Override public MergeViewer createComponent(@NotNull MergeContext context, @NotNull MergeRequest request) { return new MyViewer(context, request); } @Override public boolean canShow(@NotNull MergeContext context, @NotNull MergeRequest request) { return true; } private static class MyViewer implements MergeViewer { @NotNull private final MergeContext myMergeContext; @NotNull private final MergeRequest myMergeRequest; @NotNull private final JPanel myPanel; MyViewer(@NotNull MergeContext context, @NotNull MergeRequest request) { myMergeContext = context; myMergeRequest = request; myPanel = new JPanel(new BorderLayout()); myPanel.add(DiffUtil.createMessagePanel("Can't show merge"), BorderLayout.CENTER); } @NotNull @Override public JComponent getComponent() { return myPanel; } @Nullable @Override public JComponent getPreferredFocusedComponent() { return null; } @NotNull @Override public ToolbarComponents init() { return new ToolbarComponents(); } @Nullable @Override public Action getResolveAction(@NotNull final MergeResult result) { if (result == MergeResult.RESOLVED) return null; String caption = MergeUtil.getResolveActionTitle(result, myMergeRequest, myMergeContext); return new AbstractAction(caption) { @Override public void actionPerformed(ActionEvent e) { myMergeContext.finishMerge(result); } }; } @Override public void dispose() { } } }
28.142857
100
0.717298
a05e90b29883b480a99478b8448831b0e2801b31
6,344
package array_stack; /** * * @author Polis */ public class ArrayStack implements iStack { //main meta tin class ArrayStack public static final int capacity = 100; private Object arr_s[]; private int itop = -1; public ArrayStack() { this(capacity); } public ArrayStack(int capacity) { arr_s = new Object[capacity]; } @Override public int size() { return (itop+1); } @Override public boolean isEmpty() { return (itop<0); } @Override public boolean isFull() { return (itop == arr_s.length); } @Override public Object top() throws StackEmptyExc { if(size() == arr_s.length) throw new StackEmptyExc("Stack is empty"); return arr_s[itop]; } @Override public void push(Object item) throws StackFullExc { if(size() == arr_s.length) throw new StackFullExc("Stack overflow"); arr_s[++itop] = item; } @Override public Object pop() throws StackEmptyExc { Object obj; if(isEmpty()) throw new StackEmptyExc("Stack is empty"); obj = arr_s[itop]; arr_s[itop--] = null; return obj; } public static void main(String args[]) { int AM, apousies; String name, surname; double age, vathmos; char sex; System.out.println("Poses theseis na exei h stoiva ;"); ArrayStack obj1 = new ArrayStack(UserInput.getInteger()); int choice = 1; while(choice>0 || choice<7) { System.out.println("---MENU---"); System.out.println(" 1.PUSH"); System.out.println(" 2.TOP"); System.out.println(" 3.POP"); System.out.println(" 4.SIZE"); System.out.println(" 5.EMPTY"); System.out.println(" 6.FULL"); System.out.println(" 0.END PROGRAM"); do { System.out.println("Dwse epilogh 0-6"); choice = UserInput.getInteger(); }while(choice<0 ||choice>6); switch(choice) { case 0: //Program ends return ; case 1: System.out.println("Dwse to AM :"); AM = UserInput.getInteger(); while(AM < 1) { System.out.print("Dwse to AM(>0): "); AM = UserInput.getInteger(); } System.out.println("Dwse ena onoma :"); name = UserInput.getString(); System.out.println("Dwse to epitheto :"); surname = UserInput.getString(); System.out.println("Dwse thn hlikia :"); age = UserInput.getDouble(); while(age < 18) { System.out.print("Dwse swsti hlikia(>18): "); age = UserInput.getDouble(); } System.out.println("Dwse to fylo (m for male or f for female) :"); sex = UserInput.getCharacter(); while(sex != 'm' && sex != 'f') { System.out.print("Dwse to fylo(m/f): "); sex = UserInput.getCharacter(); } System.out.println("Dwse tis apousies"); apousies = UserInput.getInteger(); while(apousies < 0) { System.out.print("Dwse tis apousies, den mporei na einai <0 : "); apousies = UserInput.getInteger(); } System.out.println("Dwse ton vathmo"); vathmos = UserInput.getDouble(); while(vathmos<0 || vathmos>10) { System.out.print("Dwse to vathmo(>=0 <=10): "); vathmos = UserInput.getDouble(); } try { obj1.push(new Student(AM,name,surname,age,sex,apousies,vathmos)); } catch(StackFullExc e) { System.out.println("Stack full can't push!"); } break; case 2: try { System.out.println("--------------"); System.out.println("--Top object-- :"+obj1.top()); System.out.println("--------------"); } catch(StackEmptyExc e) { System.out.println("--------------"); System.out.println("Stack is empty"); System.out.println("--------------"); } break; case 3: try { System.out.println("--------------"); System.out.println("Pop done\n OBJECT :"+ obj1.pop()); System.out.println("--------------"); } catch(StackEmptyExc e) { System.out.println("--------------"); System.out.println("Stack is empty"); System.out.println("--------------"); } break; case 4: System.out.println("--------------"); System.out.println("Size = "+obj1.size()); System.out.println("--------------"); break; case 5: System.out.println("--------------"); System.out.println("Empty? "+obj1.isEmpty()); System.out.println("--------------"); break; case 6: System.out.println("--------------"); System.out.println("Full? "+obj1.isFull()); System.out.println("--------------"); break; } } } }
35.244444
89
0.401955
48c36028b358e05c75f806c55ca9a361f34f3be4
1,874
package com.mycompany.fallphotowall.util; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class ImageThreadPoolExecutor extends ThreadPoolExecutor { private static ImageThreadPoolExecutor imageThreadPoolExecutor; /* * 线程池相关 * */ private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final int CORE_POOL_SIZE = CPU_COUNT + 1; private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 +1; private static final long KEEP_ALIVE =10L; //用于给线程池创建线程的线程工厂类 private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { return new Thread(r,"EasyImageLoader#" + mCount.getAndIncrement()); } }; private ImageThreadPoolExecutor(int corePoolSize , int maximumPoolSize , long keepAliveTime , TimeUnit unit , BlockingQueue<Runnable> workQueue , ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); } /* * 单例模式 * */ public static synchronized ImageThreadPoolExecutor getInstance(){ if(imageThreadPoolExecutor==null){ imageThreadPoolExecutor = new ImageThreadPoolExecutor(CORE_POOL_SIZE ,MAXIMUM_POOL_SIZE ,KEEP_ALIVE ,TimeUnit.SECONDS ,new LinkedBlockingDeque<Runnable>(),sThreadFactory); } return imageThreadPoolExecutor; } }
34.703704
92
0.688901
f8928794c49773329d811598e1c99af11cb0e169
2,461
package com.github.maybeec.lexeme; import com.github.maybeec.lexeme.schemaprovider.MergeSchemaProvider; /** * * @author sholzer (Jul 7, 2015) */ public final class LeXeMeFactory { /** * */ private static LeXeMeBuilder builder = null; /** * Sets the field 'builder'. * @param builder * new value of builder * @author sholzer (Jul 7, 2015) */ public static void setBuilder(LeXeMeBuilder builder) { LeXeMeFactory.builder = builder; } /** * Private constructor to prevent instances * * @author sholzer (Jul 7, 2015) */ private LeXeMeFactory() { } /** * Special constructor to be used in nested merge processes. Won't perform a renaming of the nodes * prefixes * @param provider * {@link MergeSchemaProvider} providing MergeSchemas for namespaces * @return a LeXeMerger * @author sholzer (12.03.2015) */ public static LeXeMerger build(MergeSchemaProvider provider) { if (builder == null) { builder = new GenericLexemeBuilder(); } return builder.build(provider); } /** * @param pathToMergeSchema * String path to the MergeSchema to be used on this document. Note: Will in future builds * replaced by pathToMergeSchemas which leads to a directory containing MergeSchemas for every * used namespace. * * If <b>null</b> the default MergeSchemas will be used * @author sholzer (12.03.2015) * @return a LeXeMerger */ public static LeXeMerger build(String pathToMergeSchema) { if (builder == null) { builder = new GenericLexemeBuilder(); } return builder.build(pathToMergeSchema); } /** * A generic builder * * @author sholzer (Sep 17, 2015) */ static final class GenericLexemeBuilder implements LeXeMeBuilder { /** * {@inheritDoc} * @author sholzer (May 31, 2016) */ @Override public LeXeMerger build(MergeSchemaProvider provider) { return new LeXeMerger(provider); } /** * {@inheritDoc} * @author sholzer (May 31, 2016) */ @Override public LeXeMerger build(String pathToMergeSchema) { return new LeXeMerger(pathToMergeSchema); } } }
26.180851
109
0.583096
ee4c195bbae8c2e02c0e554f624f5b6407327800
3,966
package com.ywh.LoRaWANServer.packet.mac_part; public class OperateMacJoinRequest implements OperateMacPkt { @Override public MacPktForm MacParseData(byte[] data, String gatawayId, String syscontent) { return null; /* byte[] datain = Arrays.copyOfRange(data, 0, 19); byte[] micComputed = LoRaMacCrypto.LoRaMacJionRequestComputeMic(datain, datain.length, LoRaMacCrypto.APPKEY); byte[] micReceived = new byte[4]; System.arraycopy(data, 19, micReceived, 0, 4); Base64Utils.myprintHex(micComputed); Base64Utils.myprintHex(micReceived); if(!ObjectToString.byteToStr(micComputed).equals(ObjectToString.byteToStr(micReceived))) return null; MacJoinRequestForm macjoinrequest = new MacJoinRequestForm(); System.arraycopy(data, 1, macjoinrequest.AppEui, 0, 8); System.arraycopy(data, 9, macjoinrequest.DevEui, 0, 8); System.arraycopy(data, 17, macjoinrequest.DevNonce,0 ,2); System.out.print("DevEui: "); Base64Utils.myprintHex(macjoinrequest.DevEui); System.out.println(ObjectToString.byteToStr(macjoinrequest.DevEui)); // Date currentTime = new Date(); // SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHH:mm:ss"); // String dateString = formatter.format(currentTime); // float temperatur = (float) (22.0 + 0.5 * Math.random()); // RedisDB redisDB = new RedisDB(); // redisDB.setup(); // String userInfo = "{\"lati\":30.75461," // + "\"long\":103.92750,\"alti\":531," + "\"temperature\":" + temperatur + "," + "\"gatewayID\":\"AA555A0000000000\"}"; // // System.out.println("rrrrrrrrrrrrrrwwwwwwwwwwwwwwwwww"); // try { // RedisDB.operateRequest(gatawayId, ObjectToString.byteToStr(macjoinrequest.DevEui), dateString, syscontent); // RedisDB.operateUp(gatawayId, ObjectToString.byteToStr(macjoinrequest.DevEui), dateString, // userInfo, syscontent); // } catch (Exception e) { // // TODO: handle exception // } // return macjoinrequest; */ } @Override public MacPktForm MacParseData(byte[] data, String gatawayId, String gatewaylati, String gatewaylong, String content) { return null; } /** * 返回 Accept 帧 */ @Override public MacPktForm MacConstructData(MacPktForm macpkt) { return null; /* byte[] appnonce = {0x01,0x02,0x03};//随机 byte[] netid = {0x00,0x00,0x65}; //devaddr 高7位 = netid 低7位 netid高17位自己定 高17位为全0 byte[] devaddr = {(byte) 0xca,(byte) 0x67,0x73,0x02}; // 随机唯一 IP 192.168.1.1 byte[] rxdelay = {0x01}; //默认1 byte[] cflist = null; // byte[] dlsetting = {0x00}; MacJoinAcceptForm macjoinaccept = new MacJoinAcceptForm(); //CreateRandom createrandom = new CreateRandom(); //macjoinaccept.AppNonce = createrandom.RandomArray(8); macjoinaccept.AppNonce = appnonce; macjoinaccept.NetId = netid; macjoinaccept.DevAddr = devaddr; macjoinaccept.dlset.RFU = 0; macjoinaccept.dlset.RX1DRoffset = 0x01; macjoinaccept.dlset.Rx2DataRate = 0x02; macjoinaccept.RxDelay = rxdelay; macjoinaccept.CfList = cflist; MacUnconfirmedDataUpForm macunconfirmeddataup = new MacUnconfirmedDataUpForm(); MacJoinRequestForm macJoinRequestForm = (MacJoinRequestForm) macpkt; byte[] appSKey = LoRaMacCrypto.LoRaMacJoinComputeAppSKey(LoRaMacCrypto.APPKEY, appnonce, macJoinRequestForm.DevNonce, netid); byte[] nwkSKey = LoRaMacCrypto.LoRaMacJoinComputeNwkSKey(LoRaMacCrypto.APPKEY, appnonce, macJoinRequestForm.DevNonce, netid); try { RedisDB.saveKeyByNode(ObjectToString.byteToStrWith(devaddr), nwkSKey, appSKey); RedisDB.saveKeyByNode(ObjectToString.byteToStrWith(macJoinRequestForm.DevEui), nwkSKey, appSKey); } catch (Exception e) { // TODO: handle exception } // 加密放在组装 phy 数据时再进行计算,同时便于 MIC 值的提取 // byte[] output; // // try { // // 加密 // output = AesEncrypt.Encrypt(AesEncrypt.APPKEY, // ParseByte2HexStr.Byte2HexStr(macjoinaccept.MacPkt2Byte())); // return output; // } catch (Exception e) { // e.printStackTrace(); // } return macjoinaccept; */ } }
37.771429
127
0.718356
49164e1fe521aa49b2dbe27152c91e80e417d60c
8,510
package com.frontanilla.estratega.core; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.utils.DelayedRemovalArray; import com.frontanilla.estratega.entities.Base; import com.frontanilla.estratega.entities.Bullet; import com.frontanilla.estratega.entities.OldTank; import com.frontanilla.estratega.entities.Wall; public class Globals { public static float columnWidth; public static DelayedRemovalArray<Faction> factions = new DelayedRemovalArray<>(); public static Grid grid; public static float gridWidth; public static int numColumns; public static boolean onMatch; public static boolean onMenu; public static boolean onWinnerScreen; public static float rightSpaceWidth; public static int screenHeight; public static class ColorHolder { public static Color[] colors = new Color[10]; public static Color[] colorsSelected = new Color[10]; private static Color darkGreen; private static Color limeGreen; private static Color purple; private static void init() { darkGreen = new Color(0.0f, 0.7f, 0.0f, 1.0f); limeGreen = new Color(0.6f, 1.0f, 0.1f, 1.0f); purple = new Color(0.7f, 0.0f, 1.0f, 1.0f); colors[0] = Color.RED; colors[1] = Color.ORANGE; colors[2] = Color.YELLOW; colors[3] = limeGreen; colors[4] = darkGreen; colors[5] = Color.CYAN; colors[6] = Color.BLUE; colors[7] = purple; colors[8] = Color.PINK; colors[9] = Color.WHITE; colorsSelected[0] = Color.RED; colorsSelected[1] = Color.ORANGE; colorsSelected[2] = Color.YELLOW; colorsSelected[3] = limeGreen; colorsSelected[4] = darkGreen; colorsSelected[5] = Color.CYAN; colorsSelected[6] = Color.BLUE; colorsSelected[7] = purple; colorsSelected[8] = Color.PINK; colorsSelected[9] = Color.WHITE; } static void nextColor(int color) { if (colorsSelected[color] == Color.RED) { colorsSelected[color] = colors[1]; } else if (colorsSelected[color] == Color.ORANGE) { colorsSelected[color] = colors[2]; } else if (colorsSelected[color] == Color.YELLOW) { colorsSelected[color] = colors[3]; } else if (colorsSelected[color] == limeGreen) { colorsSelected[color] = colors[4]; } else if (colorsSelected[color] == darkGreen) { colorsSelected[color] = colors[5]; } else if (colorsSelected[color] == Color.CYAN) { colorsSelected[color] = colors[6]; } else if (colorsSelected[color] == Color.BLUE) { colorsSelected[color] = colors[7]; } else if (colorsSelected[color] == purple) { colorsSelected[color] = colors[8]; } else if (colorsSelected[color] == Color.PINK) { colorsSelected[color] = colors[9]; } else if (colorsSelected[color] == Color.WHITE) { colorsSelected[color] = colors[0]; } } } public static class FontHolder { public static BitmapFont scoreNumbers; public static BitmapFont teamsNumbers; private static void init() { float numbersXScale = (Globals.rightSpaceWidth * 0.6f) / 80.0f; float numbersYScale = (Globals.columnWidth * 0.6f) / 46.0f; scoreNumbers = new BitmapFont(Gdx.files.internal("Fonts/ThridFont.fnt")); scoreNumbers.getData().setScale(numbersXScale, numbersYScale); float teamsXScale = (((float) (Globals.screenHeight / 3)) * 0.6f) / 80.0f; float teamsYScale = (((float) (Globals.screenHeight / 3)) * 0.6f) / 46.0f; teamsNumbers = new BitmapFont(Gdx.files.internal("Fonts/ThridFont.fnt")); teamsNumbers.getData().setScale(teamsXScale, teamsYScale); } private static void dispose() { scoreNumbers.dispose(); teamsNumbers.dispose(); } } public static class SoundHolder { public static Sound buildWall; public static Sound buyTank; public static Sound destroy; public static Sound fireBullet; private static void init() { fireBullet = Gdx.audio.newSound(Gdx.files.internal("Sounds/firebullet.wav")); buildWall = Gdx.audio.newSound(Gdx.files.internal("Sounds/construccion.wav")); buyTank = Gdx.audio.newSound(Gdx.files.internal("Sounds/yessir.wav")); destroy = Gdx.audio.newSound(Gdx.files.internal("Sounds/explosion.wav")); } private static void dispose() { fireBullet.dispose(); buildWall.dispose(); buyTank.dispose(); destroy.dispose(); } } public static class TextureHolder { public static Texture backGround; public static Texture button; public static Texture buttonSelected; public static Texture colorFrame; public static Texture frame; public static Texture menu; public static Texture playButton; public static Texture scoreFrame; public static Texture sword; public static Texture teamsLabel; public static Texture transparent; public static Texture units; public static Texture winnerLabel; private static void init() { units = new Texture("Images/units.png"); backGround = new Texture("Images/gridcolumn.png"); transparent = new Texture("Images/transparent.png"); button = new Texture("Images/button.png"); buttonSelected = new Texture("Images/buttonselected.png"); scoreFrame = new Texture("Images/scoreframe.png"); menu = new Texture("Images/menu.png"); frame = new Texture("Images/frame.png"); playButton = new Texture("Images/playbutton.png"); sword = new Texture("Images/sword.png"); colorFrame = new Texture("Images/colorframe.png"); teamsLabel = new Texture("Images/teamslabel.png"); winnerLabel = new Texture("Images/winner.png"); Base.setClassRegion(new TextureRegion(units, 0, 64, 32, 32)); Bullet.setClassRegion(new TextureRegion(units, 32, 0, 32, 31)); OldTank.setClassRegion(new TextureRegion(units, 0, 0, 32, 32)); Wall.setClassRegion(new TextureRegion(units, 0, 32, 32, 32)); } private static void dispose() { units.dispose(); backGround.dispose(); transparent.dispose(); button.dispose(); buttonSelected.dispose(); scoreFrame.dispose(); menu.dispose(); frame.dispose(); playButton.dispose(); sword.dispose(); colorFrame.dispose(); teamsLabel.dispose(); winnerLabel.dispose(); } } static void init() { screenHeight = Gdx.graphics.getHeight(); columnWidth = (float) (screenHeight / 8); numColumns = (int) ((((float) Gdx.graphics.getWidth()) / columnWidth) - 1.0f); gridWidth = columnWidth * ((float) numColumns); rightSpaceWidth = ((float) Gdx.graphics.getWidth()) - gridWidth; onMenu = true; grid = new Grid(numColumns, 8); TextureHolder.init(); SoundHolder.init(); FontHolder.init(); ColorHolder.init(); } static void dispose() { TextureHolder.dispose(); SoundHolder.dispose(); FontHolder.dispose(); } public static void restart() { int i; int a = Turn.faction.getBulletList().size(); for (i = 0; i < a; i++) { Turn.faction.getBulletList().remove(0); } int b = grid.getUsedCells().size; for (i = 0; i < b; i++) { grid.getUsedCells().get(0).removeUnit(); } factions = new DelayedRemovalArray<>(); Turn.firstRound = true; Turn.turnNumber = 0; InputManager.waitingForBullets = false; } }
39.581395
90
0.594712
8e437f4a2e4b77190e145b6fe8141b08b9d5b99f
1,511
/** * 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.tajo.type; import org.apache.tajo.schema.Field; public abstract class TypeVisitor { public void visit(Type type) { switch (type.kind) { case ARRAY: visitArray((Array) type); break; case RECORD: visitRecord((Record) type); break; case MAP: visitMap((Map) type); break; default: visitPrimitive(type); } } void visitPrimitive(Type type) {} void visitMap(Map map) { visit(map.keyType()); visit(map.valueType()); } void visitArray(Array array) { visit(array.elementType()); } void visitRecord(Record record) { for (Field field : record.fields()) { visit(field.type()); } } }
27.472727
75
0.685639
d028fb48296d63a07a071112ad72b5972cec58e9
3,278
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.springboot; import org.springframework.transaction.support.DefaultTransactionStatus; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Ballerina Transaction Registry. * Holds transactional resources against Ballerina Transactional ID. * * @since 1.0.0 */ public class BallerinaTransactionRegistry { private static ThreadLocal<String> localTransactionID = new ThreadLocal<>(); private static Map<String, DefaultTransactionStatus> transactionObjectMap = new ConcurrentHashMap<>(); private static Map<String, Map<Object, Object>> transactionResourceMap = new ConcurrentHashMap<>(); private static Map<String, String> transactionStatusMap = new ConcurrentHashMap<>(); public static String getTransactionId() { return localTransactionID.get(); } public static void setTransactionId(String transactionId) { localTransactionID.set(transactionId); } public static void cleanup() { localTransactionID.remove(); } // Transaction resource map public static void addTxnResources(String txnID, Map<Object, Object> resources) { transactionResourceMap.put(txnID, resources); } public static Map<Object, Object> getTxnResources(String txnID) { return transactionResourceMap.get(txnID); } public static void removeTxnResources(String txnID) { transactionResourceMap.remove(txnID); } public static boolean containsTxnResources(String txnID) { return transactionResourceMap.containsKey(txnID); } // Transaction status public static void addTxnStatus(String txnID, String txnStatus) { transactionStatusMap.put(txnID, txnStatus); } public static String getTxnStatus(String txnID) { return transactionStatusMap.get(txnID); } public static void removeTxnStatus(String txnID) { transactionStatusMap.remove(txnID); } public static boolean containsTxnStatus(String txnID) { return transactionStatusMap.containsKey(txnID); } // Transaction Object public static void addTxnObject(String txnID, DefaultTransactionStatus txnObject) { transactionObjectMap.put(txnID, txnObject); } public static DefaultTransactionStatus getTxnObject(String txnID) { return transactionObjectMap.get(txnID); } public static void removeTxnObject(String txnID) { transactionObjectMap.remove(txnID); } public static boolean containsTxnObject(String txnID) { return transactionObjectMap.containsKey(txnID); } }
32.455446
106
0.724527
43849e091d30ce70abd0ad37432d320332b4c1f2
6,049
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lealone.hansql.exec.planner.torel; import java.util.List; import java.util.Map; import org.lealone.hansql.common.expression.LogicalExpression; import org.lealone.hansql.common.logical.LogicalPlan; import org.lealone.hansql.common.logical.data.Filter; import org.lealone.hansql.common.logical.data.GroupingAggregate; import org.lealone.hansql.common.logical.data.Join; import org.lealone.hansql.common.logical.data.Limit; import org.lealone.hansql.common.logical.data.LogicalOperator; import org.lealone.hansql.common.logical.data.Order; import org.lealone.hansql.common.logical.data.Project; import org.lealone.hansql.common.logical.data.Scan; import org.lealone.hansql.common.logical.data.Union; import org.lealone.hansql.common.logical.data.visitors.AbstractLogicalVisitor; import org.lealone.hansql.exec.planner.logical.DrillAggregateRel; import org.lealone.hansql.exec.planner.logical.DrillJoinRel; import org.lealone.hansql.exec.planner.logical.DrillLimitRel; import org.lealone.hansql.exec.planner.logical.DrillRel; import org.lealone.hansql.exec.planner.logical.DrillSortRel; import org.lealone.hansql.exec.planner.logical.DrillUnionRel; import org.lealone.hansql.exec.planner.logical.ScanFieldDeterminer; import org.lealone.hansql.exec.planner.logical.ScanFieldDeterminer.FieldList; import org.lealone.hansql.optimizer.plan.RelOptCluster; import org.lealone.hansql.optimizer.plan.RelOptTable; import org.lealone.hansql.optimizer.plan.RelTraitSet; import org.lealone.hansql.optimizer.plan.RelOptTable.ToRelContext; import org.lealone.hansql.optimizer.rel.InvalidRelException; import org.lealone.hansql.optimizer.rel.RelNode; import org.lealone.hansql.optimizer.rel.RelRoot; import org.lealone.hansql.optimizer.rel.type.RelDataType; import org.lealone.hansql.optimizer.rel.type.RelDataTypeFactory; import org.lealone.hansql.optimizer.rex.RexBuilder; import org.lealone.hansql.optimizer.rex.RexNode; import org.lealone.hansql.optimizer.schema.SchemaPlus; public class ConversionContext implements ToRelContext { static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ConversionContext.class); private static final ConverterVisitor VISITOR = new ConverterVisitor(); private final Map<Scan, FieldList> scanFieldLists; private final RelOptCluster cluster; public ConversionContext(RelOptCluster cluster, LogicalPlan plan) { super(); scanFieldLists = ScanFieldDeterminer.getFieldLists(plan); this.cluster = cluster; } @Override public RelOptCluster getCluster() { return cluster; } private FieldList getFieldList(Scan scan) { assert scanFieldLists.containsKey(scan); return scanFieldLists.get(scan); } public RexBuilder getRexBuilder(){ return cluster.getRexBuilder(); } public RelTraitSet getLogicalTraits(){ RelTraitSet set = RelTraitSet.createEmpty(); set.add(DrillRel.DRILL_LOGICAL); return set; } public RelNode toRel(LogicalOperator operator) throws InvalidRelException{ return operator.accept(VISITOR, this); } public RexNode toRex(LogicalExpression e){ return null; } public RelDataTypeFactory getTypeFactory(){ return cluster.getTypeFactory(); } public RelOptTable getTable(Scan scan){ FieldList list = getFieldList(scan); return null; } @Override public RelRoot expandView(RelDataType rowType, String queryString, List<String> schemaPath, List<String> viewPath) { throw new UnsupportedOperationException(); } //@Override public RelRoot expandView(RelDataType rowType, String queryString, SchemaPlus rootSchema, List<String> schemaPath) { throw new UnsupportedOperationException(); } private static class ConverterVisitor extends AbstractLogicalVisitor<RelNode, ConversionContext, InvalidRelException>{ @Override public RelNode visitScan(Scan scan, ConversionContext context){ //return BaseScanRel.convert(scan, context); return null; } @Override public RelNode visitFilter(Filter filter, ConversionContext context) throws InvalidRelException{ //return BaseFilterRel.convert(filter, context); return null; } @Override public RelNode visitProject(Project project, ConversionContext context) throws InvalidRelException{ //return BaseProjectRel.convert(project, context); return null; } @Override public RelNode visitOrder(Order order, ConversionContext context) throws InvalidRelException{ return DrillSortRel.convert(order, context); } @Override public RelNode visitJoin(Join join, ConversionContext context) throws InvalidRelException{ return DrillJoinRel.convert(join, context); } @Override public RelNode visitLimit(Limit limit, ConversionContext context) throws InvalidRelException{ return DrillLimitRel.convert(limit, context); } @Override public RelNode visitUnion(Union union, ConversionContext context) throws InvalidRelException{ return DrillUnionRel.convert(union, context); } @Override public RelNode visitGroupingAggregate(GroupingAggregate groupBy, ConversionContext context) throws InvalidRelException { return DrillAggregateRel.convert(groupBy, context); } } }
35.374269
120
0.780294
7ac36d8d2473a9b2eb419a7b1eeca6cb6a07bbfe
223
package com.extracraftx.minecraft.extradoors.interfaces; public interface TeleportableLivingEntity{ public boolean teleport(double x, double y, double z, float yaw, float pitch, boolean particles, int maxDrop); }
31.857143
114
0.784753
531f95a4b581b3af557256d98528924713a84b3c
10,172
/* * Copyright 2020-2020 Exactpro (Exactpro Systems 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.exactpro.remotehand.web; import com.exactpro.remotehand.DriverPoolProvider; import com.exactpro.remotehand.RhConfigurationException; import com.exactpro.remotehand.sessions.SessionContext; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.ie.InternetExplorerOptions; import org.openqa.selenium.logging.LogType; import org.openqa.selenium.logging.LoggingPreferences; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class WebDriverPoolProvider implements DriverPoolProvider<WebDriverWrapper> { private static final Logger logger = LoggerFactory.getLogger(WebDriverPoolProvider.class); private final Queue<WebDriverWrapper> webDriverPool = new ConcurrentLinkedQueue<>(); public void initDriverPool() { WebConfiguration config = WebConfiguration.getInstance(); int i = config.getDriverPoolSize(); try { if (i > 0) for (int j = 0; j < i; j++) webDriverPool.add(createDriverStorage(config)); } catch (RhConfigurationException e) { logger.warn("Could not initialize driver pool", e); } } @Override public WebDriverWrapper createDriverWrapper(SessionContext context) throws RhConfigurationException { WebConfiguration config = WebConfiguration.getInstance(); WebDriverWrapper webDriverWrapper = webDriverPool.poll(); if (webDriverWrapper == null || !isDriverAlive(webDriverWrapper.getDriver())) webDriverWrapper = createDriverStorage(config); return webDriverWrapper; } private WebDriverWrapper createDriverStorage(WebConfiguration configuration) throws RhConfigurationException { DesiredCapabilities dc = createDesiredCapabilities(configuration); WebDriver driver; File downloadDir = WebUtils.createDownloadDirectory(); try { switch (configuration.getBrowserToUse()) { case IE: driver = createIeDriver(configuration, dc); break; case EDGE: driver = createEdgeDriver(configuration, dc); break; case CHROME: driver = createChromeDriver(configuration, dc, downloadDir, false); break; case CHROME_HEADLESS: driver = createChromeDriver(configuration, dc, downloadDir,true); break; case FIREFOX_HEADLESS: driver = createFirefoxDriver(configuration, dc, downloadDir, true); break; default: driver = createFirefoxDriver(configuration, dc, downloadDir, false); } } catch (RhConfigurationException e) { WebUtils.deleteDownloadDirectory(downloadDir); throw e; } return new WebDriverWrapper(driver, downloadDir); } @Override public void clearDriverPool() { WebDriverWrapper webDriverWrapper; while ((webDriverWrapper = webDriverPool.poll()) != null) { WebUtils.deleteDownloadDirectory(webDriverWrapper.getDownloadDir()); closeDriver(null, webDriverWrapper); } } public boolean isDriverAlive(WebDriver driver) { if (driver == null) return false; try { return driver.getWindowHandles().size() > 0; } catch (WebDriverException e) { logger.warn("Error received as result of checking browser state", e); return false; } } // Notes about driver initialization: // 1. For some driver's constructors we will get an error if we pass null as DesiredCapabilities. // 2. Constructor can throw RuntimeException in case of driver file absence. private InternetExplorerDriver createIeDriver(WebConfiguration cfg, DesiredCapabilities dc) throws RhConfigurationException { try { System.setProperty("webdriver.ie.driver", cfg.getIeDriverFileName()); return dc != null ? new InternetExplorerDriver(new InternetExplorerOptions(dc)) : new InternetExplorerDriver(); } catch (Exception e) { throw new RhConfigurationException("Could not create Internet Explorer driver", e); } } private EdgeDriver createEdgeDriver(WebConfiguration cfg, DesiredCapabilities dc) throws RhConfigurationException { try { System.setProperty("webdriver.edge.driver", cfg.getEdgeDriverFileName()); EdgeOptions options = new EdgeOptions(); if (dc != null) { for (Map.Entry<String, Object> capability : dc.asMap().entrySet()) options.setCapability(capability.getKey(), capability.getValue()); } return new EdgeDriver(options); } catch (Exception e) { throw new RhConfigurationException("Could not create Microsoft Edge driver", e); } } private ChromeDriver createChromeDriver(WebConfiguration cfg, DesiredCapabilities dc, File downloadDir, boolean headlessMode) throws RhConfigurationException { try { System.setProperty("webdriver.chrome.driver", cfg.getChromeDriverFileName()); ChromeOptions options = new ChromeOptions(); if (headlessMode) { options.setHeadless(true); options.addArguments("window-size=1920x1080"); } options.addArguments("--no-sandbox", "--ignore-ssl-errors=yes", "--ignore-certificate-errors"); String binaryParam = cfg.getBinary(); if (binaryParam != null && !binaryParam.isEmpty()) { File binaryFile = new File(binaryParam); if (binaryFile.exists()) options.setBinary(binaryParam); } Map<String, Object> prefs = new HashMap<>(3); prefs.put("profile.default_content_settings.popups", "0"); prefs.put("profile.content_settings.exceptions.clipboard", createClipboardSettingsChrome(cfg.isReadClipboardPermissions())); prefs.put("download.default_directory", downloadDir.getAbsolutePath()); options.setExperimentalOption("prefs", prefs); options.setExperimentalOption("w3c", cfg.isEnableW3C()); if (dc != null) { for (Map.Entry<String, Object> capability : dc.asMap().entrySet()) options.setCapability(capability.getKey(), capability.getValue()); } return new ChromeDriver(ChromeDriverService.createDefaultService(), options); } catch (Exception e) { throw new RhConfigurationException("Could not create Chrome driver", e); } } public static Map<String, Object> createClipboardSettingsChrome(boolean enabled) { Map<String,Object> map = new HashMap<>(); map.put("last_modified", String.valueOf(System.currentTimeMillis())); //0 - default, 1 - enable, 2 - disable map.put("setting", enabled ? 1 : 2); return Collections.singletonMap("[*.],*", map); } private FirefoxDriver createFirefoxDriver(WebConfiguration cfg, DesiredCapabilities dc, File downloadDir, boolean headlessMode) throws RhConfigurationException { try { System.setProperty("webdriver.gecko.driver", cfg.getFirefoxDriverFileName()); FirefoxOptions options = new FirefoxOptions(); if (headlessMode) { options.setHeadless(true); options.addArguments("--width=1920"); options.addArguments("--height=1080"); } //Use for the default download directory the last folder specified for a download options.addPreference("browser.download.folderList", 2); //Set the last directory used for saving a file from the "What should (browser) do with this file?" dialog. options.addPreference("browser.download.dir", downloadDir.getAbsolutePath()); //This is true by default. options.addPreference("browser.download.useDownloadDir", true); if (dc != null) { for (Map.Entry<String, Object> capability : dc.asMap().entrySet()) options.setCapability(capability.getKey(), capability.getValue()); } return new FirefoxDriver(options); } catch (Exception e) { throw new RhConfigurationException("Could not create Firefox driver", e); } } private DesiredCapabilities createDesiredCapabilities(WebConfiguration cfg) { DesiredCapabilities dc = new DesiredCapabilities(); if (cfg.isProxySettingsSet()) dc.setCapability(CapabilityType.PROXY, createProxySettings(cfg)); if (cfg.isDriverLoggingEnabled()) dc.setCapability(CapabilityType.LOGGING_PREFS, createLoggingPreferences(cfg)); return dc; } private Proxy createProxySettings(WebConfiguration cfg) { Proxy proxy = new Proxy(); proxy.setHttpProxy(cfg.getHttpProxySetting()); proxy.setSslProxy(cfg.getSslProxySetting()); proxy.setFtpProxy(cfg.getFtpProxySetting()); proxy.setSocksProxy(cfg.getSocksProxySetting()); proxy.setNoProxy(cfg.getNoProxySetting()); return proxy; } private LoggingPreferences createLoggingPreferences(WebConfiguration cfg) { LoggingPreferences preferences = new LoggingPreferences(); preferences.enable(LogType.BROWSER, cfg.getBrowserLoggingLevel()); preferences.enable(LogType.DRIVER, cfg.getDriverLoggingLevel()); preferences.enable(LogType.PERFORMANCE, cfg.getPerformanceLoggingLevel()); preferences.enable(LogType.CLIENT, cfg.getClientLoggingLevel()); return preferences; } @Override public void closeDriver(String sessionId, WebDriverWrapper driver) { try { driver.getDriver().quit(); } catch (Exception e) { logger.error("Error while closing driver", e); } } }
32.812903
160
0.750492
18f58cb4643076cadc65bae6dd5c02fb77a65585
966
package com.lym.security.code.img.propertities; import com.lym.security.code.consts.ValidateCodeConsts; import com.lym.security.code.propertities.ValidateCodeProperties; import org.springframework.boot.context.properties.ConfigurationProperties; /** * 验证码配置项 * * @author lym * @since 1.0 */ @ConfigurationProperties(prefix = ValidateCodeConsts.CONFIG_PREFIX + ".image") public class ImageCodeProperties extends ValidateCodeProperties { /** * 图片宽 */ private int width = 120; /** * 图片高,推荐为宽的 1 / 3 */ private int height = 40; ImageCodeProperties() { // 默认长度为 4 setLength(4); setParameterName(ValidateCodeConsts.IMAGE); } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } }
19.714286
78
0.646998
25bcf5e51c41eb3e65993afb926af5c7bb539179
2,170
package com.tvd12.ezyfox.testing.reflect; import java.util.Comparator; import java.util.stream.Collectors; import org.testng.annotations.Test; import com.tvd12.ezyfox.reflect.EzyClassTree; public class EzyClassTreeTest { @Test public void test() { EzyClassTree tree = new EzyClassTree(); tree = new EzyClassTree(Ex2Branch2Exception.class); tree.add(Ex2Branch2Exception.class); tree.add(Ex2Branch1Exception.class); tree.add(Ex1Branch2Exception.class); tree.add(Ex1Branch1Exception.class); tree.add(Branch2Exception.class); tree.add(Branch1Exception.class); tree.add(Exception.class); tree.add(RootException.class); tree.add(RootException.class); System.out.println(tree); System.out.println("\n================================"); System.out.println(String.join("\n", tree.toList().stream() .map(t -> t.toString()) .collect(Collectors.toList()))); } public static class Compa implements Comparator<Class<?>> { @Override public int compare(Class<?> a, Class<?> b) { if(a == b) return 0; if(a.isAssignableFrom(b)) return 1; if(b.isAssignableFrom(a)) return -1; return a.getName().compareTo(b.getName()); } } public static class Ex2Branch2Exception extends Branch2Exception { private static final long serialVersionUID = -6068208036555261492L; } public static class Ex1Branch2Exception extends Branch2Exception { private static final long serialVersionUID = -6068208036555261492L; } public static class Ex2Branch1Exception extends Branch1Exception { private static final long serialVersionUID = -6068208036555261492L; } public static class Ex1Branch1Exception extends Branch1Exception { private static final long serialVersionUID = -6068208036555261492L; } public static class Branch2Exception extends RootException { private static final long serialVersionUID = -6068208036555261492L; } public static class Branch1Exception extends RootException { private static final long serialVersionUID = -6068208036555261492L; } public static class RootException extends Exception { private static final long serialVersionUID = -6068208036555261492L; } }
28.181818
69
0.745161
39501d216869d406445fb27aca79888ee124f1b0
523
package com.obiwanwheeler.creators; import java.util.Scanner; public class Creator { Scanner scanner = new Scanner(System.in); public void startCreate(){ System.out.println("would you like to make a deck (d), or add new cards to existing ones (c)?"); String userChoice = scanner.next(); switch (userChoice){ case "d": new DeckCreator().createNewDeck(); break; case "c": new CardCreator().doCardCreation(); break; } } }
26.15
104
0.590822
732508926da1c0be5552dc2249abf2032871e928
1,652
package com.example.acer.shopping.entity; import java.sql.Timestamp; import java.util.Date; public class Cart { //cartId,userId,collectNumber,collectTime /* public Cart(int cartId, int userId, int collectNumber, Timestamp collectTime) { super(); this.cartId = cartId; this.userId = userId; this.collectNumber = collectNumber; this.collectTime = collectTime; } */ private int cartId; public Cart(int cartId, Product product, int userId, int collectNumber, Timestamp collectTime) { super(); this.cartId = cartId; this.product= product; this.userId = userId; this.collectNumber = collectNumber; this.collectTime = collectTime; } public Cart(int cartId,int userId, int collectNumber, Timestamp collectTime) { this.cartId = cartId; this.userId = userId; this.collectNumber = collectNumber; this.collectTime = collectTime; } public int getCartId() { return cartId; } public void setCartId(int cartId) { this.cartId = cartId; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getCollectNumber() { return collectNumber; } public void setCollectNumber(int collectNumber) { this.collectNumber = collectNumber; } public Date getCollectTime() { return collectTime; } public void setCollectTime(Timestamp collectTime) { this.collectTime = collectTime; } private Product product; private int userId; private int collectNumber; private Timestamp collectTime; public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } }
19.209302
72
0.720339
9aaa03ef8df68e3fc4291afc05e9f7a619363fe0
1,221
package livelance.app.support; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; import livelance.app.model.Location; import livelance.app.web.controller.ApiLocationController; import livelance.app.web.resource.LocationResource; @Component public class LocationResourceAsm extends ResourceAssemblerSupport<Location, LocationResource>{ public LocationResourceAsm() { super(ApiLocationController.class, LocationResource.class); } public LocationResource toResource(Location location) { LocationResource res = new LocationResource(); res.setCountry(location.getCountry()); res.setCity(location.getCity()); res.setStreet(location.getStreet()); res.setNumber(location.getNumber()); res.setLatitude(location.getLatitude()); res.setLongitude(location.getLongitude()); res.setRid(location.getId()); res.add(linkTo(methodOn(ApiLocationController.class). get(location.getId(), location.getDeal().getId())).withSelfRel()); return res; } }
35.911765
95
0.781327
e0cb122e3cb40ae83449598858187247f84e0070
496
package com.cn.pojo; import lombok.Data; import java.util.List; /** * 树数据封装类 * * @author chen * @date 2018-01-02 17:56 */ @Data public class MenuDTO { public static Long rootId = 0L; protected Long id; /** 名称 */ protected String name; /** 父id */ protected Long parentId; /** 链接地址 */ protected String url; /** 是否勾选 */ protected Boolean checked; /** 图标 */ protected String icon; /** 子菜单 */ protected List<MenuDTO> children; }
13.052632
37
0.582661
e2faf07dbf24273c7a4db5e1e65e70c770f7f439
506
package com.supervisor.sdk.pgsql.statement; import com.supervisor.sdk.datasource.Base; import java.util.Arrays; public final class PgDropColumnStatement extends PgUpdateSchemaStatement { public PgDropColumnStatement(Base base, final String entity, final String column) { super( base, script(column, entity), Arrays.asList() ); } private static String script(String column, String entity) { return String.format("ALTER TABLE %s DROP COLUMN IF EXISTS %s;", entity, column); } }
24.095238
84
0.745059
6c54585e1b2b73e70313834fd9bfb9daa75eb3e9
9,319
package com.uiresource.cookit; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import com.uiresource.cookit.modelo.Marca; import com.uiresource.cookit.modelo.Respuesta; import com.uiresource.cookit.recycler.Vestimenta; import com.uiresource.cookit.utilidades.ClienteRest; import com.uiresource.cookit.utilidades.OnTaskCompleted; import com.uiresource.cookit.utilidades.Util; import java.util.List; public class NuevaVestimentaFragment extends Fragment implements OnTaskCompleted, View.OnClickListener { private static final int INGRESAR_VESTIMENTA = 1; private static final int SOLICITUD_MARCAS = 2; private Context globalContext = null; private Spinner color; private Spinner estilo; private Spinner genero; private Spinner tipo; private Spinner talla; private Spinner marca; private List<Marca> marcas; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActivity().getApplicationContext(); globalContext=this.getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_nueva_vestimenta, container, false); } @Override public void onResume() { super.onResume(); ((Button) this.getActivity().findViewById(R.id.ves_reg_vestimenta)).setOnClickListener(this); color = (Spinner) this.getActivity().findViewById(R.id.ves_color); ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this.getActivity(), R.array.Color, R.layout.support_simple_spinner_dropdown_item); color.setAdapter(adapter1); estilo = (Spinner) this.getActivity().findViewById(R.id.ves_estilo); ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this.getActivity(), R.array.Estilo, R.layout.support_simple_spinner_dropdown_item); estilo.setAdapter(adapter2); genero = (Spinner) this.getActivity().findViewById(R.id.ves_genero); ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this.getActivity(), R.array.GeneroV, R.layout.support_simple_spinner_dropdown_item); genero.setAdapter(adapter3); tipo = (Spinner) this.getActivity().findViewById(R.id.ves_tipo); ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(this.getActivity(), R.array.Tipo, R.layout.support_simple_spinner_dropdown_item); tipo.setAdapter(adapter4); talla = (Spinner) this.getActivity().findViewById(R.id.ves_talla); ArrayAdapter<CharSequence> adapter5 = ArrayAdapter.createFromResource(this.getActivity(), R.array.Talla, R.layout.support_simple_spinner_dropdown_item); talla.setAdapter(adapter5); // marca = (Spinner) this.getActivity().findViewById(R.id.ves_marca); // ArrayAdapter<CharSequence> adapter6 = ArrayAdapter.createFromResource(this.getActivity(), R.array.generos, R.layout.support_simple_spinner_dropdown_item); // marca.setAdapter(adapter6); consultaListadoMarcas(); //((Button) this.getActivity().findViewById(R.id.NEbtn_reg)).setOnClickListener(this); } @Override public void onTaskCompleted(int idSolicitud, String result) { switch (idSolicitud){ case INGRESAR_VESTIMENTA: if(result!=null){ try { Respuesta res = ClienteRest.getResult(result, Respuesta.class); Util.showMensaje(globalContext, res.getMensaje()); if (res.getCodigo() == 1) { ((EditText) this.getActivity().findViewById(R.id.ves_descripcion)).setText(""); ((EditText) this.getActivity().findViewById(R.id.ves_precio)).setText(""); ((EditText) this.getActivity().findViewById(R.id.ves_imagen)).setText(""); onResume(); //this.getActivity().finish(); } }catch (Exception e){ e.printStackTrace(); Util.showMensaje(globalContext,R.string.msj_error_clienrest_formato); } }else Util.showMensaje(globalContext,R.string.msj_error_clienrest); break; case SOLICITUD_MARCAS: if(result!=null){ try { List<Marca> res = ClienteRest.getResults(result, Marca.class); //Util.showMensaje(globalContext, res.get(0).getNombre()+"<<<<<"); marcas=res; marca = (Spinner) this.getActivity().findViewById(R.id.ves_marca); marca.setAdapter(new ArrayAdapter<Marca>(globalContext, android.R.layout.simple_spinner_item, marcas)); }catch (Exception e){ Log.i("MainActivity", "Error en carga de categorias", e); Util.showMensaje(globalContext, R.string.msj_error_clienrest_formato); } }else Util.showMensaje(globalContext, R.string.msj_error_clienrest); break; default: break; } } private void confirmarGuardarVes() { String pregunta = "Esto seguro de realizar el registro?"; new AlertDialog.Builder(globalContext) .setTitle(getResources().getString(R.string.msj_confirmacion)) .setMessage(pregunta) .setNegativeButton(android.R.string.cancel, null)//sin listener .setPositiveButton(getResources().getString(R.string.lbl_aceptar), new DialogInterface.OnClickListener() {//un listener que al pulsar, solicite el WS de Transsaccion @Override public void onClick(DialogInterface dialog, int which){ guardarVes(); } }) .show(); } private void guardarVes(){ String descripcion = ((EditText) this.getActivity().findViewById(R.id.ves_descripcion)).getText().toString(); String col = color.getSelectedItem().toString(); String est = estilo.getSelectedItem().toString(); String gen = genero.getSelectedItem().toString(); String tip = tipo.getSelectedItem().toString(); String tal =talla.getSelectedItem().toString(); String precio1 = ((EditText) this.getActivity().findViewById(R.id.ves_precio)).getText().toString(); Double precio = Double.parseDouble(precio1); String ima= ((EditText) this.getActivity().findViewById(R.id.ves_imagen)).getText().toString(); Marca mar = (Marca) marca.getSelectedItem(); try { String URL = Util.URL_SRV + "vestimenta/newvestimenta"; ClienteRest clienteRest = new ClienteRest(this); Vestimenta vestimenta = new Vestimenta(); vestimenta.setDescripcion(descripcion); vestimenta.setColor(col); vestimenta.setEstilo(est); vestimenta.setGenero(gen); vestimenta.setTipo(tip); vestimenta.setTalla(tal); vestimenta.setPrecio(precio); vestimenta.setImagen(ima); vestimenta.setMarca(mar); SharedPreferences miPreferencia = this.getActivity().getSharedPreferences("MisPreferencias", globalContext.MODE_PRIVATE); String idEmpresa = miPreferencia.getString("idEmpresa","No de pudo obtener"); clienteRest.doPost2(URL, vestimenta,"?id="+idEmpresa , INGRESAR_VESTIMENTA, true); }catch(Exception e){ Util.showMensaje(globalContext, R.string.msj_error_clienrest); e.printStackTrace(); } } protected void consultaListadoMarcas() { try { String URL = Util.URL_SRV + "marca/getmarcas"; ClienteRest clienteRest = new ClienteRest(this); clienteRest.doGet(URL, "", SOLICITUD_MARCAS, true); }catch(Exception e){ Util.showMensaje(globalContext, R.string.msj_error_clienrest); e.printStackTrace(); } } @Override public void onClick(View view) { switch (view.getId()){ case R.id.ves_reg_vestimenta: confirmarGuardarVes(); break; default: break; } } }
46.133663
165
0.619594
c1e96eb9a9edc3f9dcae9fd5ab11055b87736b3e
3,308
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.liferay.training.gradebook.service.impl; import com.liferay.portal.aop.AopService; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.util.OrderByComparator; import com.liferay.training.gradebook.model.Assignment; import com.liferay.training.gradebook.service.base.AssignmentServiceBaseImpl; import java.util.List; import org.osgi.service.component.annotations.Component; /** * The implementation of the assignment remote service. * * <p> * All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the <code>com.liferay.training.gradebook.service.AssignmentService</code> interface. * * <p> * This is a remote service. Methods of this service are expected to have security checks based on the propagated JAAS credentials because this service can be accessed remotely. * </p> * * @author Brian Wing Shun Chan * @see AssignmentServiceBaseImpl */ @Component( property = { "json.web.service.context.name=gradebook", "json.web.service.context.path=Assignment" }, service = AopService.class ) public class AssignmentServiceImpl extends AssignmentServiceBaseImpl { public Assignment addAssignment( Assignment assignment, ServiceContext serviceContext) throws PortalException { // TODO: ADD SECURITY CHECK! return assignmentLocalService.addAssignment(assignment, serviceContext); } public Assignment createAssignment() { // TODO: ADD SECURITY CHECK! return assignmentLocalService.createAssignment(0); } public Assignment deleteAssignment(long assignmentId) throws PortalException { // TODO: ADD SECURITY CHECK! return assignmentLocalService.deleteAssignment(assignmentId); } public Assignment getAssignment(long assignmentId) throws PortalException { // TODO: ADD SECURITY CHECK! return assignmentLocalService.getAssignment(assignmentId); } public List<Assignment> getAssignmentsByKeywords( long groupId, String keywords, int start, int end, int status, OrderByComparator<Assignment> orderByComparator) { return assignmentLocalService.getAssignmentsByKeywords( groupId, keywords, start, end, status, orderByComparator); } public long getAssignmentsCountByKeywords( long groupId, String keywords, int status) { return assignmentLocalService.getAssignmentsCountByKeywords( groupId, keywords, status); } public Assignment updateAssignment( Assignment assignment, ServiceContext serviceContext) throws PortalException { // TODO: ADD SECURITY CHECK! return assignmentLocalService.updateAssignment( assignment, serviceContext); } }
31.207547
223
0.784764
4f518a4506ff6e546a923a4f18e13bfa20fc51c4
18,737
package com.aware; import android.Manifest; import android.content.ContentValues; import android.content.Intent; import android.content.pm.PackageManager; import android.database.ContentObserver; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteException; import android.net.Uri; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.provider.CallLog.Calls; import android.support.v4.content.ContextCompat; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import com.aware.providers.Communication_Provider; import com.aware.providers.Communication_Provider.Calls_Data; import com.aware.providers.Communication_Provider.Messages_Data; import com.aware.ui.PermissionsHandler; import com.aware.utils.Aware_Sensor; import com.aware.utils.Encrypter; /** * Capture users' communications (calls and messages) events * @author denzil * */ public class Communication extends Aware_Sensor { /** * Logging tag (default = "AWARE::Communication") */ public static String TAG = "AWARE::Communication"; /** * Broadcasted event: call accepted by the user */ public static final String ACTION_AWARE_CALL_ACCEPTED = "ACTION_AWARE_CALL_ACCEPTED"; /** * Broadcasted event: phone is ringing */ public static final String ACTION_AWARE_CALL_RINGING = "ACTION_AWARE_CALL_RINGING"; /** * Broadcasted event: call unanswered */ public static final String ACTION_AWARE_CALL_MISSED = "ACTION_AWARE_CALL_MISSED"; /** * Broadcasted event: call attempt by the user */ public static final String ACTION_AWARE_CALL_MADE = "ACTION_AWARE_CALL_MADE"; /** * Broadcasted event: user IS in a call at the moment */ public static final String ACTION_AWARE_USER_IN_CALL = "ACTION_AWARE_USER_IN_CALL"; /** * Broadcasted event: user is NOT in a call */ public static final String ACTION_AWARE_USER_NOT_IN_CALL = "ACTION_AWARE_USER_NOT_IN_CALL"; /** * Broadcasted event: message received */ public static final String ACTION_AWARE_MESSAGE_RECEIVED = "ACTION_AWARE_MESSAGE_RECEIVED"; /** * Broadcasted event: message sent */ public static final String ACTION_AWARE_MESSAGE_SENT = "ACTION_AWARE_MESSAGE_SENT"; /** * Un-official and un-supported SMS provider * BEWARE: Might have to change in the future API's as Android evolves... */ private static final Uri MESSAGES_CONTENT_URI = Uri.parse("content://sms"); private static final int MESSAGE_INBOX = 1; private static final int MESSAGE_SENT = 2; private static TelephonyManager telephonyManager = null; private static CallsObserver callsObs = null; private static MessagesObserver msgsObs = null; /** * ContentObserver for internal call log of Android. When there is a change, * it logs up-to-date information of the calls received, made and missed. * @author df * */ private class CallsObserver extends ContentObserver { public CallsObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Cursor lastCall = getContentResolver().query(Calls.CONTENT_URI, null, null, null, Calls.DATE + " DESC LIMIT 1"); if( lastCall != null && lastCall.moveToFirst() ) { Cursor exists = getContentResolver().query(Calls_Data.CONTENT_URI, null, Calls_Data.TIMESTAMP +"="+lastCall.getLong(lastCall.getColumnIndex(Calls.DATE)), null, null); if(exists == null || exists.moveToFirst() == false ) { switch(lastCall.getInt(lastCall.getColumnIndex(Calls.TYPE))) { case Calls.INCOMING_TYPE: if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_CALLS).equals("true") ) { ContentValues received = new ContentValues(); received.put(Calls_Data.TIMESTAMP, lastCall.getLong(lastCall.getColumnIndex(Calls.DATE))); received.put(Calls_Data.DEVICE_ID, Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID)); received.put(Calls_Data.TYPE, Calls.INCOMING_TYPE); received.put(Calls_Data.DURATION, lastCall.getInt(lastCall.getColumnIndex(Calls.DURATION))); received.put(Calls_Data.TRACE, Encrypter.hashPhone(getApplicationContext(), lastCall.getString(lastCall.getColumnIndex(Calls.NUMBER))) ); try { getContentResolver().insert(Calls_Data.CONTENT_URI, received); }catch( SQLiteException e ) { if(Aware.DEBUG) Log.d(TAG,e.getMessage()); }catch( SQLException e ) { if(Aware.DEBUG) Log.d(TAG,e.getMessage()); } } if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_COMMUNICATION_EVENTS).equals("true") ) { if( Aware.DEBUG ) Log.d(TAG, ACTION_AWARE_CALL_ACCEPTED); Intent callAccepted = new Intent(ACTION_AWARE_CALL_ACCEPTED); sendBroadcast(callAccepted); } break; case Calls.MISSED_TYPE: if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_CALLS).equals("true") ) { ContentValues missed = new ContentValues(); missed.put(Calls_Data.TIMESTAMP, lastCall.getLong(lastCall.getColumnIndex(Calls.DATE))); missed.put(Calls_Data.DEVICE_ID, Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID)); missed.put(Calls_Data.TYPE, Calls.MISSED_TYPE); missed.put(Calls_Data.DURATION, lastCall.getInt(lastCall.getColumnIndex(Calls.DURATION))); missed.put(Calls_Data.TRACE, Encrypter.hashPhone(getApplicationContext(), lastCall.getString(lastCall.getColumnIndex(Calls.NUMBER))) ); try { getContentResolver().insert(Calls_Data.CONTENT_URI, missed); }catch( SQLiteException e ) { if(Aware.DEBUG) Log.d(TAG,e.getMessage()); }catch( SQLException e ) { if(Aware.DEBUG) Log.d(TAG,e.getMessage()); } } if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_COMMUNICATION_EVENTS).equals("true") ) { if( Aware.DEBUG ) Log.d(TAG, ACTION_AWARE_CALL_MISSED); Intent callMissed = new Intent(ACTION_AWARE_CALL_MISSED); sendBroadcast(callMissed); } break; case Calls.OUTGOING_TYPE: if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_CALLS).equals("true") ) { ContentValues outgoing = new ContentValues(); outgoing.put(Calls_Data.TIMESTAMP, lastCall.getLong(lastCall.getColumnIndex(Calls.DATE))); outgoing.put(Calls_Data.DEVICE_ID, Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID)); outgoing.put(Calls_Data.TYPE, Calls.OUTGOING_TYPE); outgoing.put(Calls_Data.DURATION, lastCall.getInt(lastCall.getColumnIndex(Calls.DURATION))); outgoing.put(Calls_Data.TRACE, Encrypter.hashPhone(getApplicationContext(), lastCall.getString(lastCall.getColumnIndex(Calls.NUMBER))) ); try { getContentResolver().insert(Calls_Data.CONTENT_URI, outgoing); }catch( SQLiteException e ) { if(Aware.DEBUG) Log.d(TAG,e.getMessage()); }catch( SQLException e ) { if(Aware.DEBUG) Log.d(TAG,e.getMessage()); } } if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_COMMUNICATION_EVENTS).equals("true") ) { if( Aware.DEBUG ) Log.d(TAG, ACTION_AWARE_CALL_MADE); Intent callOutgoing = new Intent(ACTION_AWARE_CALL_MADE); sendBroadcast(callOutgoing); } break; } }else exists.close(); lastCall.close(); } } } private class MessagesObserver extends ContentObserver { public MessagesObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Cursor lastMessage = getContentResolver().query(MESSAGES_CONTENT_URI,null,null,null,"date DESC LIMIT 1"); if( lastMessage != null && lastMessage.moveToFirst() ) { Cursor exists = getContentResolver().query(Messages_Data.CONTENT_URI, null, Messages_Data.TIMESTAMP+"="+lastMessage.getLong(lastMessage.getColumnIndex("date")), null, null); if( exists == null || ! exists.moveToFirst() ) { switch(lastMessage.getInt(lastMessage.getColumnIndex("type"))) { case MESSAGE_INBOX: if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_MESSAGES).equals("true") ) { ContentValues inbox = new ContentValues(); inbox.put(Messages_Data.TIMESTAMP, lastMessage.getLong(lastMessage.getColumnIndex("date"))); inbox.put(Messages_Data.DEVICE_ID, Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID)); inbox.put(Messages_Data.TYPE, MESSAGE_INBOX); inbox.put(Messages_Data.TRACE, Encrypter.hashPhone(getApplicationContext(), lastMessage.getString(lastMessage.getColumnIndex("address")))); try { getContentResolver().insert(Messages_Data.CONTENT_URI, inbox); }catch( SQLiteException e ) { if(Aware.DEBUG) Log.d(TAG,e.getMessage()); }catch( SQLException e ) { if(Aware.DEBUG) Log.d(TAG,e.getMessage()); } } if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_COMMUNICATION_EVENTS).equals("true") ) { if( Aware.DEBUG ) Log.d(TAG, ACTION_AWARE_MESSAGE_RECEIVED); Intent messageReceived = new Intent(ACTION_AWARE_MESSAGE_RECEIVED); sendBroadcast(messageReceived); } break; case MESSAGE_SENT: if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_MESSAGES).equals("true") ) { ContentValues sent = new ContentValues(); sent.put(Messages_Data.TIMESTAMP, lastMessage.getLong(lastMessage.getColumnIndex("date"))); sent.put(Messages_Data.DEVICE_ID, Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID)); sent.put(Messages_Data.TYPE, MESSAGE_SENT); sent.put(Messages_Data.TRACE, Encrypter.hashPhone(getApplicationContext(), lastMessage.getString(lastMessage.getColumnIndex("address")))); try { getContentResolver().insert(Messages_Data.CONTENT_URI, sent); }catch( SQLiteException e ) { if(Aware.DEBUG) Log.d(TAG,e.getMessage()); }catch( SQLException e ) { if(Aware.DEBUG) Log.d(TAG,e.getMessage()); } } if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_COMMUNICATION_EVENTS).equals("true") ) { if( Aware.DEBUG ) Log.d(TAG, ACTION_AWARE_MESSAGE_SENT); Intent messageSent = new Intent(ACTION_AWARE_MESSAGE_SENT); sendBroadcast(messageSent); } break; } }else exists.close(); lastMessage.close(); } } } private PhoneState phoneState = new PhoneState(); private class PhoneState extends PhoneStateListener { @Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); if( Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_COMMUNICATION_EVENTS).equals("true") ) { switch(state) { case TelephonyManager.CALL_STATE_RINGING: if(Aware.DEBUG) Log.d(TAG,ACTION_AWARE_CALL_RINGING); Intent callRinging = new Intent(ACTION_AWARE_CALL_RINGING); sendBroadcast(callRinging); break; case TelephonyManager.CALL_STATE_OFFHOOK: if(Aware.DEBUG) Log.d(TAG,ACTION_AWARE_USER_IN_CALL); Intent inCall = new Intent(ACTION_AWARE_USER_IN_CALL); sendBroadcast(inCall); break; case TelephonyManager.CALL_STATE_IDLE: if(Aware.DEBUG) Log.d(TAG,ACTION_AWARE_USER_NOT_IN_CALL); Intent userFree = new Intent(ACTION_AWARE_USER_NOT_IN_CALL); sendBroadcast(userFree); break; } } } } /** * Activity-Service binder */ private final IBinder serviceBinder = new ServiceBinder(); public class ServiceBinder extends Binder { Communication getService() { return Communication.getService(); } } @Override public IBinder onBind(Intent intent) { return serviceBinder; } private static Communication commSrv = Communication.getService(); /** * Singleton instance to service * @return Communication obj */ public static Communication getService() { if( commSrv == null ) commSrv = new Communication(); return commSrv; } @Override public void onCreate() { super.onCreate(); telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); callsObs = new CallsObserver(new Handler()); msgsObs = new MessagesObserver(new Handler()); DATABASE_TABLES = Communication_Provider.DATABASE_TABLES; TABLES_FIELDS = Communication_Provider.TABLES_FIELDS; CONTEXT_URIS = new Uri[]{ Calls_Data.CONTENT_URI, Messages_Data.CONTENT_URI}; REQUIRED_PERMISSIONS.add(Manifest.permission.READ_CONTACTS); REQUIRED_PERMISSIONS.add(Manifest.permission.READ_PHONE_STATE); REQUIRED_PERMISSIONS.add(Manifest.permission.READ_CALL_LOG); REQUIRED_PERMISSIONS.add(Manifest.permission.READ_SMS); if(Aware.DEBUG) Log.d(TAG, "Communication service created!"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { boolean permissions_ok = true; for (String p : REQUIRED_PERMISSIONS) { if (ContextCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) { permissions_ok = false; break; } } if (permissions_ok) { DEBUG = Aware.getSetting(this, Aware_Preferences.DEBUG_FLAG).equals("true"); if( Aware.getSetting(getApplicationContext(),Aware_Preferences.STATUS_CALLS).equals("true") ) { getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, callsObs); }else{ getContentResolver().unregisterContentObserver(callsObs); } if( Aware.getSetting(getApplicationContext(),Aware_Preferences.STATUS_MESSAGES).equals("true") ) { getContentResolver().registerContentObserver(MESSAGES_CONTENT_URI, true, msgsObs); }else { getContentResolver().unregisterContentObserver(msgsObs); } if( Aware.getSetting(getApplicationContext(),Aware_Preferences.STATUS_COMMUNICATION_EVENTS).equals("true") ) { telephonyManager.listen(phoneState, PhoneStateListener.LISTEN_CALL_STATE); }else{ telephonyManager.listen(phoneState, PhoneStateListener.LISTEN_NONE); } if(Aware.DEBUG) Log.d(TAG, TAG + " service active..."); } else { Intent permissions = new Intent(this, PermissionsHandler.class); permissions.putExtra(PermissionsHandler.EXTRA_REQUIRED_PERMISSIONS, REQUIRED_PERMISSIONS); permissions.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(permissions); } return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); getContentResolver().unregisterContentObserver(callsObs); getContentResolver().unregisterContentObserver(msgsObs); telephonyManager.listen(phoneState, PhoneStateListener.LISTEN_NONE); if(Aware.DEBUG) Log.d(TAG, TAG + " service terminated..."); } }
47.920716
186
0.582217
00f0b732848fe132846d48451c61f5e17fd2defd
1,527
package host.kuro.onetwothree.command; import cn.nukkit.Player; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import cn.nukkit.lang.TranslationContainer; import cn.nukkit.utils.TextFormat; import host.kuro.onetwothree.Language; import host.kuro.onetwothree.OneTwoThreeAPI; public abstract class CommandBase extends Command { protected OneTwoThreeAPI api; public CommandBase(String name, OneTwoThreeAPI api) { super(name); this.description = Language.translate("commands." + name + ".description"); String usageMessage = Language.translate("commands." + name + ".usage"); this.usageMessage = usageMessage.equals("commands." + name + ".usage") ? "/" + name : usageMessage; this.setPermission("onetwothree." + name); this.api = api; } protected OneTwoThreeAPI getAPI() { return api; } public void sendUsage(CommandSender sender) { sender.sendMessage(new TranslationContainer("commands.generic.usage", this.usageMessage)); } protected boolean testIngame(CommandSender sender) { if (!(sender instanceof Player)) { //sender.sendMessage(TextFormat.RED + Language.translate("commands.generic.ingame")); return false; } return true; } protected void sendPermissionMessage(CommandSender sender) { sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.permission")); } }
35.511628
108
0.677145
ab4e20279a59395b5bbe69e2469bbc2101498ae3
360
package com.billybyte.spanjava.recordtypes.expanded.subtypes; public class TierNumberLeg { private final String tierNumberLeg; public TierNumberLeg(String tierNumberLeg) { this.tierNumberLeg = tierNumberLeg; } public String getTierNumberLeg() { return tierNumberLeg; } public String toString() { return tierNumberLeg; } }
18.947368
62
0.730556
880daa8b718c34e1728440e0267ec3f30d5b27f8
311
package net.ajmichael.projecteuler; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.assertEquals; @RunWith(JUnit4.class) public class Problem086_T { @Test public void testSolve() { assertEquals(1818, Problem086.solve()); } }
18.294118
44
0.758842
a247d9339ceab1fa31eaafa0e75614e9eac2bb5e
37,710
// Copyright 2009 Distributed Systems Group, University of Kassel // This program is distributed under the GNU Lesser General Public License (LGPL). // // This file is part of the Carpe Noctem Software Framework. // // The Carpe Noctem Software Framework is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The Carpe Noctem Software Framework is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. package de.uni_kassel.cn.planDesigner.ui.editors; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.commands.operations.IOperationHistory; import org.eclipse.core.commands.operations.IOperationHistoryListener; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.commands.operations.IUndoableOperation; import org.eclipse.core.commands.operations.ObjectUndoContext; import org.eclipse.core.commands.operations.OperationHistoryEvent; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Status; import org.eclipse.draw2d.ColorConstants; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature.Setting; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.edit.domain.IEditingDomainProvider; import org.eclipse.emf.edit.provider.ComposedAdapterFactory; import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory; import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory; import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor; import org.eclipse.emf.transaction.RecordingCommand; import org.eclipse.emf.transaction.RollbackException; import org.eclipse.emf.transaction.Transaction; import org.eclipse.emf.transaction.TransactionalEditingDomain; import org.eclipse.emf.workspace.IWorkspaceCommandStack; import org.eclipse.emf.workspace.ResourceUndoContext; import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; import org.eclipse.gef.DefaultEditDomain; import org.eclipse.gef.EditDomain; import org.eclipse.gef.EditPartFactory; import org.eclipse.gef.EditPartViewer; import org.eclipse.gef.GraphicalEditPart; import org.eclipse.gef.GraphicalViewer; import org.eclipse.gef.commands.CommandStack; import org.eclipse.gef.editparts.ScalableFreeformRootEditPart; import org.eclipse.gef.editparts.ZoomManager; import org.eclipse.gef.palette.PaletteRoot; import org.eclipse.gef.ui.actions.ZoomInAction; import org.eclipse.gef.ui.actions.ZoomOutAction; import org.eclipse.gef.ui.palette.FlyoutPaletteComposite; import org.eclipse.gef.ui.palette.FlyoutPaletteComposite.FlyoutPreferences; import org.eclipse.gef.ui.palette.PaletteViewer; import org.eclipse.gef.ui.palette.PaletteViewerProvider; import org.eclipse.gef.ui.parts.ScrollingGraphicalViewer; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IPartListener; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.views.contentoutline.ContentOutline; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.ui.views.properties.IPropertySheetPage; import org.eclipse.ui.views.properties.PropertySheet; import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage; import de.uni_kassel.cn.alica.Plan; import de.uni_kassel.cn.alica.provider.AlicaItemProviderAdapterFactory; import de.uni_kassel.cn.alica.util.AlicaSerializationHelper; import de.uni_kassel.cn.planDesigner.ui.PlanDesignerActivator; import de.uni_kassel.cn.planDesigner.ui.PlanEditorEditPartFactory; import de.uni_kassel.cn.planDesigner.ui.adapter.HiddenElementProviderFactory; import de.uni_kassel.cn.planDesigner.ui.adapter.PlanEditorHiddenElementProviderFactory; import de.uni_kassel.cn.planDesigner.ui.commands.CalculatePlanCardinalitiesCommand; import de.uni_kassel.cn.planDesigner.ui.commands.CreateUIExtensionCommmand; import de.uni_kassel.cn.planDesigner.ui.commands.EMF2GEFCommandStack; import de.uni_kassel.cn.planDesigner.ui.commands.EnsurePlanParametrisationConsistencyCommand; import de.uni_kassel.cn.planDesigner.ui.edit.PMLTransactionalEditingDomain; import de.uni_kassel.cn.planDesigner.ui.properties.ICommandStackTabbedPropertySheetPageContributor; import de.uni_kassel.cn.planDesigner.ui.properties.PMLTabbedPropertySheetPage; import de.uni_kassel.cn.planDesigner.ui.uiextensionmodel.PmlUiExtension; import de.uni_kassel.cn.planDesigner.ui.uiextensionmodel.PmlUiExtensionMap; import de.uni_kassel.cn.planDesigner.ui.uiextensionmodel.provider.PmlUIExtensionModelItemProviderAdapterFactory; import de.uni_kassel.cn.planDesigner.ui.util.CommonUtils; import de.uni_kassel.cn.planDesigner.ui.util.DiagramDropTargetListener; import de.uni_kassel.cn.planDesigner.ui.util.IEditorConstants; import de.uni_kassel.cn.planDesigner.ui.util.OverviewOutlinePage; import de.uni_kassel.cn.planDesigner.ui.util.PlanEditorUtils; import de.uni_kassel.cn.planDesigner.ui.util.PlanMapper; import de.uni_kassel.cn.planDesigner.ui.util.PlanmodellerEditorPaletteFactory; import de.uni_kassel.cn.planDesigner.ui.util.UIAwareEditor; public class PlanEditor extends EditorPart implements ICommandStackTabbedPropertySheetPageContributor, ISelectionProvider, IEditingDomainProvider, UIAwareEditor{ /** * The EditDomain which bundles the GraphicalViewer, the PaletteViewer * the commandStack. The commandStack will be a EMF2GEFCommandStack.GEFCommandStack * to work with the EMF Editing domain. * */ private EditDomain editDomain; private WorkspaceSynchronizer workspaceSynchronizer; /** * The editingDomain is the EMF side. It has the connection to the model and also * a commandStack which will be a EMF2GEFCommandStack. */ private PMLTransactionalEditingDomain editingDomain; /** * The GraphicalViewer */ private GraphicalViewer graphicalViewer; /** * The paletteViewer */ private PaletteViewer paletteViewer; private FlyoutPaletteComposite flyoutPaletteComposite; private PaletteViewerProvider provider; // We track dirty state by the last operation executed when saved private IUndoableOperation savedOperation; /** * The paletteRoot */ private PaletteRoot paletteRoot; private OverviewOutlinePage outlinePage; private PMLTabbedPropertySheetPage propertyPage; private PlanMapper planMapper; /** * The history listeners listenes to the IOperationHistory and currently determines * if this editor is affected by change of the history. The editor is affected if * the operations modified resources belonging to this editor instance. */ private final IOperationHistoryListener historyListener = new IOperationHistoryListener() { public void historyNotification(final OperationHistoryEvent event) { Set<Resource> affectedResources = ResourceUndoContext.getAffectedResources( event.getOperation()); switch(event.getEventType()) { case OperationHistoryEvent.DONE: // if (affectedResources.contains(getPlanMapper().getPlanResource()) || // affectedResources.contains(getUIExtensionResource())) { //WARNING: THIS IS HIGHLY EXPERIMENTAL! if (PlanEditorUtils.isModifiedResourceAffected(PlanEditor.this, affectedResources)) { final IUndoableOperation operation = event.getOperation(); // remove the default undo context so that we can have // independent undo/redo of independent resource changes operation.removeContext(((IWorkspaceCommandStack) getEditingDomain().getCommandStack()).getDefaultUndoContext()); // add our undo context to populate our undo menu operation.addContext(getUndoContext()); getSite().getShell().getDisplay().asyncExec(new Runnable() { public void run() { firePropertyChange(IEditorPart.PROP_DIRTY); if (propertyPage != null && propertyPage.getControl().isVisible() && propertyPage.getCurrentTab() != null) { propertyPage.refresh(); } } }); } break; case OperationHistoryEvent.UNDONE: case OperationHistoryEvent.REDONE: if (affectedResources.contains(getPlanMapper().getPlanResource()) || affectedResources.contains(getUIExtensionResource())) { // if (PlanEditorUtils.isModifiedResourceAffected(PlanEditor.this, affectedResources)) { getSite().getShell().getDisplay().asyncExec(new Runnable() { public void run() { firePropertyChange(IEditorPart.PROP_DIRTY); if (propertyPage != null && propertyPage.getControl().isVisible() && propertyPage.getCurrentTab() != null) { propertyPage.refresh(); } } }); } break; } } }; private IPartListener partListener = new IPartListener() { // If an open, unsaved file was deleted, query the user to either do a "Save As" // or close the editor. public void partActivated(IWorkbenchPart part) { if (part instanceof ContentOutline) { if (((ContentOutline)part).getCurrentPage() == getOutlinePage()) { getActionBarContributor().setActiveEditor(PlanEditor.this); } } else if (part instanceof PropertySheet) { if (((PropertySheet)part).getCurrentPage() == propertyPage) { getActionBarContributor().setActiveEditor(PlanEditor.this); handleActivate(); } } else if (part == PlanEditor.this) { handleActivate(); } } public void partBroughtToTop(IWorkbenchPart part) {} public void partClosed(IWorkbenchPart part) {} public void partDeactivated(IWorkbenchPart part) {} public void partOpened(IWorkbenchPart part) {} }; /** * The selectionListener. */ private ISelectionListener selectionListener = new ISelectionListener() { public void selectionChanged(IWorkbenchPart part, ISelection selection) { setSelection(selection); } }; private Resource uiExtensionResource; private ObjectUndoContext undoContext; /** * This keeps track of all the {@link org.eclipse.jface.viewers.ISelectionChangedListener}s that are listening to this editor. */ protected Collection<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>(); /** * This keeps track of the selection of the editor as a whole. */ protected ISelection editorSelection = StructuredSelection.EMPTY; /** * Resources that have been saved. */ protected Collection<Resource> savedResources = new ArrayList<Resource>(); /** * This is the one adapter factory used for providing views of the model. */ protected ComposedAdapterFactory adapterFactory; /** * Resources that have been changed since last activation. */ protected Collection<Resource> changedResources = new ArrayList<Resource>(); /** * Resources that have been removed since last activation. */ protected Collection<Resource> removedResources = new ArrayList<Resource>(); /** * Resources that have been moved since last activation. */ //.CUSTOM: Demonstrates the WorkspaceSynchronizer's handling of moves protected Map<Resource, URI> movedResources = new HashMap<Resource, URI>(); private HiddenElementProviderFactory hiddenElementProvider; public PlanEditor() { super(); undoContext = new ObjectUndoContext(this, IEditorConstants.PLAN_EDITOR_ID); } private IOperationHistory getOperationHistory() { return ((IWorkspaceCommandStack) getEditingDomain().getCommandStack()).getOperationHistory(); } @Override public void doSave(IProgressMonitor monitor) { WorkspaceModifyOperation operation = new WorkspaceModifyOperation() { // This is the method that gets invoked when the operation runs. public void execute(IProgressMonitor monitor) { // // Calculate the min/max cardinalities // new RecordingCommand(getEditingDomain()){ // @Override // protected void doExecute() { // getPlan().calculateCardinalities(); // } // }.execute(); getEditingDomain().getCommandStack().execute(new CalculatePlanCardinalitiesCommand(getPlan())); getEditingDomain().getCommandStack().execute(new EnsurePlanParametrisationConsistencyCommand(getPlan())); getEditingDomain().getCommandStack().execute(new RecordingCommand(getEditingDomain()){ @Override protected void doExecute() { try { // Let the planMapper save the plan getPlanMapper().save(); // Remove any corrupt extensions removeCorruptExtensions(); // Save the UI Extension resource getUIExtensionResource().save(null); Resource taskrepoResource = CommonUtils.getTaskRepository(editingDomain, true).eResource(); // Save the task repository taskrepoResource.save(AlicaSerializationHelper.getInstance().getLoadSaveOptions()); List<Resource> behaviours = PlanEditorUtils.collectModifiedResources(PlanEditor.this, false); for(Resource r : behaviours) { r.save(AlicaSerializationHelper.getInstance().getLoadSaveOptions()); } savedResources.addAll(behaviours); savedResources.add(getPlanMapper().getPlanResource()); savedResources.add(getUIExtensionResource()); savedResources.add(taskrepoResource); } catch (IOException e) { e.printStackTrace(); } catch (RollbackException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } }; try { new ProgressMonitorDialog(getSite().getShell()).run(true, false, operation); // Refresh the necessary state. // //We record the last operation executed when saved. savedOperation = getOperationHistory().getUndoOperation(getUndoContext()); // getEMFCommandStack().saveIsDone(); firePropertyChange(IEditorPart.PROP_DIRTY); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void doSaveAs() { performSaveAs(); } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { IFile file = ((IFileEditorInput)input).getFile(); if(file == null) throw new PartInitException("File for " +input +" not found"); planMapper = new PlanMapper(file); // Load the file with the editingDomain Resource resource = planMapper.load(); if(resource != null){ // TODO: We should not need that anymore due to ltk delete support checkForUnresolvableReferences(resource, true); } else throw new PartInitException("Could not load the plan"); // load the ui extension resource Resource uiExt = getEditingDomain().loadExtensionResource(resource); setUIExtensionResource(uiExt); // TODO: We should not need that anymore due to ltk delete support checkForUnresolvableReferences(uiExt, false); // Store site and Input setSite(site); setInput(input); site.getPage().addPartListener(partListener); setPartName(file.getName()); // Add selection change listener getSite().getWorkbenchWindow().getSelectionService() .addSelectionListener(getSelectionListener()); if(getGraphicalViewer() != null){ getGraphicalViewer().setContents(getResource()); } workspaceSynchronizer = new WorkspaceSynchronizer( getEditingDomain(), createSynchronizationDelegate()); getOperationHistory().addOperationHistoryListener(historyListener); // getEditingDomain().addResourceSetListener(getResourceSetListener()); } private void checkForUnresolvableReferences(Resource r, boolean displayMsg){ Map<EObject, Collection<Setting>> proxies = PlanEditorUtils.checkForUnresolvableReferences(this,r); if(!proxies.isEmpty() && displayMsg){ // Display a message to the user that some object could not be resolved final MultiStatus status = new MultiStatus( PlanDesignerActivator.PLUGIN_ID, 94, "Some referenced elements could not be found.", null); for(EObject e : proxies.keySet()){ status.add(new Status(IStatus.WARNING, PlanDesignerActivator.PLUGIN_ID, "Element " +e +" was removed because it could not be loaded.")); } Display.getCurrent().asyncExec(new Runnable(){ public void run() { ErrorDialog.openError(Display.getCurrent().getActiveShell(), "Problem loading plan", "Some elements which were contained in the plan could not be loaded\n" + "and were removed from the plan. See Details for further information", status); } }); } } private WorkspaceSynchronizer.Delegate createSynchronizationDelegate() { return new WorkspaceSynchronizer.Delegate() { public boolean handleResourceDeleted(Resource resource) { if ((resource == getResource()) && !isDirty()) { // just close now without prompt getSite().getShell().getDisplay().asyncExec(new Runnable() { public void run() { getSite().getPage().closeEditor(PlanEditor.this, false); PlanEditor.this.dispose(); } }); } else { removedResources.add(resource); } return true; } public boolean handleResourceMoved(Resource resource, URI newURI) { movedResources.put(resource, newURI); return true; } public boolean handleResourceChanged(Resource resource) { if (savedResources.contains(resource)) { savedResources.remove(resource); } else { changedResources.add(resource); } return true; } public void dispose() { removedResources.clear(); changedResources.clear(); movedResources.clear(); } }; } @Override public void dispose() { if(hiddenElementProvider != null) { hiddenElementProvider.dispose(); } // Remove selection listener getSite().getWorkbenchWindow().getSelectionService() .removeSelectionListener(getSelectionListener()); if (getActionBarContributor().getActiveEditor() == this) { getActionBarContributor().setActiveEditor(null); } workspaceSynchronizer.dispose(); // Remove the operation history stuff getOperationHistory().removeOperationHistoryListener(historyListener); getOperationHistory().dispose(getUndoContext(), true, true, true); // We are the only one who is editing the UIExtensionResource, so remove it from the // shared resourceSet getUIExtensionResource().eAdapters().clear(); getEditingDomain().getResourceSet().getResources().remove(getUIExtensionResource()); // TODO: Remove the partListener if we do support saveAs, cause otherwise there will be // no registered partListener @see setSite()! getSite().getPage().removePartListener(partListener); getResource().unload(); adapterFactory.dispose(); // getEditingDomain().removeResourceSetListener(getResourceSetListener()); super.dispose(); } @Override public boolean isDirty() { // We track the last operation executed before save was performed IUndoableOperation op = getOperationHistory().getUndoOperation(getUndoContext()); return op != savedOperation; } @Override public boolean isSaveAsAllowed() { return false; } @Override public void createPartControl(Composite parent) { this.flyoutPaletteComposite = new FlyoutPaletteComposite(parent, SWT.NONE, getSite().getPage(), getPaletteViewerProvider(), getPalettePreferences()); this.graphicalViewer = createGraphicalViewer(flyoutPaletteComposite); this.getSite().setSelectionProvider(this.graphicalViewer); this.flyoutPaletteComposite.setGraphicalControl(this.graphicalViewer.getControl()); } @Override public void setFocus() { getGraphicalViewer().getControl().setFocus(); } public EditDomain getEditDomain() { if (this.editDomain == null){ this.editDomain = new DefaultEditDomain(this){ @Override public CommandStack getCommandStack() { return PlanEditor.this.getGEFCommandStack(); } }; this.editDomain.setPaletteRoot(getPaletteRoot()); } return editDomain; } public void setEditDomain(EditDomain editDomain) { this.editDomain = editDomain; this.editDomain.setPaletteRoot(getPaletteRoot()); } /** * Returns the inner GEF commandStack of the TransactionalEditingDomain * @return */ public CommandStack getGEFCommandStack() { return ((EMF2GEFCommandStack)getEditingDomain().getCommandStack()).getCommandStack4GEF(); } /** * Returns the EMF CommandStack * @return */ public EMF2GEFCommandStack getEMFCommandStack(){ return (EMF2GEFCommandStack)getEditingDomain().getCommandStack(); } public GraphicalViewer getGraphicalViewer() { return graphicalViewer; } /** * Creates a new GraphicalViewer, configures, registers and initializes it. * * @param parent * @return */ @SuppressWarnings("deprecation") private GraphicalViewer createGraphicalViewer(Composite parent) { // Create the viewer GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); // Configure the viewer viewer.getControl().setBackground(ColorConstants.listBackground); ScalableFreeformRootEditPart root = new ScalableFreeformRootEditPart(); List<String> zoomLevels = new ArrayList<String>(3); zoomLevels.add(ZoomManager.FIT_ALL); zoomLevels.add(ZoomManager.FIT_WIDTH); zoomLevels.add(ZoomManager.FIT_HEIGHT); root.getZoomManager().setZoomLevelContributions(zoomLevels); viewer.setRootEditPart(root); // Create zoom actions IAction zoomIn = new ZoomInAction(root.getZoomManager()); IAction zoomOut = new ZoomOutAction(root.getZoomManager()); // also bind the actions to keyboard shortcuts getSite().getKeyBindingService().registerAction(zoomIn); getSite().getKeyBindingService().registerAction(zoomOut); // Hook the viewer into the EditDomain getEditDomain().addViewer(viewer); // Activate the viewer as selection provider for Eclipse getSite().setSelectionProvider(viewer); // Initializes the viewer with input viewer.setEditPartFactory(getEditPartFactory()); if(getResource() != null){ viewer.setContents(getResource()); } // Register DropTarget listener viewer.addDropTargetListener(new DiagramDropTargetListener(viewer)); final List<String> allowedIds = new ArrayList<String>(); allowedIds.add("de.uni_kassel.cn"); allowedIds.add(IWorkbenchActionConstants.MB_ADDITIONS); MenuManager menuMgr = new MenuManager(); // Add the marker where other plugins can contribute new actions menuMgr.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); viewer.setContextMenu(menuMgr); getSite().registerContextMenu(menuMgr, getSite().getSelectionProvider()); return viewer; } protected EditPartFactory getEditPartFactory() { return new PlanEditorEditPartFactory(); } @SuppressWarnings("unchecked") @Override public Object getAdapter(Class adapter) { // Handle common GEF elements if (adapter == GraphicalViewer.class || adapter == EditPartViewer.class) return getGraphicalViewer(); else if (adapter == CommandStack.class) return getEMFCommandStack(); else if(adapter == TransactionalEditingDomain.class) return getEditingDomain(); else if (adapter == EditDomain.class) return getEditDomain(); else if (adapter == IUndoContext.class) // used by undo/redo actions to get their undo context return undoContext; else if (adapter == IPropertySheetPage.class) return createPropertySheetPage(); else if (adapter == IContentOutlinePage.class) return getOutlinePage(); else if (adapter == ZoomManager.class) return ((ScalableFreeformRootEditPart)getGraphicalViewer() .getRootEditPart()).getZoomManager(); else if (adapter == UIAwareEditor.class) return this; else if(adapter == HiddenElementProviderFactory.class) { return getHiddenElementProviderFactory(); } return super.getAdapter(adapter); } private Object getHiddenElementProviderFactory() { if(hiddenElementProvider == null) { hiddenElementProvider = new PlanEditorHiddenElementProviderFactory(this); } return hiddenElementProvider; } protected PaletteRoot getPaletteRoot() { if (this.paletteRoot == null) { // Create the paletteRoot this.paletteRoot = PlanmodellerEditorPaletteFactory.createPalette(); } return this.paletteRoot; } public PaletteViewer getPaletteViewer() { return paletteViewer; } public ISelectionListener getSelectionListener() { return selectionListener; } public Resource getUIExtensionResource(){ // if(uiExtensionResource == null){ // uiExtensionResource = getEditingDomain().loadExtensionResource(getResource()); // } // // return uiExtensionResource; return uiExtensionResource; } protected void setUIExtensionResource(Resource extRes){ this.uiExtensionResource = extRes; } public EditingDomainActionBarContributor getActionBarContributor() { return (EditingDomainActionBarContributor)getEditorSite().getActionBarContributor(); } public IActionBars getActionBars() { return getActionBarContributor().getActionBars(); } /** * Returns the undoable <code>PropertySheetPage</code> for this editor. We cannot * cache this instance but we will always keep a reference to the current page * for refreshing purposes. * * @return the undoable <code>PropertySheetPage</code> */ protected TabbedPropertySheetPage createPropertySheetPage() { propertyPage = new PMLTabbedPropertySheetPage(this); return propertyPage; } // public EList<EObject> getPlanDiagram() { // return planDiagram; // } /** * Returns the palette viewer provider that is used to create palettes for the view and * the flyout. Creates one if it doesn't already exist. * * @return the PaletteViewerProvider that can be used to create PaletteViewers for * this editor * @see #createPaletteViewerProvider() */ protected final PaletteViewerProvider getPaletteViewerProvider() { if (provider == null) provider = createPaletteViewerProvider(); return provider; } /** * Creates a PaletteViewerProvider that will be used to create palettes for the view * and the flyout. * * @return the palette provider */ protected PaletteViewerProvider createPaletteViewerProvider() { return new PaletteViewerProvider(getEditDomain()); } /** * This method returns a FlyoutPreferences object that stores the flyout * settings in the Planmodeller plugin. * @return the FlyoutPreferences object used to save the flyout palette's preferences */ protected FlyoutPreferences getPalettePreferences() { return FlyoutPaletteComposite .createFlyoutPreferences(PlanDesignerActivator.getDefault().getPluginPreferences()); } public Plan getPlan() { // if(this.plan == null){ // this.plan = (Plan)getResource().getContents().get(0); // } return getPlanMapper().getPlan(); } public Resource getResource() { return getPlanMapper().getPlanResource(); } private OverviewOutlinePage getOutlinePage() { if(this.outlinePage == null) this.outlinePage = new OverviewOutlinePage(this, getGraphicalViewer()); return outlinePage; } protected void closeEditor(boolean save) { getSite().getPage().closeEditor(PlanEditor.this, save); } protected boolean performSaveAs() { SaveAsDialog dialog = new SaveAsDialog(getSite().getWorkbenchWindow().getShell()); dialog.setOriginalFile(((IFileEditorInput)getEditorInput()).getFile()); dialog.open(); IPath path= dialog.getResult(); if (path == null) return false; IWorkspace workspace = ResourcesPlugin.getWorkspace(); final IFile file= workspace.getRoot().getFile(path); if (!file.exists()) { WorkspaceModifyOperation op= new WorkspaceModifyOperation() { public void execute(final IProgressMonitor monitor) { // TODO: Perform save as here... // saveProperties(); // try { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // writeToOutputStream(out); // file.create(new ByteArrayInputStream(out.toByteArray()), true, monitor); // out.close(); // } // catch (Exception e) { // e.printStackTrace(); // } } }; try { new ProgressMonitorDialog(getSite().getWorkbenchWindow().getShell()) .run(false, true, op); } catch (Exception e) { e.printStackTrace(); } } try { setInput(new FileEditorInput(file)); getEMFCommandStack().saveIsDone(); } catch (Exception e) { e.printStackTrace(); } return true; } @Override protected void setSite(IWorkbenchPartSite site) { super.setSite(site); // TODO: Add the partListener if we do support saveAs! // getSite().getWorkbenchWindow().getPartService().addPartListener(partListener); } public String getContributorId() { return IEditorConstants.PLAN_EDITOR_ID; } public PMLTransactionalEditingDomain getEditingDomain() { if(editingDomain == null){ adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE); adapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new AlicaItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory()); // TODO: Thats not working, i.e. the domain doenst find the provider while searching // form them in creating new commands adapterFactory.addAdapterFactory(new PmlUIExtensionModelItemProviderAdapterFactory()); editingDomain = (PMLTransactionalEditingDomain)TransactionalEditingDomain.Registry.INSTANCE.getEditingDomain( IEditorConstants.PML_TRANSACTIONAL_EDITING_DOMAIN_ID); } return editingDomain; } protected ObjectUndoContext getUndoContext() { return undoContext; } public void addSelectionChangedListener(ISelectionChangedListener listener) { selectionChangedListeners.add(listener); } public ISelection getSelection() { return editorSelection; } public void removeSelectionChangedListener( ISelectionChangedListener listener) { selectionChangedListeners.remove(listener); } public void setSelection(ISelection selection) { editorSelection = selection; for (ISelectionChangedListener listener : selectionChangedListeners) { listener.selectionChanged(new SelectionChangedEvent(this, selection)); } // setStatusLineManager(selection); } public PmlUiExtensionMap getUIExtensionMap(){ // if(uiExtensionMap == null){ // uiExtensionMap = (PmlUiExtensionMap)getUIExtensionResource().getContents().get(0); // } // return uiExtensionMap; return (PmlUiExtensionMap)getUIExtensionResource().getContents().get(0); } /** * Get's the UI Extension for the given object, optionally creates one if it * doesn't exist yet. * @param obj * @param create * @return */ public PmlUiExtension getUIExtension(final EObject obj, boolean create) { final PmlUiExtensionMap map = getUIExtensionMap(); PmlUiExtension ext = map.getExtensions().get(obj); // No extension found... if (ext == null && create) { // ... create one CreateUIExtensionCommmand cmd = new CreateUIExtensionCommmand(getEditingDomain(),map,obj); getEMFCommandStack().execute(cmd); ext = cmd.getResult().toArray(new PmlUiExtension[1])[0]; } return ext; } /** * Removes corrupt extensions which would be saved within the extension file. * An extension is corrupt if the corresponding EObject is not contained in * a resource and due to that could not be loaded after opening the extension * file again. */ private void removeCorruptExtensions() throws RollbackException, InterruptedException{ getEMFCommandStack().execute(new RecordingCommand(getEditingDomain()){ @Override protected void doExecute() { PmlUiExtensionMap myUIMap = getUIExtensionMap(); // Check if extension has a corresponding EObject Set<EObject> keys = myUIMap.getExtensions().keySet(); List<EObject> toRemove = new ArrayList<EObject>(); for(EObject e : keys){ if(e == null || e.eResource() == null) toRemove.add(e); } for(EObject e : toRemove) myUIMap.getExtensions().remove(e); } },Collections.singletonMap( Transaction.OPTION_UNPROTECTED, Boolean.TRUE)); } public AdapterFactory getAdapterFactory() { return adapterFactory; } /** * Handles what to do with changed resource on activation. */ protected void handleChangedResource() { Resource res = getResource(); if (PlanEditorUtils.isModifiedResourceAffected(this, changedResources) && handleDirtyConflict()) { changedResources.removeAll(PlanEditorUtils.collectModifiedResources(this,true)); changedResources.remove(getPlanMapper().getPlanResource()); getOperationHistory().dispose(undoContext, true, true, true); firePropertyChange(IEditorPart.PROP_DIRTY); if (res.isLoaded()) { res.unload(); getUIExtensionResource().unload(); try { res.load(AlicaSerializationHelper.getInstance().getLoadSaveOptions()); getUIExtensionResource().load(null); } catch (IOException exception) { exception.printStackTrace(); } } // Refresh the graphicalViewer getGraphicalViewer().setContents(res); } } /** * Shows a dialog that asks if conflicting changes should be discarded. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected boolean handleDirtyConflict() { // return // MessageDialog.openQuestion // (getSite().getShell(), // "File conflict", //$NON-NLS-1$ // "Plan Designer has encountered a conflict with this file due to changes from " + // "externally. \n\nDo you want to discard all your changes and reload your file?"); //$NON-NLS-1$ return false; } /** * Handles activation of the editor or it's associated views. */ protected void handleActivate() { // Refresh any actions that may become enabled or disabled. setSelection(getSelection()); try { final Resource res = getResource(); if (PlanEditorUtils.isModifiedResourceAffected(this, removedResources)) { // Something has been removed, first check if the acutal pml file // was removed. If so we ask the user how to proceed if(removedResources.contains(getResource()) && handleDirtyConflict()) getSite().getPage().closeEditor(PlanEditor.this, false); else{ // Something else has been removed } } else if (movedResources.containsKey(res)) { if (savedResources.contains(res)) { getOperationHistory().dispose(undoContext, true, true, true); // change saved resource's URI and remove from map res.setURI(movedResources.remove(res)); // must change my editor input IEditorInput newInput = new FileEditorInput( WorkspaceSynchronizer.getFile(res)); setInputWithNotify(newInput); setPartName(newInput.getName()); } else { // handleMovedResource(); System.err.println("Resource moved!!"); } } else if (PlanEditorUtils.isModifiedResourceAffected(this, changedResources)) { changedResources.removeAll(savedResources); handleChangedResource(); } } finally { removedResources.clear(); changedResources.clear(); movedResources.clear(); savedResources.clear(); } } /** * Handles what to do with moved resource on activation. */ protected void handleMovedResource() { if (!isDirty() || handleDirtyConflict()) { Resource res = getResource(); URI newURI = movedResources.get(res); if (newURI != null) { if (res.isLoaded()) { // unload res.unload(); } // load the new URI in another editor res.getResourceSet().getResource(newURI, true); } } } public PlanMapper getPlanMapper() { return planMapper; } public GraphicalEditPart getRootEditPart() { return (GraphicalEditPart)getGraphicalViewer().getEditPartRegistry().get(getPlan()); } }
33.021016
161
0.745664
0122596fa339cadc35920bc108a2a85a4f3e8949
1,635
package com.tinnova.cadastroveiculos.entities; import com.tinnova.cadastroveiculos.dto.VeiculoDTO; import com.tinnova.cadastroveiculos.enumerated.MarcaVeiculo; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDateTime; @Data @NoArgsConstructor @Entity @Table(name = "veiculos") public class Veiculo implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Enumerated(value = EnumType.STRING) @Column(nullable = false) private MarcaVeiculo marca; @Column(nullable = false) private Integer ano; @Column(nullable = false) private String descricao; @Column(nullable = false) private Boolean vendido; private LocalDateTime created; private LocalDateTime updated; public Veiculo(MarcaVeiculo marca, String descricao, Integer ano) { this.marca = marca; this.descricao = descricao; this.ano = ano; } @PrePersist public void prePersist() { created = LocalDateTime.now(); } @PreUpdate public void preUpdate() { updated = LocalDateTime.now(); } public void copyNotNullProperties(VeiculoDTO veiculoDTO) { if (veiculoDTO.getMarca() != null) marca = veiculoDTO.getMarca(); if (veiculoDTO.getDescricao() != null) descricao = veiculoDTO.getDescricao(); if (veiculoDTO.getAno() != null) ano = veiculoDTO.getAno(); if (veiculoDTO.getVendido() != null) vendido = veiculoDTO.getVendido(); } }
25.546875
85
0.697248
72950d15ca9600a945b19c33fe05dccec67a7c31
391
package com.codeka.justconduits.common.impl.energy; import com.codeka.justconduits.packets.IConduitToolExternalPacket; import net.minecraft.network.FriendlyByteBuf; public class EnergyConduitToolExternalConnectionPacket implements IConduitToolExternalPacket { @Override public void encode(FriendlyByteBuf buffer) { } @Override public void decode(FriendlyByteBuf buffer) { } }
26.066667
94
0.823529
b9547d370c6afd7a42107ec6f18cdafaca2457f4
5,520
package com.haibusiness.szweb.controller; import com.haibusiness.szweb.entity.Authority; import com.haibusiness.szweb.entity.User; import com.haibusiness.szweb.exception.BadRequestException; import com.haibusiness.szweb.security.PBKDF2Encoder; import com.haibusiness.szweb.security.SecurityContextHolder; import com.haibusiness.szweb.service.AuthorityService; import com.haibusiness.szweb.service.UserService; import com.haibusiness.szweb.vo.Response; import lombok.AllArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("/user") @AllArgsConstructor public class UserController { private UserService userService; private PBKDF2Encoder pbkdf2Encoder; private AuthorityService authorityService; @Autowired @Qualifier("userServiceImpl") private UserDetailsService userDetailsServicee; /** * 查询所用用户 * @return */ @GetMapping @PreAuthorize("hasAuthority('ROLE_ADMIN')") public ResponseEntity list( @RequestParam(value="pageIndex",required=false,defaultValue="0") int pageIndex, @RequestParam(value="pageSize",required=false,defaultValue="10") int pageSize, @RequestParam(value="name",required=false,defaultValue="") String name ) { Pageable pageable = PageRequest.of(pageIndex, pageSize); Page<User> page = userService.listUsersByNameLike(name, pageable); Map model=new HashMap<>(); model.put("page", page); model.put("name","用户管理"); model.put("url", "user"); return ResponseEntity.ok().body(model); } /** * 新建/更新用户 * @param user * @return */ @PostMapping @PreAuthorize("hasAuthority('ROLE_ADMIN')") public ResponseEntity<Response> update(@RequestBody User user) { Long id=user.getId(); if(id == null) { user.setPassword(pbkdf2Encoder.encode("e10adc3949ba59abbe56e057f20f883e")); // 加密密码 }else{ User oldUser=userService.getUserById(id); oldUser.setEmail(user.getEmail()); oldUser.setEnabled(user.isEnabled()); oldUser.setAuthorities((List<Authority>)user.getAuthorities()); user=oldUser; } try { userService.saveUser(user); } catch (Exception e) { return ResponseEntity.ok().body(new Response(false, e.toString())); } return ResponseEntity.ok().body(new Response(true, "处理成功", user)); } /** * 删除用户 * @param id * @return */ @DeleteMapping(value = "/{id}") @PreAuthorize("hasAuthority('ROLE_ADMIN')") public ResponseEntity<Response> delete(@PathVariable("id") Long id) { try { userService.removeUser(id); } catch (Exception e) { return ResponseEntity.ok().body( new Response(false, e.getMessage())); } return ResponseEntity.ok().body( new Response(true, "处理成功")); } /** * 验证密码 * @param pass * @return */ @GetMapping(value = "/validPass/{pass}") public ResponseEntity validPass(@PathVariable String pass){ UserDetails userDetails = SecurityContextHolder.getUserDetails(); User user = (User)userDetailsServicee.loadUserByUsername(userDetails.getUsername()); Map map = new HashMap(); map.put("status",200); if(!user.getPassword().equals(pbkdf2Encoder.encode(pass))){ map.put("status",400); } return new ResponseEntity(map, HttpStatus.OK); } /** * 修改密码 * @param pass * @return */ @GetMapping(value = "/updatePass/{pass}") public ResponseEntity updatePass(@PathVariable String pass){ UserDetails userDetails = SecurityContextHolder.getUserDetails(); User user = (User)userDetailsServicee.loadUserByUsername(userDetails.getUsername()); if(user.getPassword().equals(pbkdf2Encoder.encode(pass))){ throw new BadRequestException("新密码不能与旧密码相同"); } user.setPassword(pbkdf2Encoder.encode(pass)); userService.updateUser(user); return new ResponseEntity(HttpStatus.OK); } /** * 修改邮箱 * @param email * @return */ @GetMapping(value = "/updateEmail/{email}") public ResponseEntity updateEmail(@PathVariable String email){ UserDetails userDetails = SecurityContextHolder.getUserDetails(); User user = (User)userDetailsServicee.loadUserByUsername(userDetails.getUsername()); user.setEmail(email); userService.updateUser(user); return new ResponseEntity(HttpStatus.OK); } }
35.612903
111
0.647826
8ee4b6ca73fc78a1ded36a1765c9283e791f3706
1,101
package sfms.rest.api.models; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; /** * Defines a Crew Member entity exposed by the Crew Member REST service. * */ @JsonInclude(JsonInclude.Include.NON_NULL) public class CrewMember { private String m_key; private String m_firstName; private String m_lastName; private List<Mission> m_missions; private List<CrewMemberState> m_states; public CrewMember() { } public String getKey() { return m_key; } public void setKey(String key) { m_key = key; } public String getFirstName() { return m_firstName; } public void setFirstName(String firstName) { m_firstName = firstName; } public String getLastName() { return m_lastName; } public void setLastName(String lastName) { m_lastName = lastName; } public List<Mission> getMissions() { return m_missions; } public void setMissions(List<Mission> missions) { m_missions = missions; } public List<CrewMemberState> getStates() { return m_states; } public void setStates(List<CrewMemberState> states) { m_states = states; } }
17.47619
72
0.732062
292b8c7bc1b3bd244556fddeacc759f11573ade0
1,993
/** * 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.streamnative.pulsar.handlers.rocketmq.inner.consumer; import com.google.common.base.Preconditions; import lombok.Getter; import org.streamnative.pulsar.handlers.rocketmq.utils.CommitLogOffsetUtils; /** * commit log offset is used to lookup message in retry logic. * it's made up by 3 components, isRetryTopic + partitionId + offset */ @Getter public final class CommitLogOffset { private final boolean isRetryTopic; private final int partitionId; private final long queueOffset; public CommitLogOffset(boolean isRetryTopic, int partitionId, long queueOffset) { Preconditions .checkArgument(partitionId >= 0 && queueOffset >= 0, "partition id and queue offset must be >= 0."); this.isRetryTopic = isRetryTopic; this.partitionId = partitionId; this.queueOffset = queueOffset; } public CommitLogOffset(long commitLogOffset) { this.isRetryTopic = CommitLogOffsetUtils.isRetryTopic(commitLogOffset); this.partitionId = CommitLogOffsetUtils.getPartitionId(commitLogOffset); this.queueOffset = CommitLogOffsetUtils.getQueueOffset(commitLogOffset); } public long getCommitLogOffset() { long commitLogOffset = CommitLogOffsetUtils.setRetryTopicTag(queueOffset, isRetryTopic); commitLogOffset = CommitLogOffsetUtils.setPartitionId(commitLogOffset, partitionId); return commitLogOffset; } }
38.326923
116
0.743101