repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
TigerMiao/NiceWeather
app/src/main/java/com/tiger_miao/niceweather/model/IChooseAreaActivityViewModel.java
306
package com.tiger_miao.niceweather.model; import java.util.List; /** * Created by tiger_miao on 15-7-2. */ public interface IChooseAreaActivityViewModel { int TYPE_PROVINCE = 0; int TYPE_CITY = 1; int TYPE_COUNTY = 2; List<String> getDataList(); void setAreaType(int areaType); }
apache-2.0
zouzhberk/ambaridemo
demo-server/src/main/java/org/apache/ambari/server/state/stack/upgrade/ServiceCheckTask.java
1419
/** * 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.ambari.server.state.stack.upgrade; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; /** * Used to represent a restart of a component. */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name="service-check") public class ServiceCheckTask extends Task { @XmlTransient private Task.Type type = Task.Type.SERVICE_CHECK; @Override public Task.Type getType() { return type; } }
apache-2.0
touwolf/mailchimp-client-api-v3
src/main/java/com/touwolf/mailchimp/model/list/ListsCampaignDefault.java
1124
package com.touwolf.mailchimp.model.list; public class ListsCampaignDefault { private String fromName; private String fromEmail; private String subject; private String language; /** * The default from name for campaigns sent to this list. */ public String getFromName() { return fromName; } public void setFromName(String fromName) { this.fromName = fromName; } /** * The default from email for campaigns sent to this list. */ public String getFromEmail() { return fromEmail; } public void setFromEmail(String fromEmail) { this.fromEmail = fromEmail; } /** * The default subject line for campaigns sent to this list. */ public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } /** * The default language for this lists’s forms. */ public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }
apache-2.0
vam-google/google-cloud-java
google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/ResourcePath.java
4937
/* * Copyright 2017 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.firestore; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.firestore.v1.DatabaseRootName; import java.util.Arrays; import java.util.Comparator; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** An immutable representation of a Firestore path to a Document or Collection. */ @AutoValue abstract class ResourcePath extends BasePath<ResourcePath> { /** * Creates a new Path. * * @param databaseName The Firestore database name. * @param segments The segments of the path relative to the root collections. */ static ResourcePath create(DatabaseRootName databaseName, ImmutableList<String> segments) { return new AutoValue_ResourcePath(segments, databaseName); } /** * Creates a new Path to the root. * * @param databaseName The Firestore database name. */ static ResourcePath create(DatabaseRootName databaseName) { return new AutoValue_ResourcePath(ImmutableList.<String>of(), databaseName); } /** * Create a new Path from its string representation. * * @param resourceName The Firestore resource name of this path. */ static ResourcePath create(String resourceName) { String[] parts = resourceName.split("/"); if (parts.length >= 6 && parts[0].equals("projects") && parts[2].equals("databases")) { String[] path = Arrays.copyOfRange(parts, 5, parts.length); return create( DatabaseRootName.of(parts[1], parts[3]), ImmutableList.<String>builder().add(path).build()); } return create(DatabaseRootName.parse(resourceName)); } /** * Returns the database name. * * @return The Firestore database name. */ abstract DatabaseRootName getDatabaseName(); /** Returns whether this path points to a document. */ boolean isDocument() { int size = getSegments().size(); return size > 0 && size % 2 == 0; } /** Returns whether this path points to a collection. */ boolean isCollection() { return getSegments().size() % 2 == 1; } /** * The Path's id (last component). * * @return The last component of the Path or null if the path points to the root. */ @Nullable String getId() { ImmutableList<String> parts = getSegments(); if (!parts.isEmpty()) { return parts.get(parts.size() - 1); } else { return null; } } /** * The Path's name (the location relative to the root of the database). * * @return The resource path relative to the root of the database. */ String getPath() { StringBuilder result = new StringBuilder(); boolean first = true; for (String part : getSegments()) { if (first) { result.append(part); first = false; } else { result.append("/").append(part); } } return result.toString(); } /** * String representation as expected by the Firestore API. * * @return The formatted name of the resource. */ String getName() { String path = getPath(); if (path.isEmpty()) { return getDatabaseName() + "/documents"; } else { return getDatabaseName() + "/documents/" + getPath(); } } /** * Compare the current path against another ResourcePath object. * * @param other The path to compare to. * @return -1 if current < other, 1 if current > other, 0 if equal */ @Override public int compareTo(@Nonnull ResourcePath other) { int cmp = this.getDatabaseName().getProject().compareTo(other.getDatabaseName().getProject()); if (cmp != 0) { return cmp; } cmp = this.getDatabaseName().getDatabase().compareTo(other.getDatabaseName().getDatabase()); if (cmp != 0) { return cmp; } return super.compareTo(other); } @Override public String toString() { return getName(); } @Override String[] splitChildPath(String name) { return name.split("/"); } @Override ResourcePath createPathWithSegments(ImmutableList<String> segments) { return create(getDatabaseName(), segments); } public static Comparator<ResourcePath> comparator() { return new Comparator<ResourcePath>() { @Override public int compare(ResourcePath left, ResourcePath right) { return left.compareTo(right); } }; } }
apache-2.0
pwrliang/MyChat
app/src/main/java/com/gl/mychatclient/MyChatApplication.java
1149
package com.gl.mychatclient; import android.app.Application; import android.os.Environment; import com.gl.mychatclient.utils.Configuration; import com.gl.mychatclient.utils.LogUtil; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; /** * Created by gl on 2016/1/31. */ public class MyChatApplication extends Application { @Override public void onCreate() { super.onCreate(); Declaration.configuration = Configuration.getInstance(this); try { File file = new File("/sdcard/ip.txt"); if (!file.exists()) return; FileInputStream in = new FileInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String ip = reader.readLine(); Declaration.SERVLET_URL = "http://" + ip + "/MyChatServer/servlet"; LogUtil.i("MyChatApplication", Declaration.SERVLET_URL); } catch (IOException e) { e.printStackTrace(); } } }
apache-2.0
noved210/WalkingQuest
unityandroidnative/library/src/main/java/walkingquest/kinematicworld/library/services/TimerService.java
3301
package walkingquest.kinematicworld.library.services; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import walkingquest.kinematicworld.library.database.DatabaseAccessor; import walkingquest.kinematicworld.library.database.databaseHandlers.NativeDataHandler; import walkingquest.kinematicworld.library.database.objects.NativeData; /** * Created by Devon on 6/15/2017. */ public class TimerService extends Service { private IBinder mBinder = new ServiceBinder(); private ServiceHandler mServiceHandler; private boolean serviceHandlerRegistered; private DatabaseAccessor databaseAccessor; private NativeData nativeData; @Override public void onCreate(){ databaseAccessor = new DatabaseAccessor(this); if((nativeData = NativeDataHandler.getNativeData(databaseAccessor.getReadableDatabase())) == null){ Log.i("Unity", "Could not find the native data"); } // bind this service to the service handler to push and pull information from it Intent intent = new Intent(this, ServiceHandler.class); bindService(intent, serviceHandlerConnection, Context.BIND_AUTO_CREATE); } @Override public int onStartCommand(Intent intent, int startId, int flags){ return START_NOT_STICKY; } @Override public void onDestroy(){ unbindService(serviceHandlerConnection); } // method invokes a push notification to the user when an event or miniquest is available // or when a miniquest has been completed and a reward can be collected public void checkTimer(){ if(serviceHandlerRegistered){ // todo remove this hardcoding long stepsRequired = 25; // push a notification about a new event being available if((mServiceHandler.getTotalSteps() % stepsRequired) == 0) { mServiceHandler.Update("NEWEVENT"); } } } // takes in specific events from the service handler public void Update(String event){ switch (event){ case "ACTIVEEVENT": checkTimer(); break; case "MINIQUESTTIMER": break; default: break; } } @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } public class ServiceBinder extends Binder { TimerService getService(){ return TimerService.this; } } private ServiceConnection serviceHandlerConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { ServiceHandler.ServiceBinder serviceBinder = (ServiceHandler.ServiceBinder) iBinder; mServiceHandler = serviceBinder.getService(); serviceHandlerRegistered = true; } @Override public void onServiceDisconnected(ComponentName componentName) { serviceHandlerRegistered = false; } }; }
apache-2.0
arnost-starosta/midpoint
tools/schrodinger/src/main/java/com/evolveum/midpoint/schrodinger/page/service/ListServicesPage.java
213
package com.evolveum.midpoint.schrodinger.page.service; import com.evolveum.midpoint.schrodinger.page.BasicPage; /** * Created by Viliam Repan (lazyman). */ public class ListServicesPage extends BasicPage { }
apache-2.0
scorpionvicky/elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/accesscontrol/DocumentSubsetReader.java
9541
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.core.security.authz.accesscontrol; import org.apache.lucene.codecs.StoredFieldsReader; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.FilterDirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.LeafReader; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.Query; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.util.BitSet; import org.apache.lucene.util.BitSetIterator; import org.apache.lucene.util.Bits; import org.apache.lucene.util.CombinedBitSet; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.common.cache.Cache; import org.elasticsearch.common.cache.CacheBuilder; import org.elasticsearch.common.logging.LoggerMessageFormat; import org.elasticsearch.common.lucene.index.SequentialStoredFieldsLeafReader; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; /** * A reader that only exposes documents via {@link #getLiveDocs()} that matches with the provided role query. */ public final class DocumentSubsetReader extends SequentialStoredFieldsLeafReader { public static DocumentSubsetDirectoryReader wrap(DirectoryReader in, DocumentSubsetBitsetCache bitsetCache, Query roleQuery) throws IOException { return new DocumentSubsetDirectoryReader(in, bitsetCache, roleQuery); } /** * Cache of the number of live docs for a given (segment, role query) pair. * This is useful because numDocs() is called eagerly by BaseCompositeReader so computing * numDocs() lazily doesn't help. Plus it helps reuse the result of the computation either * between refreshes, or across refreshes if no more documents were deleted in the * considered segment. The size of the top-level map is bounded by the number of segments * on the node. */ static final Map<IndexReader.CacheKey, Cache<Query, Integer>> NUM_DOCS_CACHE = new ConcurrentHashMap<>(); /** * Compute the number of live documents. This method is SLOW. */ private static int computeNumDocs(LeafReader reader, BitSet roleQueryBits) { final Bits liveDocs = reader.getLiveDocs(); if (roleQueryBits == null) { return 0; } else if (liveDocs == null) { // slow return roleQueryBits.cardinality(); } else { // very slow, but necessary in order to be correct int numDocs = 0; DocIdSetIterator it = new BitSetIterator(roleQueryBits, 0L); // we don't use the cost try { for (int doc = it.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = it.nextDoc()) { if (liveDocs.get(doc)) { numDocs++; } } return numDocs; } catch (IOException e) { throw new UncheckedIOException(e); } } } /** * Like {@link #computeNumDocs} but caches results. */ private static int getNumDocs(LeafReader reader, Query roleQuery, BitSet roleQueryBits) throws IOException, ExecutionException { IndexReader.CacheHelper cacheHelper = reader.getReaderCacheHelper(); // this one takes deletes into account if (cacheHelper == null) { throw new IllegalStateException("Reader " + reader + " does not support caching"); } final boolean[] added = new boolean[] { false }; Cache<Query, Integer> perReaderCache = NUM_DOCS_CACHE.computeIfAbsent(cacheHelper.getKey(), key -> { added[0] = true; return CacheBuilder.<Query, Integer>builder() // Not configurable, this limit only exists so that if a role query is updated // then we won't risk OOME because of old role queries that are not used anymore .setMaximumWeight(1000) .weigher((k, v) -> 1) // just count .build(); }); if (added[0]) { IndexReader.ClosedListener closedListener = NUM_DOCS_CACHE::remove; try { cacheHelper.addClosedListener(closedListener); } catch (AlreadyClosedException e) { closedListener.onClose(cacheHelper.getKey()); throw e; } } return perReaderCache.computeIfAbsent(roleQuery, q -> computeNumDocs(reader, roleQueryBits)); } public static final class DocumentSubsetDirectoryReader extends FilterDirectoryReader { private final Query roleQuery; private final DocumentSubsetBitsetCache bitsetCache; DocumentSubsetDirectoryReader(final DirectoryReader in, final DocumentSubsetBitsetCache bitsetCache, final Query roleQuery) throws IOException { super(in, new SubReaderWrapper() { @Override public LeafReader wrap(LeafReader reader) { try { return new DocumentSubsetReader(reader, bitsetCache, roleQuery); } catch (Exception e) { throw ExceptionsHelper.convertToElastic(e); } } }); this.bitsetCache = bitsetCache; this.roleQuery = roleQuery; verifyNoOtherDocumentSubsetDirectoryReaderIsWrapped(in); } @Override protected DirectoryReader doWrapDirectoryReader(DirectoryReader in) throws IOException { return new DocumentSubsetDirectoryReader(in, bitsetCache, roleQuery); } private static void verifyNoOtherDocumentSubsetDirectoryReaderIsWrapped(DirectoryReader reader) { if (reader instanceof FilterDirectoryReader) { FilterDirectoryReader filterDirectoryReader = (FilterDirectoryReader) reader; if (filterDirectoryReader instanceof DocumentSubsetDirectoryReader) { throw new IllegalArgumentException(LoggerMessageFormat.format("Can't wrap [{}] twice", DocumentSubsetDirectoryReader.class)); } else { verifyNoOtherDocumentSubsetDirectoryReaderIsWrapped(filterDirectoryReader.getDelegate()); } } } @Override public CacheHelper getReaderCacheHelper() { return in.getReaderCacheHelper(); } } private final DocumentSubsetBitsetCache bitsetCache; private final Query roleQuery; // we don't use a volatile here because the bitset is resolved before numDocs in the synchronized block // so any thread that see numDocs != -1 should also see the true value of the roleQueryBits (happens-before). private BitSet roleQueryBits; private volatile int numDocs = -1; private DocumentSubsetReader(final LeafReader in, DocumentSubsetBitsetCache bitsetCache, final Query roleQuery) { super(in); this.bitsetCache = bitsetCache; this.roleQuery = roleQuery; } /** * Resolve the role query and the number of docs lazily */ private void computeNumDocsIfNeeded() { if (numDocs == -1) { synchronized (this) { if (numDocs == -1) { try { roleQueryBits = bitsetCache.getBitSet(roleQuery, in.getContext()); numDocs = getNumDocs(in, roleQuery, roleQueryBits); } catch (Exception e) { throw new ElasticsearchException("Failed to load role query", e); } } } } } @Override public Bits getLiveDocs() { computeNumDocsIfNeeded(); final Bits actualLiveDocs = in.getLiveDocs(); if (roleQueryBits == null) { // If we would return a <code>null</code> liveDocs then that would mean that no docs are marked as deleted, // but that isn't the case. No docs match with the role query and therefore all docs are marked as deleted return new Bits.MatchNoBits(in.maxDoc()); } else if (actualLiveDocs == null) { return roleQueryBits; } else { // apply deletes when needed: return new CombinedBitSet(roleQueryBits, actualLiveDocs); } } @Override public int numDocs() { computeNumDocsIfNeeded(); return numDocs; } @Override public boolean hasDeletions() { // we always return liveDocs and hide docs: return true; } @Override public CacheHelper getCoreCacheHelper() { return in.getCoreCacheHelper(); } @Override public CacheHelper getReaderCacheHelper() { // Not delegated since we change the live docs return null; } @Override protected StoredFieldsReader doGetSequentialStoredFieldsReader(StoredFieldsReader reader) { return reader; } }
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Debug/Debugger-agent-dbgmodel/src/main/java/agent/dbgmodel/jna/dbgmodel/debughost/IDebugHostPublic.java
1424
/* ### * IP: GHIDRA * * 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 agent.dbgmodel.jna.dbgmodel.debughost; import com.sun.jna.platform.win32.Guid.IID; import com.sun.jna.platform.win32.WinDef.ULONGByReference; import com.sun.jna.platform.win32.WinNT.HRESULT; import agent.dbgmodel.jna.dbgmodel.DbgModelNative.LOCATION; import agent.dbgmodel.jna.dbgmodel.UnknownWithUtils.VTableIndex; public interface IDebugHostPublic extends IDebugHostBaseClass { final IID IID_IDEBUG_HOST_PUBLIC = new IID("6C597AC9-FB4D-4f6d-9F39-22488539F8F4"); enum VTIndicesX implements VTableIndex { GET_LOCATION_KIND, // GET_LOCATION, // ; public int start = VTableIndex.follow(VTIndices.class); @Override public int getIndex() { return this.ordinal() + start; } } HRESULT GetLocationKind(ULONGByReference locationKind); // LocationKind* HRESULT GetLocation(LOCATION.ByReference location); }
apache-2.0
Top-Q/jsystem
jsystem-core-projects/jsystemAgent/src/main/java/jsystem/extensions/report/xml/ReportInformation.java
943
/* * Created on Nov 30, 2005 * * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. */ package jsystem.extensions.report.xml; /** * Define an interface into test group results * * @author guy.arieli * */ public interface ReportInformation { int getNumberOfTests(); int getNumberOfTestsPass(); int getNumberOfTestsFail(); int getNumberOfTestsWarning(); String getVersion(); String getBuild(); String getUserName(); String getScenarioName(); String getSutName(); String getStation(); long getStartTime(); // long getEndTime(); String getTestClassName(int testIndex); String getTestName(int testIndex); int getTestStatus(int testIndex); String getTestSteps(int testIndex); String getTestDocumentation(int testIndex); String getTestFailCause(int testIndex); long getTestStartTime(int testIndex); long getTestEndTime(int testIndex); void refresh(); }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-run/v1alpha1/1.31.0/com/google/api/services/run/v1alpha1/model/InstanceTemplateSpec.java
2628
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.run.v1alpha1.model; /** * InstanceTemplateSpec describes the data an instance should have when created from a template. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Run Admin API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class InstanceTemplateSpec extends com.google.api.client.json.GenericJson { /** * Optional. Specification of the desired behavior of the instance. More info: * https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and- * status +optional * The value may be {@code null}. */ @com.google.api.client.util.Key private InstanceSpec spec; /** * Optional. Specification of the desired behavior of the instance. More info: * https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and- * status +optional * @return value or {@code null} for none */ public InstanceSpec getSpec() { return spec; } /** * Optional. Specification of the desired behavior of the instance. More info: * https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and- * status +optional * @param spec spec or {@code null} for none */ public InstanceTemplateSpec setSpec(InstanceSpec spec) { this.spec = spec; return this; } @Override public InstanceTemplateSpec set(String fieldName, Object value) { return (InstanceTemplateSpec) super.set(fieldName, value); } @Override public InstanceTemplateSpec clone() { return (InstanceTemplateSpec) super.clone(); } }
apache-2.0
delebash/orientdb-parent
server/src/main/java/com/orientechnologies/orient/server/handler/OServerHandlerAbstract.java
988
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.server.handler; import com.orientechnologies.orient.server.plugin.OServerPluginAbstract; /** * Deprecated, use OServerPluginAbstract instead. * * @author Luca Garulli (l.garulli--at--orientechnologies.com) * */ @Deprecated public abstract class OServerHandlerAbstract extends OServerPluginAbstract { }
apache-2.0
Sunshine-Constructing/sunshine-security
sunshine-security-service/src/main/java/com/sunshine/security/jooq/tables/records/SchemaVersionRecord.java
10914
/* * This file is generated by jOOQ. */ package com.sunshine.security.jooq.tables.records; import com.sunshine.security.jooq.tables.SchemaVersion; import java.sql.Timestamp; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record10; import org.jooq.Row10; import org.jooq.impl.UpdatableRecordImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.9.5" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class SchemaVersionRecord extends UpdatableRecordImpl<SchemaVersionRecord> implements Record10<Integer, String, String, String, String, Integer, String, Timestamp, Integer, Byte> { private static final long serialVersionUID = -690936534; /** * Setter for <code>sunshine-security.schema_version.installed_rank</code>. */ public void setInstalledRank(Integer value) { set(0, value); } /** * Getter for <code>sunshine-security.schema_version.installed_rank</code>. */ public Integer getInstalledRank() { return (Integer) get(0); } /** * Setter for <code>sunshine-security.schema_version.version</code>. */ public void setVersion(String value) { set(1, value); } /** * Getter for <code>sunshine-security.schema_version.version</code>. */ public String getVersion() { return (String) get(1); } /** * Setter for <code>sunshine-security.schema_version.description</code>. */ public void setDescription(String value) { set(2, value); } /** * Getter for <code>sunshine-security.schema_version.description</code>. */ public String getDescription() { return (String) get(2); } /** * Setter for <code>sunshine-security.schema_version.type</code>. */ public void setType(String value) { set(3, value); } /** * Getter for <code>sunshine-security.schema_version.type</code>. */ public String getType() { return (String) get(3); } /** * Setter for <code>sunshine-security.schema_version.script</code>. */ public void setScript(String value) { set(4, value); } /** * Getter for <code>sunshine-security.schema_version.script</code>. */ public String getScript() { return (String) get(4); } /** * Setter for <code>sunshine-security.schema_version.checksum</code>. */ public void setChecksum(Integer value) { set(5, value); } /** * Getter for <code>sunshine-security.schema_version.checksum</code>. */ public Integer getChecksum() { return (Integer) get(5); } /** * Setter for <code>sunshine-security.schema_version.installed_by</code>. */ public void setInstalledBy(String value) { set(6, value); } /** * Getter for <code>sunshine-security.schema_version.installed_by</code>. */ public String getInstalledBy() { return (String) get(6); } /** * Setter for <code>sunshine-security.schema_version.installed_on</code>. */ public void setInstalledOn(Timestamp value) { set(7, value); } /** * Getter for <code>sunshine-security.schema_version.installed_on</code>. */ public Timestamp getInstalledOn() { return (Timestamp) get(7); } /** * Setter for <code>sunshine-security.schema_version.execution_time</code>. */ public void setExecutionTime(Integer value) { set(8, value); } /** * Getter for <code>sunshine-security.schema_version.execution_time</code>. */ public Integer getExecutionTime() { return (Integer) get(8); } /** * Setter for <code>sunshine-security.schema_version.success</code>. */ public void setSuccess(Byte value) { set(9, value); } /** * Getter for <code>sunshine-security.schema_version.success</code>. */ public Byte getSuccess() { return (Byte) get(9); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record10 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row10<Integer, String, String, String, String, Integer, String, Timestamp, Integer, Byte> fieldsRow() { return (Row10) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row10<Integer, String, String, String, String, Integer, String, Timestamp, Integer, Byte> valuesRow() { return (Row10) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Integer> field1() { return SchemaVersion.SCHEMA_VERSION.INSTALLED_RANK; } /** * {@inheritDoc} */ @Override public Field<String> field2() { return SchemaVersion.SCHEMA_VERSION.VERSION; } /** * {@inheritDoc} */ @Override public Field<String> field3() { return SchemaVersion.SCHEMA_VERSION.DESCRIPTION; } /** * {@inheritDoc} */ @Override public Field<String> field4() { return SchemaVersion.SCHEMA_VERSION.TYPE; } /** * {@inheritDoc} */ @Override public Field<String> field5() { return SchemaVersion.SCHEMA_VERSION.SCRIPT; } /** * {@inheritDoc} */ @Override public Field<Integer> field6() { return SchemaVersion.SCHEMA_VERSION.CHECKSUM; } /** * {@inheritDoc} */ @Override public Field<String> field7() { return SchemaVersion.SCHEMA_VERSION.INSTALLED_BY; } /** * {@inheritDoc} */ @Override public Field<Timestamp> field8() { return SchemaVersion.SCHEMA_VERSION.INSTALLED_ON; } /** * {@inheritDoc} */ @Override public Field<Integer> field9() { return SchemaVersion.SCHEMA_VERSION.EXECUTION_TIME; } /** * {@inheritDoc} */ @Override public Field<Byte> field10() { return SchemaVersion.SCHEMA_VERSION.SUCCESS; } /** * {@inheritDoc} */ @Override public Integer value1() { return getInstalledRank(); } /** * {@inheritDoc} */ @Override public String value2() { return getVersion(); } /** * {@inheritDoc} */ @Override public String value3() { return getDescription(); } /** * {@inheritDoc} */ @Override public String value4() { return getType(); } /** * {@inheritDoc} */ @Override public String value5() { return getScript(); } /** * {@inheritDoc} */ @Override public Integer value6() { return getChecksum(); } /** * {@inheritDoc} */ @Override public String value7() { return getInstalledBy(); } /** * {@inheritDoc} */ @Override public Timestamp value8() { return getInstalledOn(); } /** * {@inheritDoc} */ @Override public Integer value9() { return getExecutionTime(); } /** * {@inheritDoc} */ @Override public Byte value10() { return getSuccess(); } /** * {@inheritDoc} */ @Override public SchemaVersionRecord value1(Integer value) { setInstalledRank(value); return this; } /** * {@inheritDoc} */ @Override public SchemaVersionRecord value2(String value) { setVersion(value); return this; } /** * {@inheritDoc} */ @Override public SchemaVersionRecord value3(String value) { setDescription(value); return this; } /** * {@inheritDoc} */ @Override public SchemaVersionRecord value4(String value) { setType(value); return this; } /** * {@inheritDoc} */ @Override public SchemaVersionRecord value5(String value) { setScript(value); return this; } /** * {@inheritDoc} */ @Override public SchemaVersionRecord value6(Integer value) { setChecksum(value); return this; } /** * {@inheritDoc} */ @Override public SchemaVersionRecord value7(String value) { setInstalledBy(value); return this; } /** * {@inheritDoc} */ @Override public SchemaVersionRecord value8(Timestamp value) { setInstalledOn(value); return this; } /** * {@inheritDoc} */ @Override public SchemaVersionRecord value9(Integer value) { setExecutionTime(value); return this; } /** * {@inheritDoc} */ @Override public SchemaVersionRecord value10(Byte value) { setSuccess(value); return this; } /** * {@inheritDoc} */ @Override public SchemaVersionRecord values(Integer value1, String value2, String value3, String value4, String value5, Integer value6, String value7, Timestamp value8, Integer value9, Byte value10) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); value6(value6); value7(value7); value8(value8); value9(value9); value10(value10); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached SchemaVersionRecord */ public SchemaVersionRecord() { super(SchemaVersion.SCHEMA_VERSION); } /** * Create a detached, initialised SchemaVersionRecord */ public SchemaVersionRecord(Integer installedRank, String version, String description, String type, String script, Integer checksum, String installedBy, Timestamp installedOn, Integer executionTime, Byte success) { super(SchemaVersion.SCHEMA_VERSION); set(0, installedRank); set(1, version); set(2, description); set(3, type); set(4, script); set(5, checksum); set(6, installedBy); set(7, installedOn); set(8, executionTime); set(9, success); } }
apache-2.0
mochalog/mochalog
subprojects/mochalog-bridge/java-api/src/main/java/io/mochalog/bridge/prolog/query/QuerySolution.java
2181
/* * Copyright 2017 The Mochalog Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mochalog.bridge.prolog.query; import io.mochalog.bridge.prolog.namespace.NoSuchVariableException; import io.mochalog.bridge.prolog.namespace.Namespace; import org.jpl7.Term; import java.util.Objects; /** * Solution to individual goal successfully proved * by the SWI-Prolog engine (with variable unification) */ public class QuerySolution { // Solution-level namespace containing // variable unifications private final Namespace namespace; /** * Constructor. * @param namespace Unification namespace */ public QuerySolution(Namespace namespace) { this.namespace = namespace; } /** * Get a value to which a variable corresponding to the * given name unified * @param name Variable name * @return Unified value * @throws NoSuchVariableException Variable with given name * is undefined */ public Term get(String name) throws NoSuchVariableException { return namespace.get(name); } @Override public final boolean equals(Object o) { // Early termination for self-identity if (this == o) { return true; } // null/type validation if (o != null && o instanceof QuerySolution) { QuerySolution solution = (QuerySolution) o; // Field comparisons return Objects.equals(namespace, solution.namespace); } return false; } @Override public int hashCode() { return Objects.hashCode(namespace); } }
apache-2.0
CELAR/celar-server
celar-beans/src/main/java/gr/ntua/cslab/celar/server/beans/ComponentDependency.java
588
package gr.ntua.cslab.celar.server.beans; import javax.xml.bind.annotation.XmlRootElement; /** * Represents a 'Component Dependency' entity as it is stored in celarDB * @author cmantas */ @XmlRootElement public class ComponentDependency extends ReflectiveEntity{ public int component_from_id, component_to_id; public String type; public ComponentDependency(){} public ComponentDependency(Component from, Component to, String type) { component_from_id = from.getId(); component_to_id = to.getId(); this.type=type; } }
apache-2.0
FrankBian/Java-Utils-Collection
com-gansuer-algorithm/src/main/java/com/gansuer/algorithms/sort/Insertion.java
714
package com.gansuer.algorithms.sort; /** * Created by Frank on 5/13/15. */ public class Insertion implements Sort { @Override public void sort(Comparable[] arr) { int len = arr.length; for (int i = 1; i < len; i++) { for (int j = i; j >= 1 && less(arr[j], arr[j - 1]); j--) { exchange(arr, j, j - 1); } } } public void sortX(Comparable[] arr) { int len = arr.length; for (int i = 1; i < len; i++) { Comparable cur = arr[i]; int j = i; for (; j >= 1 && less(cur, arr[j - 1]); j--) { arr[j] = arr[j - 1]; } arr[j] = cur; } } }
apache-2.0
de-jcup/egradle
egradle-plugin-main/src/test/java/de/jcup/egradle/integration/test/SpotCheckIntegrationTest.java
5175
/* * Copyright 2016 Albert Tregnaghi * * 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 de.jcup.egradle.integration.test; import static de.jcup.egradle.integration.TypeAssert.*; import org.junit.Rule; import org.junit.Test; import de.jcup.egradle.codeassist.dsl.Type; import de.jcup.egradle.integration.IntegrationTestComponents; /** * Does some spot check to data * * @author Albert Tregnaghi * */ public class SpotCheckIntegrationTest { @Rule public IntegrationTestComponents components = IntegrationTestComponents.initialize(); @Test public void jar_has_interface_copy_spec() { /* execute */ Type jarType = components.getGradleDslProvider().getType("org.gradle.api.tasks.bundling.Jar"); /* test */ assertType(jarType).hasInterface("org.gradle.api.file.CopySpec"); } @Test public void sourceset_fullname_has_mixin_parts_from_scala() { /* execute */ Type sourceSetType = components.getGradleDslProvider().getType("org.gradle.api.tasks.SourceSet"); /* test */ assertType(sourceSetType).hasName("org.gradle.api.tasks.SourceSet").hasMethod("scala", "groovy.lang.Closure"); } @Test public void sourceset_shortname_has_mixin_parts_from_scala() { /* execute */ Type sourceSetType = components.getGradleDslProvider().getType("SourceSet"); /* test */ assertType(sourceSetType).hasName("org.gradle.api.tasks.SourceSet").hasMethod("scala", "groovy.lang.Closure"); } @Test public void jar_has_zip_as_super_class__this_information_must_be_available_in_data() { /* execute */ Type jarType = components.getGradleDslProvider().getType("org.gradle.jvm.tasks.Jar"); /* test */ assertType(jarType).hasSuperType("org.gradle.api.tasks.bundling.Zip"); } @Test public void bundling_jar_has_jar_as_super_class__this_information_must_be_available_in_data() { /* execute */ Type jarType = components.getGradleDslProvider().getType("org.gradle.api.tasks.bundling.Jar"); /* test */ assertType(jarType).hasSuperType("org.gradle.jvm.tasks.Jar"); } @Test public void jar_1_has_manifest_method_itself__and_also_inherited_method_getTemporaryDirFactory_did_not_fail_alone_but_when_all() { /* execute */ Type jarType = components.getGradleDslProvider().getType("org.gradle.jvm.tasks.Jar"); /* test */ /* @formatter:off */ assertType(jarType). hasMethod("manifest", "groovy.lang.Closure"). hasMethod("getTemporaryDirFactory"); /* @formatter:on */ } /** * Special test case which did produce a loop inheratance problem. An example * * <pre> * Class A Class B * * methodA:ClassB methodB: ClassA * * -> extends Class C -> extends Class C * * Class C * * methodC: String * * <pre> * * Now it depends which of the classes will be first initialized: * * 1. Class A: will resolve Class B which will resolve * */ @Test public void jar_2_has_manifest_method_itself__and_also_inherited_method_getTemporaryDirFactory__failed_always_alone_and_also_when_all() { /* execute */ Type copyType = components.getGradleDslProvider().getType("org.gradle.api.tasks.Copy"); // jar type seems to be already loaded by former call */ Type jarType = components.getGradleDslProvider().getType("org.gradle.jvm.tasks.Jar"); /* test */ /* @formatter:off */ assertType(copyType). hasMethod("getTemporaryDirFactory"); assertType(jarType). hasMethod("manifest", "groovy.lang.Closure"). hasMethod("getTemporaryDirFactory"); /* @formatter:on */ } @Test public void jar_3_has_manifest_method_itself__and_also_inherited_method_getTemporaryDirFactory_did_not_fail_alone_but_when_all() { /* execute */ Type jarType = components.getGradleDslProvider().getType("org.gradle.jvm.tasks.Jar"); Type copyType = components.getGradleDslProvider().getType("org.gradle.api.tasks.Copy"); /* test */ /* @formatter:off */ assertType(jarType). hasMethod("manifest", "groovy.lang.Closure"). hasMethod("getTemporaryDirFactory"); assertType(copyType). hasMethod("getTemporaryDirFactory"); /* @formatter:on */ } @Test public void jar_has_inherited_property_zip64() { /* execute */ Type jarType = components.getGradleDslProvider().getType("org.gradle.jvm.tasks.Jar"); /* test */ assertType(jarType).hasSuperType().hasProperty("zip64"); } }
apache-2.0
ykim514/DashClient
dashlib/src/com/sonymobile/seeder/internal/SampleTable.java
12518
/* * Copyright (C) 2014 Sony Mobile Communications Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.sonymobile.seeder.internal; import java.nio.ByteBuffer; import java.util.ArrayList; import android.util.Log; class SampleTable { private static final boolean LOGS_ENABLED = Configuration.DEBUG || false; private static final String TAG = "SampleTable"; ByteBuffer mSttsData; ByteBuffer mCttsData; ByteBuffer mStscData; ByteBuffer mStszData; ByteBuffer mStcoData; ByteBuffer mStssData; private int mSampleCount; private int mTimeScale; private boolean mUseLongChunkOffsets; private long mDurationUs = 0; private int[] mSampleSize; private int[] mSampleDescriptionIndex; private long[] mSampleOffset; private boolean[] mSampleIsSyncSample; private long[] mSampleTimestampUs; private long[] mSampleDurationUs; public SampleTable() { } public boolean isUsingLongChunkOffsets() { return mUseLongChunkOffsets; } public void setStcoData(byte[] data) { mStcoData = ByteBuffer.wrap(data); mUseLongChunkOffsets = false; } public void setCo64Data(byte[] data) { mStcoData = ByteBuffer.wrap(data); mUseLongChunkOffsets = true; } public void setSttsData(byte[] data) { mSttsData = ByteBuffer.wrap(data); } public void setStssData(byte[] data) { mStssData = ByteBuffer.wrap(data); } public void setStscData(byte[] data) { mStscData = ByteBuffer.wrap(data); } public void setCttsData(byte[] data) { mCttsData = ByteBuffer.wrap(data); } public void setStszData(byte[] data) { mStszData = ByteBuffer.wrap(data); } public long getTimestampUs(int i) { return mSampleTimestampUs[i]; } public long getDurationUs(int i) { return mSampleDurationUs[i]; } public long getOffset(int i) { return mSampleOffset[i]; } public int getSize(int i) { return mSampleSize[i]; } public int getSampleDescriptionIndex(int i) { return mSampleDescriptionIndex[i]; } public boolean isSyncSample(int i) { return mSampleIsSyncSample[i]; } ByteBuffer getStszData() { return mStszData; } ByteBuffer getStcoData() { return mStcoData; } public boolean calculateSampleCountAndDuration() { if (mStszData == null || mStszData.capacity() == 0 || mSttsData == null || mSttsData.capacity() == 0 ) { if (LOGS_ENABLED) Log.e(TAG, "unable to calculate sample count and duration"); if (LOGS_ENABLED && mStszData == null) { Log.e(TAG, "missing mStszData"); } if (LOGS_ENABLED && mSttsData == null) { Log.e(TAG, "missing mSttsData"); } return false; } mStszData.rewind(); mSttsData.rewind(); // stsz data mStszData.getInt(); // version and flags mStszData.getInt(); // sample_size mSampleCount = mStszData.getInt(); // sample_count if (mSampleCount == 0) { return false; } // stts data mSttsData.getInt(); // version and flags int sttsEntryCount = mSttsData.getInt(); // entry_count long sttsCurrentSampleTimeToSample = 0; int sttsCurrentSampleCount = 0; int sttsCurrentSampleDelta = 0; for (int i = 0; i < sttsEntryCount; ++i) { sttsCurrentSampleCount = mSttsData.getInt(); sttsCurrentSampleDelta = mSttsData.getInt(); sttsCurrentSampleTimeToSample += sttsCurrentSampleCount * ((long)sttsCurrentSampleDelta * 1000000 / mTimeScale); } mDurationUs = sttsCurrentSampleTimeToSample; return true; } @SuppressWarnings("unused") public boolean buildSampleTable() { if (mStszData == null || mStszData.capacity() == 0 || mSttsData == null || mSttsData.capacity() == 0 || mStscData == null || mStscData.capacity() == 0 || mStcoData == null || mStcoData.capacity() == 0) { if (LOGS_ENABLED) Log.e(TAG, "unable to build sample table"); if (LOGS_ENABLED && mStszData == null) { Log.e(TAG, "missing mStszData"); } if (LOGS_ENABLED && mSttsData == null) { Log.e(TAG, "missing mSttsData"); } if (LOGS_ENABLED && mStscData == null) { Log.e(TAG, "missing mStscData"); } if (LOGS_ENABLED && mStcoData == null) { Log.e(TAG, "missing mStcoData"); } return false; } mStszData.rewind(); mSttsData.rewind(); mStscData.rewind(); mStcoData.rewind(); if (mStssData != null) { mStssData.rewind(); } if (mCttsData != null) { mCttsData.rewind(); } // stsz data mStszData.getInt(); // version and flags int sampleSize = mStszData.getInt(); // sample_size mSampleCount = mStszData.getInt(); // sample_count if (mSampleCount == 0) { return false; } mSampleSize = new int[mSampleCount]; mSampleDescriptionIndex = new int[mSampleCount]; mSampleOffset = new long[mSampleCount]; mSampleIsSyncSample = new boolean[mSampleCount]; mSampleTimestampUs = new long[mSampleCount]; mSampleDurationUs = new long[mSampleCount]; // stts data mSttsData.getInt(); // version and flags int sttsEntryCount = mSttsData.getInt(); // entry_count int sttsCurrentEntry = 1; int sttsCurrentSampleCount = mSttsData.getInt(); int sttsSampleCounter = 1; int sttsCurrentSampleDelta = mSttsData.getInt(); long sttsCurrentSampleTimeToSample = 0; // ctss data int cttsSampleCount = 0; int cttsSampleOffset = 0; int cttsCurrentEntrySampleCount = 1; if (mCttsData != null) { mCttsData.getInt(); // version and flags mCttsData.getInt(); // entry_count cttsSampleCount = mCttsData.getInt(); // sample_count cttsSampleOffset = mCttsData.getInt(); // sample_offset } // stco data mStcoData.getInt(); // version and flags int stcoEntryCount = mStcoData.getInt(); // entry_count long stcoChunkOffset = mUseLongChunkOffsets ? mStcoData.getLong() : 0xFFFFFFFFL & mStcoData.getInt(); // chunk_offset // stsc data mStscData.getInt(); // version and flags int stscEntryCount = mStscData.getInt(); // entry_count mStscData.getInt(); // first_chunk int stscSamplesPerChunk = mStscData.getInt(); // samples_per_chunk int stscSampleDescriptionIndex = mStscData.getInt(); // sample_description_index int stscNextFirstChunk = stcoEntryCount + 1; if (stscEntryCount > 1) { stscNextFirstChunk = mStscData.getInt(); } int chunkCount = 1; int stscCurrentEntryNumber = 1; int stscSamplePerChunkCount = 1; long currentSampleOffset = stcoChunkOffset; // stss data int stssEntryCount = 0; int stssSampleNumber = 0; int stssTableCount = 0; if (mStssData != null) { mStssData.getInt(); // version and flags stssEntryCount = mStssData.getInt(); // entry_count stssSampleNumber = mStssData.getInt(); // sample_number; } for (int i = 0; i < mSampleCount; i++) { // Chunk data for sample if (stscSamplePerChunkCount > stscSamplesPerChunk) { chunkCount++; stscSamplePerChunkCount = 1; // STCO should be interpreted as an unsigned int. currentSampleOffset = mUseLongChunkOffsets ? mStcoData.getLong() : 0xFFFFFFFFL & mStcoData.getInt(); } if (chunkCount == stscNextFirstChunk) { stscSamplesPerChunk = mStscData.getInt(); stscSampleDescriptionIndex = mStscData.getInt(); stscCurrentEntryNumber++; if (stscCurrentEntryNumber < stscEntryCount) { stscNextFirstChunk = mStscData.getInt(); } else { stscNextFirstChunk = Integer.MAX_VALUE; } } if (mCttsData != null) { if (cttsCurrentEntrySampleCount > cttsSampleCount) { cttsCurrentEntrySampleCount = 1; cttsSampleCount = mCttsData.getInt(); cttsSampleOffset = mCttsData.getInt(); } } // Stsz data for sample int entrySize = sampleSize; if (sampleSize == 0) { entrySize = mStszData.getInt(); // entry_size } mSampleSize[i] = entrySize; // stts data for sample if (sttsSampleCounter > sttsCurrentSampleCount) { sttsCurrentSampleCount = mSttsData.getInt(); sttsCurrentSampleDelta = mSttsData.getInt(); sttsSampleCounter = 1; sttsCurrentEntry++; if (sttsCurrentEntry > sttsEntryCount) { return false; } } mSampleTimestampUs[i] = sttsCurrentSampleTimeToSample; mSampleDurationUs[i] = (long)sttsCurrentSampleDelta * 1000000 / mTimeScale; sttsCurrentSampleTimeToSample += (long)sttsCurrentSampleDelta * 1000000 / mTimeScale; sttsSampleCounter++; // ctts data for sample if (mCttsData != null) { cttsCurrentEntrySampleCount++; mSampleTimestampUs[i] += (int)((long)cttsSampleOffset * 1000000 / mTimeScale); } mSampleDescriptionIndex[i] = stscSampleDescriptionIndex; mSampleOffset[i] = currentSampleOffset; currentSampleOffset += entrySize; stscSamplePerChunkCount++; // stss data if (mStssData != null) { if (i+1 == stssSampleNumber) { stssTableCount++; mSampleIsSyncSample[i] = true; if (stssTableCount < stssEntryCount) { stssSampleNumber = mStssData.getInt(); } } } else { mSampleIsSyncSample[i] = true; } } mDurationUs = sttsCurrentSampleTimeToSample; return true; } public void releaseSampleTable() { mSampleSize = null; mSampleDescriptionIndex = null; mSampleOffset = null; mSampleIsSyncSample = null; mSampleTimestampUs = null; mSampleDurationUs = null; } public int getSampleCount() { return mSampleCount; } public void setTimescale(int timeScale) { mTimeScale = timeScale; } public int findSampleIndex(long seekTimeUs) { long sampleTimeUs = 0; int sampleCount = 0; int latestSyncSampleIndex = 0; for (int i = 0; i < mSampleCount; i++) { if (mSampleIsSyncSample[i]) { sampleTimeUs = mSampleTimestampUs[i]; if (sampleTimeUs >= seekTimeUs) { break; } latestSyncSampleIndex = sampleCount; } sampleCount++; } return latestSyncSampleIndex; } public long getTimeOfSample(int sampleIndex) { if (sampleIndex < mSampleCount) { return mSampleTimestampUs[sampleIndex]; } return -1; } public long getDurationUs() { return mDurationUs; } }
apache-2.0
timaar/Tiimspot
src/main/java/com/timaar/tiimspot/web/filter/package-info.java
68
/** * Servlet filters. */ package com.timaar.tiimspot.web.filter;
apache-2.0
jexp/idea2
plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/rename/RenameTest.java
2839
package org.jetbrains.plugins.groovy.refactoring.rename; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiReference; import com.intellij.psi.impl.source.PostprocessReformattingAspect; import com.intellij.refactoring.rename.RenameProcessor; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod; import org.jetbrains.plugins.groovy.util.TestUtils; import java.util.List; /** * @author ven */ public class RenameTest extends LightCodeInsightFixtureTestCase { public void testClosureIt() throws Throwable { doTest(); } public void testTo_getter() throws Throwable { doTest(); } public void testTo_prop() throws Throwable { doTest(); } public void testTo_setter() throws Throwable { doTest(); } public void testScriptMethod() throws Throwable { doTest(); } public void doTest() throws Throwable { final String testFile = getTestName(true).replace('$', '/') + ".test"; final List<String> list = TestUtils.readInput(TestUtils.getAbsoluteTestDataPath() + "groovy/refactoring/rename/" + testFile); myFixture.configureByText(GroovyFileType.GROOVY_FILE_TYPE, list.get(0)); PsiReference ref = myFixture.getFile().findReferenceAt(myFixture.getEditor().getCaretModel().getOffset()); final PsiElement resolved = ref == null ? null : ref.resolve(); if (resolved instanceof PsiMethod && !(resolved instanceof GrAccessorMethod)) { PsiMethod method = (PsiMethod)resolved; String name = method.getName(); String newName = createNewNameForMethod(name); myFixture.renameElementAtCaret(newName); } else if (resolved instanceof GrAccessorMethod) { GrField field = ((GrAccessorMethod)resolved).getProperty(); RenameProcessor processor = new RenameProcessor(myFixture.getProject(), field, "newName", true, true); processor.addElement(resolved, createNewNameForMethod(((GrAccessorMethod)resolved).getName())); processor.run(); } else { myFixture.renameElementAtCaret("newName"); } PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting(); myFixture.checkResult(list.get(1)); } private String createNewNameForMethod(final String name) { String newName = "newName"; if (name.startsWith("get")) { newName = "get" + StringUtil.capitalize(newName); } else if (name.startsWith("is")) { newName = "is" + StringUtil.capitalize(newName); } else if (name.startsWith("set")) { newName = "set" + StringUtil.capitalize(newName); } return newName; } }
apache-2.0
OpenGamma/Strata
modules/market/src/main/java/com/opengamma/strata/market/curve/node/FixedInflationSwapCurveNode.java
28897
/* * Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.market.curve.node; import java.io.Serializable; import java.time.LocalDate; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.joda.beans.Bean; import org.joda.beans.ImmutableBean; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaBean; import org.joda.beans.MetaProperty; import org.joda.beans.gen.BeanDefinition; import org.joda.beans.gen.ImmutableDefaults; import org.joda.beans.gen.ImmutablePreBuild; import org.joda.beans.gen.PropertyDefinition; import org.joda.beans.impl.direct.DirectFieldsBeanBuilder; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import com.google.common.collect.ImmutableSet; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.currency.FxRateProvider; import com.opengamma.strata.basics.index.PriceIndex; import com.opengamma.strata.collect.timeseries.LocalDateDoubleTimeSeries; import com.opengamma.strata.data.MarketData; import com.opengamma.strata.data.ObservableId; import com.opengamma.strata.market.ValueType; import com.opengamma.strata.market.curve.CurveNode; import com.opengamma.strata.market.curve.CurveNodeDate; import com.opengamma.strata.market.curve.CurveNodeDateOrder; import com.opengamma.strata.market.observable.IndexQuoteId; import com.opengamma.strata.market.param.DatedParameterMetadata; import com.opengamma.strata.market.param.LabelDateParameterMetadata; import com.opengamma.strata.market.param.TenorDateParameterMetadata; import com.opengamma.strata.product.common.BuySell; import com.opengamma.strata.product.rate.InflationEndInterpolatedRateComputation; import com.opengamma.strata.product.rate.InflationEndMonthRateComputation; import com.opengamma.strata.product.rate.InflationInterpolatedRateComputation; import com.opengamma.strata.product.rate.InflationMonthlyRateComputation; import com.opengamma.strata.product.swap.RateAccrualPeriod; import com.opengamma.strata.product.swap.RatePaymentPeriod; import com.opengamma.strata.product.swap.ResolvedSwapLeg; import com.opengamma.strata.product.swap.ResolvedSwapTrade; import com.opengamma.strata.product.swap.SwapLeg; import com.opengamma.strata.product.swap.SwapLegType; import com.opengamma.strata.product.swap.SwapPaymentPeriod; import com.opengamma.strata.product.swap.SwapTrade; import com.opengamma.strata.product.swap.type.FixedInflationSwapTemplate; /** * A curve node whose instrument is a Fixed-Inflation swap. * <p> * The trade produced by the node will be a fixed receiver (SELL) for a positive quantity * and a fixed payer (BUY) for a negative quantity. */ @BeanDefinition public final class FixedInflationSwapCurveNode implements CurveNode, ImmutableBean, Serializable { /** * The template for the swap associated with this node. */ @PropertyDefinition(validate = "notNull") private final FixedInflationSwapTemplate template; /** * The identifier of the market data value that provides the rate. */ @PropertyDefinition(validate = "notNull") private final ObservableId rateId; /** * The additional spread added to the fixed rate. */ @PropertyDefinition private final double additionalSpread; /** * The label to use for the node, defaulted. * <p> * When building, this will default based on the tenor if not specified. */ @PropertyDefinition(validate = "notEmpty", overrideGet = true) private final String label; /** * The method by which the date of the node is calculated, defaulted to 'End'. */ @PropertyDefinition private final CurveNodeDate date; /** * The date order rules, used to ensure that the dates in the curve are in order. * If not specified, this will default to {@link CurveNodeDateOrder#DEFAULT}. */ @PropertyDefinition(validate = "notNull", overrideGet = true) private final CurveNodeDateOrder dateOrder; //------------------------------------------------------------------------- /** * Returns a curve node for a Fixed-Inflation swap using the specified instrument template and rate key. * <p> * A suitable default label will be created. * * @param template the template used for building the instrument for the node * @param rateId the identifier of the market rate used when building the instrument for the node * @return a node whose instrument is built from the template using a market rate */ public static FixedInflationSwapCurveNode of(FixedInflationSwapTemplate template, ObservableId rateId) { return of(template, rateId, 0d); } /** * Returns a curve node for a Fixed-Inflation swap using the specified instrument template, rate key and spread. * <p> * A suitable default label will be created. * * @param template the template defining the node instrument * @param rateId the identifier of the market data providing the rate for the node instrument * @param additionalSpread the additional spread amount added to the rate * @return a node whose instrument is built from the template using a market rate */ public static FixedInflationSwapCurveNode of( FixedInflationSwapTemplate template, ObservableId rateId, double additionalSpread) { return builder() .template(template) .rateId(rateId) .additionalSpread(additionalSpread) .build(); } /** * Returns a curve node for a Fixed-Inflation swap using the specified instrument template, * rate key, spread and label. * * @param template the template defining the node instrument * @param rateId the identifier of the market data providing the rate for the node instrument * @param additionalSpread the additional spread amount added to the rate * @param label the label to use for the node * @return a node whose instrument is built from the template using a market rate */ public static FixedInflationSwapCurveNode of( FixedInflationSwapTemplate template, ObservableId rateId, double additionalSpread, String label) { return new FixedInflationSwapCurveNode( template, rateId, additionalSpread, label, CurveNodeDate.END, CurveNodeDateOrder.DEFAULT); } @ImmutableDefaults private static void applyDefaults(Builder builder) { builder.date = CurveNodeDate.END; builder.dateOrder = CurveNodeDateOrder.DEFAULT; } @ImmutablePreBuild private static void preBuild(Builder builder) { if (builder.label == null && builder.template != null) { builder.label = builder.template.getTenor().toString(); } } //------------------------------------------------------------------------- @Override public Set<ObservableId> requirements() { return ImmutableSet.of(rateId); } @Override public LocalDate date(LocalDate valuationDate, ReferenceData refData) { return date.calculate( () -> calculateEnd(valuationDate, refData), () -> calculateLastFixingDate(valuationDate, refData)); } @Override public DatedParameterMetadata metadata(LocalDate valuationDate, ReferenceData refData) { LocalDate nodeDate = date(valuationDate, refData); if (date.isFixed()) { return LabelDateParameterMetadata.of(nodeDate, label); } return TenorDateParameterMetadata.of(nodeDate, template.getTenor(), label); } // calculate the end date private LocalDate calculateEnd(LocalDate valuationDate, ReferenceData refData) { SwapTrade trade = template.createTrade(valuationDate, BuySell.BUY, 1, 1, refData); return trade.getProduct().getEndDate().adjusted(refData); } // calculate the last fixing date private LocalDate calculateLastFixingDate(LocalDate valuationDate, ReferenceData refData) { SwapTrade trade = template.createTrade(valuationDate, BuySell.BUY, 1, 1, refData); SwapLeg inflationLeg = trade.getProduct().getLegs(SwapLegType.INFLATION).get(0); ResolvedSwapLeg inflationLegExpanded = inflationLeg.resolve(refData); List<SwapPaymentPeriod> periods = inflationLegExpanded.getPaymentPeriods(); int nbPeriods = periods.size(); RatePaymentPeriod lastPeriod = (RatePaymentPeriod) periods.get(nbPeriods - 1); List<RateAccrualPeriod> accruals = lastPeriod.getAccrualPeriods(); int nbAccruals = accruals.size(); RateAccrualPeriod lastAccrual = accruals.get(nbAccruals - 1); if (lastAccrual.getRateComputation() instanceof InflationMonthlyRateComputation) { return ((InflationMonthlyRateComputation) lastAccrual.getRateComputation()) .getEndObservation().getFixingMonth().atEndOfMonth(); } if (lastAccrual.getRateComputation() instanceof InflationInterpolatedRateComputation) { return ((InflationInterpolatedRateComputation) lastAccrual.getRateComputation()) .getEndSecondObservation().getFixingMonth().atEndOfMonth(); } if (lastAccrual.getRateComputation() instanceof InflationEndMonthRateComputation) { return ((InflationEndMonthRateComputation) lastAccrual.getRateComputation()) .getEndObservation().getFixingMonth().atEndOfMonth(); } if (lastAccrual.getRateComputation() instanceof InflationEndInterpolatedRateComputation) { return ((InflationEndInterpolatedRateComputation) lastAccrual.getRateComputation()) .getEndSecondObservation().getFixingMonth().atEndOfMonth(); } throw new IllegalArgumentException("Rate computation type not supported for last fixing date of an inflation swap."); } @Override public SwapTrade trade(double quantity, MarketData marketData, ReferenceData refData) { double fixedRate = marketData.getValue(rateId) + additionalSpread; BuySell buySell = quantity > 0 ? BuySell.SELL : BuySell.BUY; return template.createTrade(marketData.getValuationDate(), buySell, Math.abs(quantity), fixedRate, refData); } @Override public ResolvedSwapTrade resolvedTrade(double quantity, MarketData marketData, ReferenceData refData) { return trade(quantity, marketData, refData).resolve(refData); } @Override public ResolvedSwapTrade sampleResolvedTrade( LocalDate valuationDate, FxRateProvider fxProvider, ReferenceData refData) { SwapTrade trade = template.createTrade(valuationDate, BuySell.SELL, 1d, additionalSpread, refData); return trade.resolve(refData); } @Override public double initialGuess(MarketData marketData, ValueType valueType) { if (ValueType.PRICE_INDEX.equals(valueType)) { PriceIndex index = template.getConvention().getFloatingLeg().getIndex(); LocalDateDoubleTimeSeries ts = marketData.getTimeSeries(IndexQuoteId.of(index)); double latestIndex = ts.getLatestValue(); double rate = marketData.getValue(rateId); double year = template.getTenor().getPeriod().getYears(); return latestIndex * Math.pow(1.0 + rate, year); } if (ValueType.ZERO_RATE.equals(valueType)) { return marketData.getValue(rateId); } throw new IllegalArgumentException("No default initial guess when value type is not 'PriceIndex' or 'ZeroRate'."); } //------------------------------------------------------------------------- /** * Returns a copy of this node with the specified date. * * @param date the date to use * @return the node based on this node with the specified date */ public FixedInflationSwapCurveNode withDate(CurveNodeDate date) { return new FixedInflationSwapCurveNode(template, rateId, additionalSpread, label, date, dateOrder); } //------------------------- AUTOGENERATED START ------------------------- /** * The meta-bean for {@code FixedInflationSwapCurveNode}. * @return the meta-bean, not null */ public static FixedInflationSwapCurveNode.Meta meta() { return FixedInflationSwapCurveNode.Meta.INSTANCE; } static { MetaBean.register(FixedInflationSwapCurveNode.Meta.INSTANCE); } /** * The serialization version id. */ private static final long serialVersionUID = 1L; /** * Returns a builder used to create an instance of the bean. * @return the builder, not null */ public static FixedInflationSwapCurveNode.Builder builder() { return new FixedInflationSwapCurveNode.Builder(); } private FixedInflationSwapCurveNode( FixedInflationSwapTemplate template, ObservableId rateId, double additionalSpread, String label, CurveNodeDate date, CurveNodeDateOrder dateOrder) { JodaBeanUtils.notNull(template, "template"); JodaBeanUtils.notNull(rateId, "rateId"); JodaBeanUtils.notEmpty(label, "label"); JodaBeanUtils.notNull(dateOrder, "dateOrder"); this.template = template; this.rateId = rateId; this.additionalSpread = additionalSpread; this.label = label; this.date = date; this.dateOrder = dateOrder; } @Override public FixedInflationSwapCurveNode.Meta metaBean() { return FixedInflationSwapCurveNode.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets the template for the swap associated with this node. * @return the value of the property, not null */ public FixedInflationSwapTemplate getTemplate() { return template; } //----------------------------------------------------------------------- /** * Gets the identifier of the market data value that provides the rate. * @return the value of the property, not null */ public ObservableId getRateId() { return rateId; } //----------------------------------------------------------------------- /** * Gets the additional spread added to the fixed rate. * @return the value of the property */ public double getAdditionalSpread() { return additionalSpread; } //----------------------------------------------------------------------- /** * Gets the label to use for the node, defaulted. * <p> * When building, this will default based on the tenor if not specified. * @return the value of the property, not empty */ @Override public String getLabel() { return label; } //----------------------------------------------------------------------- /** * Gets the method by which the date of the node is calculated, defaulted to 'End'. * @return the value of the property */ public CurveNodeDate getDate() { return date; } //----------------------------------------------------------------------- /** * Gets the date order rules, used to ensure that the dates in the curve are in order. * If not specified, this will default to {@link CurveNodeDateOrder#DEFAULT}. * @return the value of the property, not null */ @Override public CurveNodeDateOrder getDateOrder() { return dateOrder; } //----------------------------------------------------------------------- /** * Returns a builder that allows this bean to be mutated. * @return the mutable builder, not null */ public Builder toBuilder() { return new Builder(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { FixedInflationSwapCurveNode other = (FixedInflationSwapCurveNode) obj; return JodaBeanUtils.equal(template, other.template) && JodaBeanUtils.equal(rateId, other.rateId) && JodaBeanUtils.equal(additionalSpread, other.additionalSpread) && JodaBeanUtils.equal(label, other.label) && JodaBeanUtils.equal(date, other.date) && JodaBeanUtils.equal(dateOrder, other.dateOrder); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(template); hash = hash * 31 + JodaBeanUtils.hashCode(rateId); hash = hash * 31 + JodaBeanUtils.hashCode(additionalSpread); hash = hash * 31 + JodaBeanUtils.hashCode(label); hash = hash * 31 + JodaBeanUtils.hashCode(date); hash = hash * 31 + JodaBeanUtils.hashCode(dateOrder); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(224); buf.append("FixedInflationSwapCurveNode{"); buf.append("template").append('=').append(JodaBeanUtils.toString(template)).append(',').append(' '); buf.append("rateId").append('=').append(JodaBeanUtils.toString(rateId)).append(',').append(' '); buf.append("additionalSpread").append('=').append(JodaBeanUtils.toString(additionalSpread)).append(',').append(' '); buf.append("label").append('=').append(JodaBeanUtils.toString(label)).append(',').append(' '); buf.append("date").append('=').append(JodaBeanUtils.toString(date)).append(',').append(' '); buf.append("dateOrder").append('=').append(JodaBeanUtils.toString(dateOrder)); buf.append('}'); return buf.toString(); } //----------------------------------------------------------------------- /** * The meta-bean for {@code FixedInflationSwapCurveNode}. */ public static final class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code template} property. */ private final MetaProperty<FixedInflationSwapTemplate> template = DirectMetaProperty.ofImmutable( this, "template", FixedInflationSwapCurveNode.class, FixedInflationSwapTemplate.class); /** * The meta-property for the {@code rateId} property. */ private final MetaProperty<ObservableId> rateId = DirectMetaProperty.ofImmutable( this, "rateId", FixedInflationSwapCurveNode.class, ObservableId.class); /** * The meta-property for the {@code additionalSpread} property. */ private final MetaProperty<Double> additionalSpread = DirectMetaProperty.ofImmutable( this, "additionalSpread", FixedInflationSwapCurveNode.class, Double.TYPE); /** * The meta-property for the {@code label} property. */ private final MetaProperty<String> label = DirectMetaProperty.ofImmutable( this, "label", FixedInflationSwapCurveNode.class, String.class); /** * The meta-property for the {@code date} property. */ private final MetaProperty<CurveNodeDate> date = DirectMetaProperty.ofImmutable( this, "date", FixedInflationSwapCurveNode.class, CurveNodeDate.class); /** * The meta-property for the {@code dateOrder} property. */ private final MetaProperty<CurveNodeDateOrder> dateOrder = DirectMetaProperty.ofImmutable( this, "dateOrder", FixedInflationSwapCurveNode.class, CurveNodeDateOrder.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "template", "rateId", "additionalSpread", "label", "date", "dateOrder"); /** * Restricted constructor. */ private Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -1321546630: // template return template; case -938107365: // rateId return rateId; case 291232890: // additionalSpread return additionalSpread; case 102727412: // label return label; case 3076014: // date return date; case -263699392: // dateOrder return dateOrder; } return super.metaPropertyGet(propertyName); } @Override public FixedInflationSwapCurveNode.Builder builder() { return new FixedInflationSwapCurveNode.Builder(); } @Override public Class<? extends FixedInflationSwapCurveNode> beanType() { return FixedInflationSwapCurveNode.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code template} property. * @return the meta-property, not null */ public MetaProperty<FixedInflationSwapTemplate> template() { return template; } /** * The meta-property for the {@code rateId} property. * @return the meta-property, not null */ public MetaProperty<ObservableId> rateId() { return rateId; } /** * The meta-property for the {@code additionalSpread} property. * @return the meta-property, not null */ public MetaProperty<Double> additionalSpread() { return additionalSpread; } /** * The meta-property for the {@code label} property. * @return the meta-property, not null */ public MetaProperty<String> label() { return label; } /** * The meta-property for the {@code date} property. * @return the meta-property, not null */ public MetaProperty<CurveNodeDate> date() { return date; } /** * The meta-property for the {@code dateOrder} property. * @return the meta-property, not null */ public MetaProperty<CurveNodeDateOrder> dateOrder() { return dateOrder; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -1321546630: // template return ((FixedInflationSwapCurveNode) bean).getTemplate(); case -938107365: // rateId return ((FixedInflationSwapCurveNode) bean).getRateId(); case 291232890: // additionalSpread return ((FixedInflationSwapCurveNode) bean).getAdditionalSpread(); case 102727412: // label return ((FixedInflationSwapCurveNode) bean).getLabel(); case 3076014: // date return ((FixedInflationSwapCurveNode) bean).getDate(); case -263699392: // dateOrder return ((FixedInflationSwapCurveNode) bean).getDateOrder(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { metaProperty(propertyName); if (quiet) { return; } throw new UnsupportedOperationException("Property cannot be written: " + propertyName); } } //----------------------------------------------------------------------- /** * The bean-builder for {@code FixedInflationSwapCurveNode}. */ public static final class Builder extends DirectFieldsBeanBuilder<FixedInflationSwapCurveNode> { private FixedInflationSwapTemplate template; private ObservableId rateId; private double additionalSpread; private String label; private CurveNodeDate date; private CurveNodeDateOrder dateOrder; /** * Restricted constructor. */ private Builder() { applyDefaults(this); } /** * Restricted copy constructor. * @param beanToCopy the bean to copy from, not null */ private Builder(FixedInflationSwapCurveNode beanToCopy) { this.template = beanToCopy.getTemplate(); this.rateId = beanToCopy.getRateId(); this.additionalSpread = beanToCopy.getAdditionalSpread(); this.label = beanToCopy.getLabel(); this.date = beanToCopy.getDate(); this.dateOrder = beanToCopy.getDateOrder(); } //----------------------------------------------------------------------- @Override public Object get(String propertyName) { switch (propertyName.hashCode()) { case -1321546630: // template return template; case -938107365: // rateId return rateId; case 291232890: // additionalSpread return additionalSpread; case 102727412: // label return label; case 3076014: // date return date; case -263699392: // dateOrder return dateOrder; default: throw new NoSuchElementException("Unknown property: " + propertyName); } } @Override public Builder set(String propertyName, Object newValue) { switch (propertyName.hashCode()) { case -1321546630: // template this.template = (FixedInflationSwapTemplate) newValue; break; case -938107365: // rateId this.rateId = (ObservableId) newValue; break; case 291232890: // additionalSpread this.additionalSpread = (Double) newValue; break; case 102727412: // label this.label = (String) newValue; break; case 3076014: // date this.date = (CurveNodeDate) newValue; break; case -263699392: // dateOrder this.dateOrder = (CurveNodeDateOrder) newValue; break; default: throw new NoSuchElementException("Unknown property: " + propertyName); } return this; } @Override public Builder set(MetaProperty<?> property, Object value) { super.set(property, value); return this; } @Override public FixedInflationSwapCurveNode build() { preBuild(this); return new FixedInflationSwapCurveNode( template, rateId, additionalSpread, label, date, dateOrder); } //----------------------------------------------------------------------- /** * Sets the template for the swap associated with this node. * @param template the new value, not null * @return this, for chaining, not null */ public Builder template(FixedInflationSwapTemplate template) { JodaBeanUtils.notNull(template, "template"); this.template = template; return this; } /** * Sets the identifier of the market data value that provides the rate. * @param rateId the new value, not null * @return this, for chaining, not null */ public Builder rateId(ObservableId rateId) { JodaBeanUtils.notNull(rateId, "rateId"); this.rateId = rateId; return this; } /** * Sets the additional spread added to the fixed rate. * @param additionalSpread the new value * @return this, for chaining, not null */ public Builder additionalSpread(double additionalSpread) { this.additionalSpread = additionalSpread; return this; } /** * Sets the label to use for the node, defaulted. * <p> * When building, this will default based on the tenor if not specified. * @param label the new value, not empty * @return this, for chaining, not null */ public Builder label(String label) { JodaBeanUtils.notEmpty(label, "label"); this.label = label; return this; } /** * Sets the method by which the date of the node is calculated, defaulted to 'End'. * @param date the new value * @return this, for chaining, not null */ public Builder date(CurveNodeDate date) { this.date = date; return this; } /** * Sets the date order rules, used to ensure that the dates in the curve are in order. * If not specified, this will default to {@link CurveNodeDateOrder#DEFAULT}. * @param dateOrder the new value, not null * @return this, for chaining, not null */ public Builder dateOrder(CurveNodeDateOrder dateOrder) { JodaBeanUtils.notNull(dateOrder, "dateOrder"); this.dateOrder = dateOrder; return this; } //----------------------------------------------------------------------- @Override public String toString() { StringBuilder buf = new StringBuilder(224); buf.append("FixedInflationSwapCurveNode.Builder{"); buf.append("template").append('=').append(JodaBeanUtils.toString(template)).append(',').append(' '); buf.append("rateId").append('=').append(JodaBeanUtils.toString(rateId)).append(',').append(' '); buf.append("additionalSpread").append('=').append(JodaBeanUtils.toString(additionalSpread)).append(',').append(' '); buf.append("label").append('=').append(JodaBeanUtils.toString(label)).append(',').append(' '); buf.append("date").append('=').append(JodaBeanUtils.toString(date)).append(',').append(' '); buf.append("dateOrder").append('=').append(JodaBeanUtils.toString(dateOrder)); buf.append('}'); return buf.toString(); } } //-------------------------- AUTOGENERATED END -------------------------- }
apache-2.0
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_8738.java
151
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_8738 { }
apache-2.0
cedricbou/FiddleWith
config/src/main/java/fiddle/config/http/FiddleHttpConfiguration.java
725
package fiddle.config.http; import javax.validation.Valid; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableMap; import com.yammer.dropwizard.client.HttpClientConfiguration; public class FiddleHttpConfiguration { @JsonProperty("default") @Valid @NotNull private HttpClientConfiguration _default = new HttpClientConfiguration(); @JsonProperty @Valid @NotNull private ImmutableMap<String, ConfiguredHttpConfiguration> configured = ImmutableMap.of(); public HttpClientConfiguration getDefault() { return _default; } public ImmutableMap<String, ConfiguredHttpConfiguration> configured() { return configured; } }
apache-2.0
andrenmaia/batfish
projects/batfish/src/batfish/logicblox/PredicateInfo.java
1532
package batfish.logicblox; import java.io.Serializable; import batfish.collections.FunctionSet; import batfish.collections.LBValueTypeList; import batfish.collections.PredicateSemantics; import batfish.collections.PredicateValueTypeMap; import batfish.collections.QualifiedNameMap; public class PredicateInfo implements Serializable { private static final long serialVersionUID = 1L; private FunctionSet _functions; private PredicateSemantics _predicateSemantics; private PredicateValueTypeMap _predicateValueTypes; private QualifiedNameMap _qualifiedNameMap; public PredicateInfo(PredicateSemantics predicateSemantics, PredicateValueTypeMap predicateValueTypes, FunctionSet functions, QualifiedNameMap qualifiedNameMap) { _functions = functions; _predicateSemantics = predicateSemantics; _predicateValueTypes = predicateValueTypes; _qualifiedNameMap = qualifiedNameMap; } public QualifiedNameMap getPredicateNames() { return _qualifiedNameMap; } public PredicateSemantics getPredicateSemantics() { return _predicateSemantics; } public String getPredicateSemantics(String unqualifiedPredicateName) { return _predicateSemantics.get(unqualifiedPredicateName); } public LBValueTypeList getPredicateValueTypes(String unqualifiedPredicateName) { return _predicateValueTypes.get(unqualifiedPredicateName); } public boolean isFunction(String relationName) { return _functions.contains(relationName); } }
apache-2.0
goodwinnk/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/data/GithubPullRequestDetailed.java
18687
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api.data; import org.jetbrains.io.mandatory.RestModel; //https://developer.github.com/v3/pulls/ //region GithubPullRequestDetailed //region GithubPullRequest /* "url": "https://api.github.com/repos/iasemenov/testing/pulls/1", "id": 180865260, "html_url": "https://github.com/iasemenov/testing/pull/1", "diff_url": "https://github.com/iasemenov/testing/pull/1.diff", "patch_url": "https://github.com/iasemenov/testing/pull/1.patch", "issue_url": "https://api.github.com/repos/iasemenov/testing/issues/1", "number": 1, "state": "open", "locked": false, "title": "pr_test", "user": { "login": "iasemenov", "id": 33097396, "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4", "gravatar_id": "", "url": "https://api.github.com/users/iasemenov", "html_url": "https://github.com/iasemenov", "followers_url": "https://api.github.com/users/iasemenov/followers", "following_url": "https://api.github.com/users/iasemenov/following{/other_user}", "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}", "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions", "organizations_url": "https://api.github.com/users/iasemenov/orgs", "repos_url": "https://api.github.com/users/iasemenov/repos", "events_url": "https://api.github.com/users/iasemenov/events{/privacy}", "received_events_url": "https://api.github.com/users/iasemenov/received_events", "type": "User", "site_admin": false }, "body": "test", "created_at": "2018-04-11T10:58:46Z", "updated_at": "2018-04-11T11:09:36Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "cd72119c443f477698a25f3a27effa1896d8718a", "assignee": { "login": "iasemenov", "id": 33097396, "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4", "gravatar_id": "", "url": "https://api.github.com/users/iasemenov", "html_url": "https://github.com/iasemenov", "followers_url": "https://api.github.com/users/iasemenov/followers", "following_url": "https://api.github.com/users/iasemenov/following{/other_user}", "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}", "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions", "organizations_url": "https://api.github.com/users/iasemenov/orgs", "repos_url": "https://api.github.com/users/iasemenov/repos", "events_url": "https://api.github.com/users/iasemenov/events{/privacy}", "received_events_url": "https://api.github.com/users/iasemenov/received_events", "type": "User", "site_admin": false }, "assignees": [ { "login": "iasemenov", "id": 33097396, "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4", "gravatar_id": "", "url": "https://api.github.com/users/iasemenov", "html_url": "https://github.com/iasemenov", "followers_url": "https://api.github.com/users/iasemenov/followers", "following_url": "https://api.github.com/users/iasemenov/following{/other_user}", "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}", "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions", "organizations_url": "https://api.github.com/users/iasemenov/orgs", "repos_url": "https://api.github.com/users/iasemenov/repos", "events_url": "https://api.github.com/users/iasemenov/events{/privacy}", "received_events_url": "https://api.github.com/users/iasemenov/received_events", "type": "User", "site_admin": false } ], "requested_reviewers": [ ], "requested_teams": [ ], "labels": [ ], "milestone": null, "commits_url": "https://api.github.com/repos/iasemenov/testing/pulls/1/commits", "review_comments_url": "https://api.github.com/repos/iasemenov/testing/pulls/1/comments", "review_comment_url": "https://api.github.com/repos/iasemenov/testing/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/iasemenov/testing/issues/1/comments", "statuses_url": "https://api.github.com/repos/iasemenov/testing/statuses/199b084e4e3da958dff2da3d319a27caf34cfc7a", "head": { "label": "iasemenov:pr_test", "ref": "pr_test", "sha": "199b084e4e3da958dff2da3d319a27caf34cfc7a", "user": { "login": "iasemenov", "id": 33097396, "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4", "gravatar_id": "", "url": "https://api.github.com/users/iasemenov", "html_url": "https://github.com/iasemenov", "followers_url": "https://api.github.com/users/iasemenov/followers", "following_url": "https://api.github.com/users/iasemenov/following{/other_user}", "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}", "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions", "organizations_url": "https://api.github.com/users/iasemenov/orgs", "repos_url": "https://api.github.com/users/iasemenov/repos", "events_url": "https://api.github.com/users/iasemenov/events{/privacy}", "received_events_url": "https://api.github.com/users/iasemenov/received_events", "type": "User", "site_admin": false }, "repo": { "id": 109837424, "name": "testing", "full_name": "iasemenov/testing", "owner": { "login": "iasemenov", "id": 33097396, "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4", "gravatar_id": "", "url": "https://api.github.com/users/iasemenov", "html_url": "https://github.com/iasemenov", "followers_url": "https://api.github.com/users/iasemenov/followers", "following_url": "https://api.github.com/users/iasemenov/following{/other_user}", "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}", "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions", "organizations_url": "https://api.github.com/users/iasemenov/orgs", "repos_url": "https://api.github.com/users/iasemenov/repos", "events_url": "https://api.github.com/users/iasemenov/events{/privacy}", "received_events_url": "https://api.github.com/users/iasemenov/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/iasemenov/testing", "description": null, "fork": false, "url": "https://api.github.com/repos/iasemenov/testing", "forks_url": "https://api.github.com/repos/iasemenov/testing/forks", "keys_url": "https://api.github.com/repos/iasemenov/testing/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/iasemenov/testing/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/iasemenov/testing/teams", "hooks_url": "https://api.github.com/repos/iasemenov/testing/hooks", "issue_events_url": "https://api.github.com/repos/iasemenov/testing/issues/events{/number}", "events_url": "https://api.github.com/repos/iasemenov/testing/events", "assignees_url": "https://api.github.com/repos/iasemenov/testing/assignees{/user}", "branches_url": "https://api.github.com/repos/iasemenov/testing/branches{/branch}", "tags_url": "https://api.github.com/repos/iasemenov/testing/tags", "blobs_url": "https://api.github.com/repos/iasemenov/testing/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/iasemenov/testing/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/iasemenov/testing/git/refs{/sha}", "trees_url": "https://api.github.com/repos/iasemenov/testing/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/iasemenov/testing/statuses/{sha}", "languages_url": "https://api.github.com/repos/iasemenov/testing/languages", "stargazers_url": "https://api.github.com/repos/iasemenov/testing/stargazers", "contributors_url": "https://api.github.com/repos/iasemenov/testing/contributors", "subscribers_url": "https://api.github.com/repos/iasemenov/testing/subscribers", "subscription_url": "https://api.github.com/repos/iasemenov/testing/subscription", "commits_url": "https://api.github.com/repos/iasemenov/testing/commits{/sha}", "git_commits_url": "https://api.github.com/repos/iasemenov/testing/git/commits{/sha}", "comments_url": "https://api.github.com/repos/iasemenov/testing/comments{/number}", "issue_comment_url": "https://api.github.com/repos/iasemenov/testing/issues/comments{/number}", "contents_url": "https://api.github.com/repos/iasemenov/testing/contents/{+path}", "compare_url": "https://api.github.com/repos/iasemenov/testing/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/iasemenov/testing/merges", "archive_url": "https://api.github.com/repos/iasemenov/testing/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/iasemenov/testing/downloads", "issues_url": "https://api.github.com/repos/iasemenov/testing/issues{/number}", "pulls_url": "https://api.github.com/repos/iasemenov/testing/pulls{/number}", "milestones_url": "https://api.github.com/repos/iasemenov/testing/milestones{/number}", "notifications_url": "https://api.github.com/repos/iasemenov/testing/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/iasemenov/testing/labels{/name}", "releases_url": "https://api.github.com/repos/iasemenov/testing/releases{/id}", "deployments_url": "https://api.github.com/repos/iasemenov/testing/deployments", "created_at": "2017-11-07T13:12:21Z", "updated_at": "2018-05-25T10:00:17Z", "pushed_at": "2018-05-25T10:00:16Z", "git_url": "git://github.com/iasemenov/testing.git", "ssh_url": "git@github.com:iasemenov/testing.git", "clone_url": "https://github.com/iasemenov/testing.git", "svn_url": "https://github.com/iasemenov/testing", "homepage": null, "size": 10, "stargazers_count": 0, "watchers_count": 0, "language": null, "has_issues": true, "has_projects": true, "has_downloads": true, "has_wiki": true, "has_pages": false, "forks_count": 1, "mirror_url": null, "archived": false, "open_issues_count": 1, "license": null, "forks": 1, "open_issues": 1, "watchers": 0, "default_branch": "master" } }, "base": { "label": "iasemenov:master", "ref": "master", "sha": "9b9a87ff885d880668f9568bbb7c5de0044fcad3", "user": { "login": "iasemenov", "id": 33097396, "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4", "gravatar_id": "", "url": "https://api.github.com/users/iasemenov", "html_url": "https://github.com/iasemenov", "followers_url": "https://api.github.com/users/iasemenov/followers", "following_url": "https://api.github.com/users/iasemenov/following{/other_user}", "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}", "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions", "organizations_url": "https://api.github.com/users/iasemenov/orgs", "repos_url": "https://api.github.com/users/iasemenov/repos", "events_url": "https://api.github.com/users/iasemenov/events{/privacy}", "received_events_url": "https://api.github.com/users/iasemenov/received_events", "type": "User", "site_admin": false }, "repo": { "id": 109837424, "name": "testing", "full_name": "iasemenov/testing", "owner": { "login": "iasemenov", "id": 33097396, "avatar_url": "https://avatars2.githubusercontent.com/u/33097396?v=4", "gravatar_id": "", "url": "https://api.github.com/users/iasemenov", "html_url": "https://github.com/iasemenov", "followers_url": "https://api.github.com/users/iasemenov/followers", "following_url": "https://api.github.com/users/iasemenov/following{/other_user}", "gists_url": "https://api.github.com/users/iasemenov/gists{/gist_id}", "starred_url": "https://api.github.com/users/iasemenov/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/iasemenov/subscriptions", "organizations_url": "https://api.github.com/users/iasemenov/orgs", "repos_url": "https://api.github.com/users/iasemenov/repos", "events_url": "https://api.github.com/users/iasemenov/events{/privacy}", "received_events_url": "https://api.github.com/users/iasemenov/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/iasemenov/testing", "description": null, "fork": false, "url": "https://api.github.com/repos/iasemenov/testing", "forks_url": "https://api.github.com/repos/iasemenov/testing/forks", "keys_url": "https://api.github.com/repos/iasemenov/testing/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/iasemenov/testing/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/iasemenov/testing/teams", "hooks_url": "https://api.github.com/repos/iasemenov/testing/hooks", "issue_events_url": "https://api.github.com/repos/iasemenov/testing/issues/events{/number}", "events_url": "https://api.github.com/repos/iasemenov/testing/events", "assignees_url": "https://api.github.com/repos/iasemenov/testing/assignees{/user}", "branches_url": "https://api.github.com/repos/iasemenov/testing/branches{/branch}", "tags_url": "https://api.github.com/repos/iasemenov/testing/tags", "blobs_url": "https://api.github.com/repos/iasemenov/testing/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/iasemenov/testing/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/iasemenov/testing/git/refs{/sha}", "trees_url": "https://api.github.com/repos/iasemenov/testing/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/iasemenov/testing/statuses/{sha}", "languages_url": "https://api.github.com/repos/iasemenov/testing/languages", "stargazers_url": "https://api.github.com/repos/iasemenov/testing/stargazers", "contributors_url": "https://api.github.com/repos/iasemenov/testing/contributors", "subscribers_url": "https://api.github.com/repos/iasemenov/testing/subscribers", "subscription_url": "https://api.github.com/repos/iasemenov/testing/subscription", "commits_url": "https://api.github.com/repos/iasemenov/testing/commits{/sha}", "git_commits_url": "https://api.github.com/repos/iasemenov/testing/git/commits{/sha}", "comments_url": "https://api.github.com/repos/iasemenov/testing/comments{/number}", "issue_comment_url": "https://api.github.com/repos/iasemenov/testing/issues/comments{/number}", "contents_url": "https://api.github.com/repos/iasemenov/testing/contents/{+path}", "compare_url": "https://api.github.com/repos/iasemenov/testing/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/iasemenov/testing/merges", "archive_url": "https://api.github.com/repos/iasemenov/testing/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/iasemenov/testing/downloads", "issues_url": "https://api.github.com/repos/iasemenov/testing/issues{/number}", "pulls_url": "https://api.github.com/repos/iasemenov/testing/pulls{/number}", "milestones_url": "https://api.github.com/repos/iasemenov/testing/milestones{/number}", "notifications_url": "https://api.github.com/repos/iasemenov/testing/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/iasemenov/testing/labels{/name}", "releases_url": "https://api.github.com/repos/iasemenov/testing/releases{/id}", "deployments_url": "https://api.github.com/repos/iasemenov/testing/deployments", "created_at": "2017-11-07T13:12:21Z", "updated_at": "2018-05-25T10:00:17Z", "pushed_at": "2018-05-25T10:00:16Z", "git_url": "git://github.com/iasemenov/testing.git", "ssh_url": "git@github.com:iasemenov/testing.git", "clone_url": "https://github.com/iasemenov/testing.git", "svn_url": "https://github.com/iasemenov/testing", "homepage": null, "size": 10, "stargazers_count": 0, "watchers_count": 0, "language": null, "has_issues": true, "has_projects": true, "has_downloads": true, "has_wiki": true, "has_pages": false, "forks_count": 1, "mirror_url": null, "archived": false, "open_issues_count": 1, "license": null, "forks": 1, "open_issues": 1, "watchers": 0, "default_branch": "master" } }, "_links": { "self": { "href": "https://api.github.com/repos/iasemenov/testing/pulls/1" }, "html": { "href": "https://github.com/iasemenov/testing/pull/1" }, "issue": { "href": "https://api.github.com/repos/iasemenov/testing/issues/1" }, "comments": { "href": "https://api.github.com/repos/iasemenov/testing/issues/1/comments" }, "review_comments": { "href": "https://api.github.com/repos/iasemenov/testing/pulls/1/comments" }, "review_comment": { "href": "https://api.github.com/repos/iasemenov/testing/pulls/comments{/number}" }, "commits": { "href": "https://api.github.com/repos/iasemenov/testing/pulls/1/commits" }, "statuses": { "href": "https://api.github.com/repos/iasemenov/testing/statuses/199b084e4e3da958dff2da3d319a27caf34cfc7a" } }, "author_association": "OWNER" */ //endregion /* "merged": false, "mergeable": false, "rebaseable": false, "mergeable_state": "dirty", "merged_by": null, "comments": 1, "review_comments": 1, "maintainer_can_modify": false, "commits": 2, "additions": 3, "deletions": 1, "changed_files": 2 */ //endregion @RestModel @SuppressWarnings("UnusedDeclaration") public class GithubPullRequestDetailed extends GithubPullRequest { private Boolean merged; private Boolean mergeable; private Boolean rebaseable; private String mergeableState; private GithubUser mergedBy; private Integer comments; private Integer reviewComments; private Boolean maintainerCanModify; private Integer commits; private Integer additions; private Integer deletions; private Integer changedFiles; }
apache-2.0
googleapis/java-bigquery
samples/snippets/src/main/java/com/example/bigquery/RelaxColumnLoadAppend.java
3790
/* * Copyright 2020 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 * * 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.example.bigquery; // [START bigquery_relax_column_load_append] import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.BigQueryOptions; import com.google.cloud.bigquery.CsvOptions; import com.google.cloud.bigquery.Field; import com.google.cloud.bigquery.Job; import com.google.cloud.bigquery.JobInfo; import com.google.cloud.bigquery.LoadJobConfiguration; import com.google.cloud.bigquery.Schema; import com.google.cloud.bigquery.StandardSQLTypeName; import com.google.cloud.bigquery.Table; import com.google.cloud.bigquery.TableId; import com.google.common.collect.ImmutableList; // Sample to append relax column in a table. public class RelaxColumnLoadAppend { public static void main(String[] args) { // TODO(developer): Replace these variables before running the sample. String datasetName = "MY_DATASET_NAME"; String tableName = "MY_TABLE_NAME"; String sourceUri = "gs://cloud-samples-data/bigquery/us-states/us-states.csv"; relaxColumnLoadAppend(datasetName, tableName, sourceUri); } public static void relaxColumnLoadAppend(String datasetName, String tableName, String sourceUri) { try { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); // Retrieve destination table reference Table table = bigquery.getTable(TableId.of(datasetName, tableName)); // column as a 'REQUIRED' field. Field name = Field.newBuilder("name", StandardSQLTypeName.STRING).setMode(Field.Mode.REQUIRED).build(); Field postAbbr = Field.newBuilder("post_abbr", StandardSQLTypeName.STRING) .setMode(Field.Mode.REQUIRED) .build(); Schema schema = Schema.of(name, postAbbr); // Skip header row in the file. CsvOptions csvOptions = CsvOptions.newBuilder().setSkipLeadingRows(1).build(); // Set job options LoadJobConfiguration loadConfig = LoadJobConfiguration.newBuilder(table.getTableId(), sourceUri) .setSchema(schema) .setFormatOptions(csvOptions) .setSchemaUpdateOptions( ImmutableList.of(JobInfo.SchemaUpdateOption.ALLOW_FIELD_RELAXATION)) .setWriteDisposition(JobInfo.WriteDisposition.WRITE_APPEND) .build(); // Create a load job and wait for it to complete. Job job = bigquery.create(JobInfo.of(loadConfig)); job = job.waitFor(); // Check the job's status for errors if (job.isDone() && job.getStatus().getError() == null) { System.out.println("Relax column append successfully loaded in a table"); } else { System.out.println( "BigQuery was unable to load into the table due to an error:" + job.getStatus().getError()); } } catch (BigQueryException | InterruptedException e) { System.out.println("Column not added during load append \n" + e.toString()); } } } // [END bigquery_relax_column_load_append]
apache-2.0
googleapis/java-securitycenter
proto-google-cloud-securitycenter-v1p1beta1/src/main/java/com/google/cloud/securitycenter/v1p1beta1/SourceName.java
11561
/* * 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.securitycenter.v1p1beta1; import com.google.api.core.BetaApi; import com.google.api.pathtemplate.PathTemplate; import com.google.api.pathtemplate.ValidationException; import com.google.api.resourcenames.ResourceName; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. @Generated("by gapic-generator-java") public class SourceName implements ResourceName { private static final PathTemplate ORGANIZATION_SOURCE = PathTemplate.createWithoutUrlEncoding("organizations/{organization}/sources/{source}"); private static final PathTemplate FOLDER_SOURCE = PathTemplate.createWithoutUrlEncoding("folders/{folder}/sources/{source}"); private static final PathTemplate PROJECT_SOURCE = PathTemplate.createWithoutUrlEncoding("projects/{project}/sources/{source}"); private volatile Map<String, String> fieldValuesMap; private PathTemplate pathTemplate; private String fixedValue; private final String organization; private final String source; private final String folder; private final String project; @Deprecated protected SourceName() { organization = null; source = null; folder = null; project = null; } private SourceName(Builder builder) { organization = Preconditions.checkNotNull(builder.getOrganization()); source = Preconditions.checkNotNull(builder.getSource()); folder = null; project = null; pathTemplate = ORGANIZATION_SOURCE; } private SourceName(FolderSourceBuilder builder) { folder = Preconditions.checkNotNull(builder.getFolder()); source = Preconditions.checkNotNull(builder.getSource()); organization = null; project = null; pathTemplate = FOLDER_SOURCE; } private SourceName(ProjectSourceBuilder builder) { project = Preconditions.checkNotNull(builder.getProject()); source = Preconditions.checkNotNull(builder.getSource()); organization = null; folder = null; pathTemplate = PROJECT_SOURCE; } public String getOrganization() { return organization; } public String getSource() { return source; } public String getFolder() { return folder; } public String getProject() { return project; } public static Builder newBuilder() { return new Builder(); } @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") public static Builder newOrganizationSourceBuilder() { return new Builder(); } @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") public static FolderSourceBuilder newFolderSourceBuilder() { return new FolderSourceBuilder(); } @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") public static ProjectSourceBuilder newProjectSourceBuilder() { return new ProjectSourceBuilder(); } public Builder toBuilder() { return new Builder(this); } public static SourceName of(String organization, String source) { return newBuilder().setOrganization(organization).setSource(source).build(); } @BetaApi("The static create methods are not stable yet and may be changed in the future.") public static SourceName ofOrganizationSourceName(String organization, String source) { return newBuilder().setOrganization(organization).setSource(source).build(); } @BetaApi("The static create methods are not stable yet and may be changed in the future.") public static SourceName ofFolderSourceName(String folder, String source) { return newFolderSourceBuilder().setFolder(folder).setSource(source).build(); } @BetaApi("The static create methods are not stable yet and may be changed in the future.") public static SourceName ofProjectSourceName(String project, String source) { return newProjectSourceBuilder().setProject(project).setSource(source).build(); } public static String format(String organization, String source) { return newBuilder().setOrganization(organization).setSource(source).build().toString(); } @BetaApi("The static format methods are not stable yet and may be changed in the future.") public static String formatOrganizationSourceName(String organization, String source) { return newBuilder().setOrganization(organization).setSource(source).build().toString(); } @BetaApi("The static format methods are not stable yet and may be changed in the future.") public static String formatFolderSourceName(String folder, String source) { return newFolderSourceBuilder().setFolder(folder).setSource(source).build().toString(); } @BetaApi("The static format methods are not stable yet and may be changed in the future.") public static String formatProjectSourceName(String project, String source) { return newProjectSourceBuilder().setProject(project).setSource(source).build().toString(); } public static SourceName parse(String formattedString) { if (formattedString.isEmpty()) { return null; } if (ORGANIZATION_SOURCE.matches(formattedString)) { Map<String, String> matchMap = ORGANIZATION_SOURCE.match(formattedString); return ofOrganizationSourceName(matchMap.get("organization"), matchMap.get("source")); } else if (FOLDER_SOURCE.matches(formattedString)) { Map<String, String> matchMap = FOLDER_SOURCE.match(formattedString); return ofFolderSourceName(matchMap.get("folder"), matchMap.get("source")); } else if (PROJECT_SOURCE.matches(formattedString)) { Map<String, String> matchMap = PROJECT_SOURCE.match(formattedString); return ofProjectSourceName(matchMap.get("project"), matchMap.get("source")); } throw new ValidationException("SourceName.parse: formattedString not in valid format"); } public static List<SourceName> parseList(List<String> formattedStrings) { List<SourceName> list = new ArrayList<>(formattedStrings.size()); for (String formattedString : formattedStrings) { list.add(parse(formattedString)); } return list; } public static List<String> toStringList(List<SourceName> values) { List<String> list = new ArrayList<>(values.size()); for (SourceName value : values) { if (value == null) { list.add(""); } else { list.add(value.toString()); } } return list; } public static boolean isParsableFrom(String formattedString) { return ORGANIZATION_SOURCE.matches(formattedString) || FOLDER_SOURCE.matches(formattedString) || PROJECT_SOURCE.matches(formattedString); } @Override public Map<String, String> getFieldValuesMap() { if (fieldValuesMap == null) { synchronized (this) { if (fieldValuesMap == null) { ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder(); if (organization != null) { fieldMapBuilder.put("organization", organization); } if (source != null) { fieldMapBuilder.put("source", source); } if (folder != null) { fieldMapBuilder.put("folder", folder); } if (project != null) { fieldMapBuilder.put("project", project); } fieldValuesMap = fieldMapBuilder.build(); } } } return fieldValuesMap; } public String getFieldValue(String fieldName) { return getFieldValuesMap().get(fieldName); } @Override public String toString() { return fixedValue != null ? fixedValue : pathTemplate.instantiate(getFieldValuesMap()); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o != null || getClass() == o.getClass()) { SourceName that = ((SourceName) o); return Objects.equals(this.organization, that.organization) && Objects.equals(this.source, that.source) && Objects.equals(this.folder, that.folder) && Objects.equals(this.project, that.project); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= Objects.hashCode(fixedValue); h *= 1000003; h ^= Objects.hashCode(organization); h *= 1000003; h ^= Objects.hashCode(source); h *= 1000003; h ^= Objects.hashCode(folder); h *= 1000003; h ^= Objects.hashCode(project); return h; } /** Builder for organizations/{organization}/sources/{source}. */ public static class Builder { private String organization; private String source; protected Builder() {} public String getOrganization() { return organization; } public String getSource() { return source; } public Builder setOrganization(String organization) { this.organization = organization; return this; } public Builder setSource(String source) { this.source = source; return this; } private Builder(SourceName sourceName) { Preconditions.checkArgument( Objects.equals(sourceName.pathTemplate, ORGANIZATION_SOURCE), "toBuilder is only supported when SourceName has the pattern of organizations/{organization}/sources/{source}"); this.organization = sourceName.organization; this.source = sourceName.source; } public SourceName build() { return new SourceName(this); } } /** Builder for folders/{folder}/sources/{source}. */ @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") public static class FolderSourceBuilder { private String folder; private String source; protected FolderSourceBuilder() {} public String getFolder() { return folder; } public String getSource() { return source; } public FolderSourceBuilder setFolder(String folder) { this.folder = folder; return this; } public FolderSourceBuilder setSource(String source) { this.source = source; return this; } public SourceName build() { return new SourceName(this); } } /** Builder for projects/{project}/sources/{source}. */ @BetaApi("The per-pattern Builders are not stable yet and may be changed in the future.") public static class ProjectSourceBuilder { private String project; private String source; protected ProjectSourceBuilder() {} public String getProject() { return project; } public String getSource() { return source; } public ProjectSourceBuilder setProject(String project) { this.project = project; return this; } public ProjectSourceBuilder setSource(String source) { this.source = source; return this; } public SourceName build() { return new SourceName(this); } } }
apache-2.0
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/utils/CollectionUtils.java
2020
/******************************************************************************* * Copyright 2015-2016 - CNRS (Centre National de Recherche Scientifique) * * 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 fr.univnantes.termsuite.utils; import java.util.List; import java.util.Set; import com.google.common.collect.Sets; public class CollectionUtils { /** * * Transforms a list of sets into a set of element pairs, * which is the union of all cartesian products of * all pairs of sets. * * Example: * * A = {a,b,c} * B = {d} * C = {e, f} * * returns AxB U AxC U BxC = { * {a,d}, {b,d}, {c,d}, * {a,e}, {a,f}, {b,e}, {b,f}, {c,e}, {c,f}, * {d,e}, {d,f} * } * * * @param iterable * @return */ @SuppressWarnings("unchecked") public static <T extends Comparable<? super T>> Set<Pair<T>> combineAndProduct(List<? extends Set<? extends T>> sets) { Set<Pair<T>> results = Sets.newHashSet(); for(int i = 0; i< sets.size(); i++) { for(int j = i+1; j< sets.size(); j++) for(List<T> l:Sets.cartesianProduct(sets.get(i), sets.get(j))) results.add(new Pair<T>(l.get(0), l.get(1))); } return results; } }
apache-2.0
dmromanov98/GameProject
Engine/src/Main/Camera.java
1315
package Main; import Graphics.Shader; import MyMath.Matrix4f; import org.joml.Vector3f; public class Camera { private Camera() { } static private Matrix4f projection; static private Matrix4f view; static private Transform transform = new Transform(); static private boolean viewMatrixShouldBeUpdated = false; static private void updateViewMatrix() { if (viewMatrixShouldBeUpdated) { view = Matrix4f.resize(new Vector3f(transform.getScale(), 1f)). multiply(Matrix4f.rotate(transform.getAngle())). multiply(Matrix4f.translate(new Vector3f(transform.getPosition(), transform.layer))); viewMatrixShouldBeUpdated = false; } } public static void initCamera(float width, float height) { projection = Matrix4f.orthographic(-.5f * width, .5f * width, -.5f * height, .5f * height, -1.0f, 1.0f); //System.out.println(projection); } public static void toShader(Shader shader) { shader.setUniformMat4f("projection", projection); shader.setUniformMat4f("view", view); } public static Transform getTransform() { viewMatrixShouldBeUpdated = true; return transform; } public static void update() { updateViewMatrix(); } }
apache-2.0
TranscendComputing/TopStackRDS
test/java/com/msi/rdsquery/integration/DescribeDBParameterGroupsActionTest.java
2442
package com.msi.rdsquery.integration; import java.util.UUID; import org.junit.Test; import org.slf4j.Logger; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.rds.model.CreateDBParameterGroupRequest; import com.amazonaws.services.rds.model.DeleteDBParameterGroupRequest; import com.amazonaws.services.rds.model.DescribeDBParameterGroupsRequest; import com.msi.tough.core.Appctx; public class DescribeDBParameterGroupsActionTest extends AbstractBaseRdsTest { private static Logger logger = Appctx.getLogger (DescribeDBParameterGroupsActionTest.class.getName()); private final String baseName = UUID.randomUUID().toString() .substring(0, 8); String name1 = "rds-descDbParsGp-1-" + baseName; String parFamily = "MySQL5.5"; //Describes all param groups @Test public void testDescribeDBParameterGroupsNoArgs() throws Exception { final DescribeDBParameterGroupsRequest request = new DescribeDBParameterGroupsRequest(); getRdsClient().describeDBParameterGroups(request); } @Test (expected = AmazonServiceException.class) public void testDescribeDBParameterGroupsInvalidParameters() throws Exception { final DescribeDBParameterGroupsRequest request = new DescribeDBParameterGroupsRequest(); request.withDBParameterGroupName("DoesNotExist"); getRdsClient().describeDBParameterGroups(request); } @Test public void testGoodDescribeDBParameterGroups() throws Exception { logger.info("Creating DBParamGroup "); final CreateDBParameterGroupRequest request = new CreateDBParameterGroupRequest(); request.setDBParameterGroupFamily(parFamily); request.setDBParameterGroupName(name1); request.setDescription("This param group was created as a test"); getRdsClient().createDBParameterGroup(request); logger.info("Describing parameter group " + name1); final DescribeDBParameterGroupsRequest descRequest = new DescribeDBParameterGroupsRequest(); descRequest.withDBParameterGroupName(name1); getRdsClient().describeDBParameterGroups(descRequest); logger.info("Deleting DBParam Group " + name1); final DeleteDBParameterGroupRequest delRequest = new DeleteDBParameterGroupRequest(); delRequest.withDBParameterGroupName(name1); getRdsClient().deleteDBParameterGroup(delRequest); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/model/UpdateFieldLevelEncryptionProfileRequest.java
8118
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.cloudfront.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateFieldLevelEncryptionProfile" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateFieldLevelEncryptionProfileRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * Request to update a field-level encryption profile. * </p> */ private FieldLevelEncryptionProfileConfig fieldLevelEncryptionProfileConfig; /** * <p> * The ID of the field-level encryption profile request. * </p> */ private String id; /** * <p> * The value of the <code>ETag</code> header that you received when retrieving the profile identity to update. For * example: <code>E2QWRUHAPOMQZL</code>. * </p> */ private String ifMatch; /** * <p> * Request to update a field-level encryption profile. * </p> * * @param fieldLevelEncryptionProfileConfig * Request to update a field-level encryption profile. */ public void setFieldLevelEncryptionProfileConfig(FieldLevelEncryptionProfileConfig fieldLevelEncryptionProfileConfig) { this.fieldLevelEncryptionProfileConfig = fieldLevelEncryptionProfileConfig; } /** * <p> * Request to update a field-level encryption profile. * </p> * * @return Request to update a field-level encryption profile. */ public FieldLevelEncryptionProfileConfig getFieldLevelEncryptionProfileConfig() { return this.fieldLevelEncryptionProfileConfig; } /** * <p> * Request to update a field-level encryption profile. * </p> * * @param fieldLevelEncryptionProfileConfig * Request to update a field-level encryption profile. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFieldLevelEncryptionProfileRequest withFieldLevelEncryptionProfileConfig(FieldLevelEncryptionProfileConfig fieldLevelEncryptionProfileConfig) { setFieldLevelEncryptionProfileConfig(fieldLevelEncryptionProfileConfig); return this; } /** * <p> * The ID of the field-level encryption profile request. * </p> * * @param id * The ID of the field-level encryption profile request. */ public void setId(String id) { this.id = id; } /** * <p> * The ID of the field-level encryption profile request. * </p> * * @return The ID of the field-level encryption profile request. */ public String getId() { return this.id; } /** * <p> * The ID of the field-level encryption profile request. * </p> * * @param id * The ID of the field-level encryption profile request. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFieldLevelEncryptionProfileRequest withId(String id) { setId(id); return this; } /** * <p> * The value of the <code>ETag</code> header that you received when retrieving the profile identity to update. For * example: <code>E2QWRUHAPOMQZL</code>. * </p> * * @param ifMatch * The value of the <code>ETag</code> header that you received when retrieving the profile identity to * update. For example: <code>E2QWRUHAPOMQZL</code>. */ public void setIfMatch(String ifMatch) { this.ifMatch = ifMatch; } /** * <p> * The value of the <code>ETag</code> header that you received when retrieving the profile identity to update. For * example: <code>E2QWRUHAPOMQZL</code>. * </p> * * @return The value of the <code>ETag</code> header that you received when retrieving the profile identity to * update. For example: <code>E2QWRUHAPOMQZL</code>. */ public String getIfMatch() { return this.ifMatch; } /** * <p> * The value of the <code>ETag</code> header that you received when retrieving the profile identity to update. For * example: <code>E2QWRUHAPOMQZL</code>. * </p> * * @param ifMatch * The value of the <code>ETag</code> header that you received when retrieving the profile identity to * update. For example: <code>E2QWRUHAPOMQZL</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateFieldLevelEncryptionProfileRequest withIfMatch(String ifMatch) { setIfMatch(ifMatch); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFieldLevelEncryptionProfileConfig() != null) sb.append("FieldLevelEncryptionProfileConfig: ").append(getFieldLevelEncryptionProfileConfig()).append(","); if (getId() != null) sb.append("Id: ").append(getId()).append(","); if (getIfMatch() != null) sb.append("IfMatch: ").append(getIfMatch()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateFieldLevelEncryptionProfileRequest == false) return false; UpdateFieldLevelEncryptionProfileRequest other = (UpdateFieldLevelEncryptionProfileRequest) obj; if (other.getFieldLevelEncryptionProfileConfig() == null ^ this.getFieldLevelEncryptionProfileConfig() == null) return false; if (other.getFieldLevelEncryptionProfileConfig() != null && other.getFieldLevelEncryptionProfileConfig().equals(this.getFieldLevelEncryptionProfileConfig()) == false) return false; if (other.getId() == null ^ this.getId() == null) return false; if (other.getId() != null && other.getId().equals(this.getId()) == false) return false; if (other.getIfMatch() == null ^ this.getIfMatch() == null) return false; if (other.getIfMatch() != null && other.getIfMatch().equals(this.getIfMatch()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFieldLevelEncryptionProfileConfig() == null) ? 0 : getFieldLevelEncryptionProfileConfig().hashCode()); hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode()); hashCode = prime * hashCode + ((getIfMatch() == null) ? 0 : getIfMatch().hashCode()); return hashCode; } @Override public UpdateFieldLevelEncryptionProfileRequest clone() { return (UpdateFieldLevelEncryptionProfileRequest) super.clone(); } }
apache-2.0
schwabe/cgeo
main/src/cgeo/geocaching/apps/cache/navi/SygicNavigationApp.java
1286
package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.R; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.utils.ProcessUtils; import org.eclipse.jdt.annotation.NonNull; import android.app.Activity; import android.content.Intent; import android.net.Uri; /** * http://help.sygic.com/entries/22207668-developers-only-sygic-implementation-to-your-app-android-sdk-iphone-sdk-url- * handler * */ class SygicNavigationApp extends AbstractPointNavigationApp { private static final String PACKAGE_NORMAL = "com.sygic.aura"; /** * there is a secondary edition of this app */ private static final String PACKAGE_VOUCHER = "com.sygic.aura_voucher"; SygicNavigationApp() { super(getString(R.string.cache_menu_sygic), null, PACKAGE_NORMAL); } @Override public boolean isInstalled() { return ProcessUtils.isLaunchable(PACKAGE_NORMAL) || ProcessUtils.isLaunchable(PACKAGE_VOUCHER); } @Override public void navigate(final @NonNull Activity activity, final @NonNull Geopoint coords) { final String str = "http://com.sygic.aura/coordinate|" + coords.getLongitude() + "|" + coords.getLatitude() + "|show"; activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(str))); } }
apache-2.0
vert-x3/vertx-codegen
src/test/java/io/vertx/test/codegen/testapi/MethodWithValidJSONReturn.java
318
package io.vertx.test.codegen.testapi; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; /** * @author <a href="http://tfox.org">Tim Fox</a> */ @VertxGen public interface MethodWithValidJSONReturn { JsonObject foo(); JsonArray bar(); }
apache-2.0
YoungDigitalPlanet/empiria.player
src/main/java/eu/ydp/empiria/player/client/module/drawing/DrawingViewImpl.java
1844
/* * Copyright 2017 Young Digital Planet S.A. * * 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 eu.ydp.empiria.player.client.module.drawing; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import eu.ydp.empiria.player.client.module.drawing.toolbox.ToolboxView; import eu.ydp.empiria.player.client.module.drawing.view.CanvasView; import eu.ydp.gwtutil.client.gin.scopes.module.ModuleScoped; public class DrawingViewImpl extends Composite implements DrawingView { private static DrawingViewUiBinder uiBinder = GWT.create(DrawingViewUiBinder.class); @UiTemplate("DrawingView.ui.xml") interface DrawingViewUiBinder extends UiBinder<Widget, DrawingViewImpl> { } @UiField(provided = true) ToolboxView toolboxView; @UiField(provided = true) CanvasView canvasView; @Inject public DrawingViewImpl(@ModuleScoped ToolboxView toolboxView, @ModuleScoped CanvasView canvasView) { this.toolboxView = toolboxView; this.canvasView = canvasView; initWidget(uiBinder.createAndBindUi(this)); } }
apache-2.0
danielshaya/reactivejournal
src/main/java/org/reactivejournal/impl/ReactiveValidator.java
3026
package org.reactivejournal.impl; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.queue.ExcerptTailer; import net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder; import net.openhft.chronicle.wire.ValueIn; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class to help in validating data in rxJournal during testing. */ public class ReactiveValidator { private static final Logger LOG = LoggerFactory.getLogger(ReactiveValidator.class.getName()); private ValidationResult validationResult; private DataItemProcessor dataItemProcessor = new DataItemProcessor(); public void validate(String fileName, Publisher flowable, String filter, Subscriber subscriber) { ChronicleQueue queue = SingleChronicleQueueBuilder.binary(fileName).build(); ExcerptTailer tailer = queue.createTailer(); validationResult = new ValidationResult(); flowable.subscribe(new Subscriber() { @Override public void onSubscribe(Subscription subscription) { subscription.request(Long.MAX_VALUE); } @Override public void onNext(Object o) { Object onQueue = null; try { onQueue = getNextMatchingFilter(tailer, filter); }catch(IllegalStateException e){ subscriber.onComplete(); }catch(Exception e){ subscriber.onError(e); } if (onQueue.equals(o)) { validationResult.setResult(ValidationResult.Result.OK); } else { validationResult.setResult(ValidationResult.Result.BAD); } validationResult.setFromQueue(onQueue); validationResult.setGenerated(o); subscriber.onNext(validationResult); } @Override public void onError(Throwable throwable) { LOG.error("error in validate [{}]", throwable); } @Override public void onComplete() { subscriber.onComplete(); queue.close(); } }); } private Object getNextMatchingFilter(ExcerptTailer tailer, String filter) { nextItemFromQueue(tailer, dataItemProcessor); if (dataItemProcessor.getFilter().equals(filter)) { return dataItemProcessor.getObject(); } else { return getNextMatchingFilter(tailer, filter); } } private boolean nextItemFromQueue(ExcerptTailer tailer,DataItemProcessor dim) { return !tailer.readDocument(w -> { ValueIn in = w.getValueIn(); dim.process(in, null); }); } public ValidationResult getValidationResult() { return validationResult; } }
apache-2.0
MobiDevelop/android-split-pane-layout
split-pane-layout/src/main/java/com/mobidevelop/spl/widget/SplitPaneLayout.java
28236
/* * Android Split Pane Layout. * https://github.com/MobiDevelop/android-split-pane-layout * * Copyright (C) 2012 Justin Shapcott * * 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.mobidevelop.spl.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.PaintDrawable; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.ViewConfiguration; import android.view.ViewGroup; import com.mobidevelop.spl.R; /** * A layout that splits the available space between two child views. * <p/> * An optionally movable bar exists between the children which allows the user * to redistribute the space allocated to each view. */ public class SplitPaneLayout extends ViewGroup { public interface OnSplitterPositionChangedListener { void onSplitterPositionChanged(SplitPaneLayout splitPaneLayout, boolean fromUser); } public static final int ORIENTATION_HORIZONTAL = 0; public static final int ORIENTATION_VERTICAL = 1; private int mOrientation = 0; private int mSplitterSize = 8; private boolean mSplitterMovable = true; private int mSplitterPosition = Integer.MIN_VALUE; private float mSplitterPositionPercent = 0.5f; private int mSplitterTouchSlop = 0; private int mPaneSizeMin = 0; private Drawable mSplitterDrawable; private Drawable mSplitterDraggingDrawable; private Rect mSplitterBounds = new Rect(); private Rect mSplitterTouchBounds = new Rect(); private Rect mSplitterDraggingBounds = new Rect(); private OnSplitterPositionChangedListener mOnSplitterPositionChangedListener; private int lastTouchX; private int lastTouchY; private boolean isDragging = false; private boolean isMovingSplitter = false; private boolean isMeasured = false; public SplitPaneLayout(Context context) { super(context); mSplitterPositionPercent = 0.5f; mSplitterDrawable = new PaintDrawable(0x88FFFFFF); mSplitterDraggingDrawable = new PaintDrawable(0x88FFFFFF); } public SplitPaneLayout(Context context, AttributeSet attrs) { super(context, attrs); extractAttributes(context, attrs); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setFocusable(true); setFocusableInTouchMode(false); } public SplitPaneLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); extractAttributes(context, attrs); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setFocusable(true); setFocusableInTouchMode(false); } private void extractAttributes(Context context, AttributeSet attrs) { if (attrs != null) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SplitPaneLayout); mOrientation = a.getInt(R.styleable.SplitPaneLayout_orientation, 0); mSplitterSize = a.getDimensionPixelSize(R.styleable.SplitPaneLayout_splitterSize, context.getResources().getDimensionPixelSize(R.dimen.spl_default_splitter_size)); mSplitterMovable = a.getBoolean(R.styleable.SplitPaneLayout_splitterMovable, true); TypedValue value = a.peekValue(R.styleable.SplitPaneLayout_splitterPosition); if (value != null) { if (value.type == TypedValue.TYPE_DIMENSION) { mSplitterPosition = a.getDimensionPixelSize(R.styleable.SplitPaneLayout_splitterPosition, Integer.MIN_VALUE); } else if (value.type == TypedValue.TYPE_FRACTION) { mSplitterPositionPercent = a.getFraction(R.styleable.SplitPaneLayout_splitterPosition, 100, 100, 50) * 0.01f; } } else { mSplitterPosition = Integer.MIN_VALUE; mSplitterPositionPercent = 0.5f; } value = a.peekValue(R.styleable.SplitPaneLayout_splitterBackground); if (value != null) { if (value.type == TypedValue.TYPE_REFERENCE || value.type == TypedValue.TYPE_STRING) { mSplitterDrawable = a.getDrawable(R.styleable.SplitPaneLayout_splitterBackground); } else if (value.type == TypedValue.TYPE_INT_COLOR_ARGB8 || value.type == TypedValue.TYPE_INT_COLOR_ARGB4 || value.type == TypedValue.TYPE_INT_COLOR_RGB8 || value.type == TypedValue.TYPE_INT_COLOR_RGB4) { mSplitterDrawable = new PaintDrawable(a.getColor(R.styleable.SplitPaneLayout_splitterBackground, 0xFF000000)); } } value = a.peekValue(R.styleable.SplitPaneLayout_splitterDraggingBackground); if (value != null) { if (value.type == TypedValue.TYPE_REFERENCE || value.type == TypedValue.TYPE_STRING) { mSplitterDraggingDrawable = a.getDrawable(R.styleable.SplitPaneLayout_splitterDraggingBackground); } else if (value.type == TypedValue.TYPE_INT_COLOR_ARGB8 || value.type == TypedValue.TYPE_INT_COLOR_ARGB4 || value.type == TypedValue.TYPE_INT_COLOR_RGB8 || value.type == TypedValue.TYPE_INT_COLOR_RGB4) { mSplitterDraggingDrawable = new PaintDrawable(a.getColor(R.styleable.SplitPaneLayout_splitterDraggingBackground, 0x88FFFFFF)); } } else { mSplitterDraggingDrawable = new PaintDrawable(0x88FFFFFF); } mSplitterTouchSlop = a.getDimensionPixelSize(R.styleable.SplitPaneLayout_splitterTouchSlop, ViewConfiguration.get(context).getScaledTouchSlop()); mPaneSizeMin = a.getDimensionPixelSize(R.styleable.SplitPaneLayout_paneSizeMin, 0); a.recycle(); } } private void computeSplitterPosition() { int measuredWidth = getMeasuredWidth(); int measuredHeight = getMeasuredHeight(); if (measuredWidth > 0 && measuredHeight > 0) { switch (mOrientation) { case ORIENTATION_HORIZONTAL: { if (mSplitterPosition == Integer.MIN_VALUE && mSplitterPositionPercent < 0) { mSplitterPosition = measuredWidth / 2; } else if (mSplitterPosition == Integer.MIN_VALUE && mSplitterPositionPercent >= 0) { mSplitterPosition = (int) (measuredWidth * mSplitterPositionPercent); if (!between(mSplitterPosition, getMinSplitterPosition(), getMaxSplitterPosition())) { mSplitterPosition = clamp(mSplitterPosition, getMinSplitterPosition(), getMaxSplitterPosition()); mSplitterPositionPercent = (float) mSplitterPosition / (float) measuredWidth; } } else if (mSplitterPosition != Integer.MIN_VALUE && mSplitterPositionPercent < 0) { if (!between(mSplitterPosition, getMinSplitterPosition(), getMaxSplitterPosition())) { mSplitterPosition = clamp(mSplitterPosition, getMinSplitterPosition(), getMaxSplitterPosition()); } mSplitterPositionPercent = (float) mSplitterPosition / (float) measuredWidth; } mSplitterBounds.set(mSplitterPosition - (mSplitterSize / 2), 0, mSplitterPosition + (mSplitterSize / 2), measuredHeight); mSplitterTouchBounds.set(mSplitterBounds.left - mSplitterTouchSlop, mSplitterBounds.top, mSplitterBounds.right + mSplitterTouchSlop, mSplitterBounds.bottom); break; } case ORIENTATION_VERTICAL: { if (mSplitterPosition == Integer.MIN_VALUE && mSplitterPositionPercent < 0) { mSplitterPosition = measuredHeight / 2; } else if (mSplitterPosition == Integer.MIN_VALUE && mSplitterPositionPercent >= 0) { mSplitterPosition = (int) (measuredHeight * mSplitterPositionPercent); if (!between(mSplitterPosition, getMinSplitterPosition(), getMaxSplitterPosition())) { mSplitterPosition = clamp(mSplitterPosition, getMinSplitterPosition(), getMaxSplitterPosition()); mSplitterPositionPercent = (float) mSplitterPosition / (float) measuredHeight; } } else if (mSplitterPosition != Integer.MIN_VALUE && mSplitterPositionPercent < 0) { if (!between(mSplitterPosition, getMinSplitterPosition(), getMaxSplitterPosition())) { mSplitterPosition = clamp(mSplitterPosition, getMinSplitterPosition(), getMaxSplitterPosition()); } mSplitterPositionPercent = (float) mSplitterPosition / (float) measuredHeight; } mSplitterBounds.set(0, mSplitterPosition - (mSplitterSize / 2), measuredWidth, mSplitterPosition + (mSplitterSize / 2)); mSplitterTouchBounds.set(mSplitterBounds.left, mSplitterBounds.top - mSplitterTouchSlop / 2, mSplitterBounds.right, mSplitterBounds.bottom + mSplitterTouchSlop / 2); break; } } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int measuredWidth = getMeasuredWidth(); int measuredHeight = getMeasuredHeight(); check(); if (measuredWidth > 0 && measuredHeight > 0) { computeSplitterPosition(); switch (mOrientation) { case ORIENTATION_HORIZONTAL: { getChildAt(0).measure(MeasureSpec.makeMeasureSpec(mSplitterPosition - (mSplitterSize / 2), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY)); getChildAt(1).measure(MeasureSpec.makeMeasureSpec(measuredWidth - (mSplitterSize / 2) - mSplitterPosition, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY)); break; } case ORIENTATION_VERTICAL: { getChildAt(0).measure(MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(mSplitterPosition - (mSplitterSize / 2), MeasureSpec.EXACTLY)); getChildAt(1).measure(MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(measuredHeight - (mSplitterSize / 2) - mSplitterPosition, MeasureSpec.EXACTLY)); break; } } isMeasured = true; } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int w = r - l; int h = b - t; switch (mOrientation) { case ORIENTATION_HORIZONTAL: { getChildAt(0).layout(0, 0, mSplitterPosition - (mSplitterSize / 2), h); getChildAt(1).layout(mSplitterPosition + (mSplitterSize / 2), 0, r, h); break; } case ORIENTATION_VERTICAL: { getChildAt(0).layout(0, 0, w, mSplitterPosition - (mSplitterSize / 2)); getChildAt(1).layout(0, mSplitterPosition + (mSplitterSize / 2), w, h); break; } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean remeasure = false; int offset = mSplitterSize; if (event.isShiftPressed()) { offset *= 5; } switch (mOrientation) { case ORIENTATION_HORIZONTAL: if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { mSplitterPosition = clamp(mSplitterPosition - offset, getMinSplitterPosition(), getMaxSplitterPosition()); mSplitterPositionPercent = -1; remeasure = true; } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { mSplitterPosition = clamp(mSplitterPosition + offset, getMinSplitterPosition(), getMaxSplitterPosition()); mSplitterPositionPercent = -1; remeasure = true; } break; case ORIENTATION_VERTICAL: if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { mSplitterPosition = clamp(mSplitterPosition - offset, getMinSplitterPosition(), getMaxSplitterPosition()); mSplitterPositionPercent = -1; remeasure = true; } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { mSplitterPosition = clamp(mSplitterPosition + offset, getMinSplitterPosition(), getMaxSplitterPosition()); mSplitterPositionPercent = -1; remeasure = true; } break; } if (remeasure) { remeasure(); notifySplitterPositionChanged(true); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onTouchEvent(MotionEvent event) { if (mSplitterMovable) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: handleTouchDown(x, y); break; case MotionEvent.ACTION_MOVE: handleTouchMove(x, y); break; case MotionEvent.ACTION_UP: handleTouchUp(x, y); break; } return true; } return false; } private void handleTouchDown(int x, int y) { if (mSplitterTouchBounds.contains(x, y)) { performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); isDragging = true; mSplitterDraggingBounds.set(mSplitterBounds); invalidate(mSplitterDraggingBounds); lastTouchX = x; lastTouchY = y; } } private void handleTouchMove(int x, int y) { if (isDragging) { if (!isMovingSplitter) { // Verify we've moved far enough to leave the touch bounds before moving the splitter if (mSplitterTouchBounds.contains(x, y)) { return; } else { isMovingSplitter = true; } } boolean take = true; switch (mOrientation) { case ORIENTATION_HORIZONTAL: { mSplitterDraggingBounds.offset(x - lastTouchX, 0); if (mSplitterDraggingBounds.centerX() < getMinSplitterPosition()) { take = false; mSplitterDraggingBounds.offset(getMinSplitterPosition() - mSplitterDraggingBounds.centerX(), 0); } if (mSplitterDraggingBounds.centerX() > getMaxSplitterPosition()) { take = false; mSplitterDraggingBounds.offset(getMaxSplitterPosition() - mSplitterDraggingBounds.centerX(), 0); } break; } case ORIENTATION_VERTICAL: { mSplitterDraggingBounds.offset(0, y - lastTouchY); if (mSplitterDraggingBounds.centerY() < getMinSplitterPosition()) { take = false; mSplitterDraggingBounds.offset(0, getMinSplitterPosition() - mSplitterDraggingBounds.centerY()); } if (mSplitterDraggingBounds.centerY() > getMaxSplitterPosition()) { take = false; mSplitterDraggingBounds.offset(0, getMaxSplitterPosition() - mSplitterDraggingBounds.centerY()); } break; } } if (take) { lastTouchX = x; lastTouchY = y; } invalidate(); } } private void handleTouchUp(int x, int y) { if (isDragging) { isDragging = false; isMovingSplitter = false; switch (mOrientation) { case ORIENTATION_HORIZONTAL: { mSplitterPosition = clamp(x, getMinSplitterPosition(), getMaxSplitterPosition()); mSplitterPositionPercent = -1; break; } case ORIENTATION_VERTICAL: { mSplitterPosition = clamp(y, getMinSplitterPosition(), getMaxSplitterPosition()); mSplitterPositionPercent = -1; break; } } remeasure(); notifySplitterPositionChanged(true); } } private int getMinSplitterPosition() { return mPaneSizeMin; } private int getMaxSplitterPosition() { switch (mOrientation) { case ORIENTATION_HORIZONTAL: return getMeasuredWidth() - mPaneSizeMin; case ORIENTATION_VERTICAL: return getMeasuredHeight() - mPaneSizeMin; } return 0; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.mSplitterPositionPercent = mSplitterPositionPercent; return ss; } @Override public void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); setSplitterPositionPercent(ss.mSplitterPositionPercent); } /** * Convenience for calling own measure method. */ private void remeasure() { // TODO: Performance: Guard against calling too often, can it be done without requestLayout? forceLayout(); measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY) ); requestLayout(); } /** * Checks that we have exactly two children. */ private void check() { if (getChildCount() != 2) { throw new RuntimeException("SplitPaneLayout must have exactly two child views."); } } private void enforcePaneSizeMin() { } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (mSplitterDrawable != null) { mSplitterDrawable.setState(getDrawableState()); mSplitterDrawable.setBounds(mSplitterBounds); mSplitterDrawable.draw(canvas); } if (isDragging) { mSplitterDraggingDrawable.setState(getDrawableState()); mSplitterDraggingDrawable.setBounds(mSplitterDraggingBounds); mSplitterDraggingDrawable.draw(canvas); } } /** * Gets the current drawable used for the splitter. * * @return the drawable used for the splitter */ public Drawable getSplitterDrawable() { return mSplitterDrawable; } /** * Sets the drawable used for the splitter. * * @param splitterDrawable the desired orientation of the layout */ public void setSplitterDrawable(Drawable splitterDrawable) { mSplitterDrawable = splitterDrawable; if (getChildCount() == 2) { remeasure(); } } /** * Gets the current drawable used for the splitter dragging overlay. * * @return the drawable used for the splitter */ public Drawable getSplitterDraggingDrawable() { return mSplitterDraggingDrawable; } /** * Sets the drawable used for the splitter dragging overlay. * * @param splitterDraggingDrawable the drawable to use while dragging the splitter */ public void setSplitterDraggingDrawable(Drawable splitterDraggingDrawable) { mSplitterDraggingDrawable = splitterDraggingDrawable; if (isDragging) { invalidate(); } } /** * Gets the current orientation of the layout. * * @return the orientation of the layout */ public int getOrientation() { return mOrientation; } /** * Sets the orientation of the layout. * * @param orientation the desired orientation of the layout */ public void setOrientation(int orientation) { if (mOrientation != orientation) { mOrientation = orientation; if (getChildCount() == 2) { remeasure(); } } } /** * Gets the current size of the splitter in pixels. * * @return the size of the splitter */ public int getSplitterSize() { return mSplitterSize; } /** * Sets the current size of the splitter in pixels. * * @param splitterSize the desired size of the splitter */ public void setSplitterSize(int splitterSize) { mSplitterSize = splitterSize; if (getChildCount() == 2) { remeasure(); } } /** * Gets whether the splitter is movable by the user. * * @return whether the splitter is movable */ public boolean isSplitterMovable() { return mSplitterMovable; } /** * Sets whether the splitter is movable by the user. * * @param splitterMovable whether the splitter is movable */ public void setSplitterMovable(boolean splitterMovable) { mSplitterMovable = splitterMovable; } /** * Gets the current position of the splitter in pixels. * * @return the position of the splitter */ public int getSplitterPosition() { return mSplitterPosition; } /** * Sets the current position of the splitter in pixels. * * @param position the desired position of the splitter */ public void setSplitterPosition(int position) { mSplitterPosition = clamp(position, 0, Integer.MAX_VALUE); mSplitterPositionPercent = -1; remeasure(); notifySplitterPositionChanged(false); } /** * Gets the current position of the splitter as a percent. * * @return the position of the splitter */ public float getSplitterPositionPercent() { return mSplitterPositionPercent; } /** * Sets the current position of the splitter as a percentage of the layout. * * @param position the desired position of the splitter */ public void setSplitterPositionPercent(float position) { mSplitterPosition = Integer.MIN_VALUE; mSplitterPositionPercent = clamp(position, 0, 1); remeasure(); notifySplitterPositionChanged(false); } /** * Gets the current "touch slop" which is used to extends the grab size of the splitter * and requires the splitter to be dragged at least this far to be considered a move. * * @return the current "touch slop" of the splitter */ public int getSplitterTouchSlop() { return mSplitterTouchSlop; } /** * Sets the current "touch slop" which is used to extends the grab size of the splitter * and requires the splitter to be dragged at least this far to be considered a move. * * @param splitterTouchSlop the desired "touch slop" of the splitter */ public void setSplitterTouchSlop(int splitterTouchSlop) { this.mSplitterTouchSlop = splitterTouchSlop; computeSplitterPosition(); } /** * Gets the minimum size of panes, in pixels. * * @return the minimum size of panes, in pixels. */ public int getPaneSizeMin() { return mPaneSizeMin; } /** * Sets the minimum size of panes, in pixels. * * @param paneSizeMin the minimum size of panes, in pixels */ public void setPaneSizeMin(int paneSizeMin) { mPaneSizeMin = paneSizeMin; if (isMeasured) { int newSplitterPosition = clamp(mSplitterPosition, getMinSplitterPosition(), getMaxSplitterPosition()); if(newSplitterPosition != mSplitterPosition) { setSplitterPosition(newSplitterPosition); } } } /** * Gets the OnSplitterPositionChangedListener to receive callbacks when the splitter position is changed * * @return the OnSplitterPositionChangedListener to receive callbacks when the splitter position is changed */ public OnSplitterPositionChangedListener getOnSplitterPositionChangedListener() { return mOnSplitterPositionChangedListener; } /** * Sets the OnSplitterPositionChangedListener to receive callbacks when the splitter position is changed * * @param l the OnSplitterPositionChangedListener to receive callbacks when the splitter position is changed */ public void setOnSplitterPositionChangedListener(OnSplitterPositionChangedListener l) { this.mOnSplitterPositionChangedListener = l; } private void notifySplitterPositionChanged(boolean fromUser) { if (mOnSplitterPositionChangedListener != null) { Log.d("SPL", "Splitter Position Changed"); mOnSplitterPositionChangedListener.onSplitterPositionChanged(this, fromUser); } } private static float clamp(float value, float min, float max) { if (value < min) { return min; } else if (value > max) { return max; } return value; } private static int clamp(int value, int min, int max) { if (value < min) { return min; } else if (value > max) { return max; } return value; } private static boolean between(int value, int min, int max) { return min <= value && value <= max; } /** * Holds important values when we need to save instance state. */ public static class SavedState extends BaseSavedState { public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; float mSplitterPositionPercent; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); mSplitterPositionPercent = in.readFloat(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeFloat(mSplitterPositionPercent); } } }
apache-2.0
cjw363/zhiyue
ZhiYue/src/com/cjw/zhiyue/ui/adapter/music/SearchSuccessAdapter.java
1281
package com.cjw.zhiyue.ui.adapter.music; import java.util.List; import com.cjw.zhiyue.R; import com.cjw.zhiyue.domain.SearchInfo.SearchSongInfo; import com.cjw.zhiyue.ui.adapter.MyBaseAdapter; import com.cjw.zhiyue.ui.holder.BaseHolder; import com.cjw.zhiyue.ui.holder.music.SearchSuccessHolder; import com.cjw.zhiyue.utils.UIUtils; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SearchSuccessAdapter extends MyBaseAdapter<SearchSongInfo> { private RecyclerView recyclerview; public SearchSuccessAdapter(List<SearchSongInfo> data, RecyclerView recyclerview) { super(data); this.recyclerview=recyclerview; } @Override public boolean isHasMore() { return false; } @Override public void onLoadMore() { } @Override public View initHolderView(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.item_search_success, parent, false); return itemView; } @Override public BaseHolder<SearchSongInfo> getHolder(View initHolderView, OnItemClickListener<SearchSongInfo> itemClickListener, int viewType) { return new SearchSuccessHolder(initHolderView,itemClickListener,recyclerview); } }
apache-2.0
ge0ffrey/optaplanner
optaplanner-persistence/optaplanner-persistence-jaxb/src/test/java/org/optaplanner/persistence/jaxb/api/score/buildin/bendablelong/BendableLongScoreJaxbXmlAdapterTest.java
2175
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.persistence.jaxb.api.score.buildin.bendablelong; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.junit.jupiter.api.Test; import org.optaplanner.core.api.score.buildin.bendablelong.BendableLongScore; import org.optaplanner.persistence.jaxb.api.score.AbstractScoreJaxbXmlAdapterTest; public class BendableLongScoreJaxbXmlAdapterTest extends AbstractScoreJaxbXmlAdapterTest { @Test public void serializeAndDeserialize() { assertSerializeAndDeserialize(null, new TestBendableLongScoreWrapper(null)); BendableLongScore score = BendableLongScore.of(new long[] { 1000L, 200L }, new long[] { 34L }); assertSerializeAndDeserialize(score, new TestBendableLongScoreWrapper(score)); score = BendableLongScore.ofUninitialized(-7, new long[] { 1000L, 200L }, new long[] { 34L }); assertSerializeAndDeserialize(score, new TestBendableLongScoreWrapper(score)); } @XmlRootElement public static class TestBendableLongScoreWrapper extends TestScoreWrapper<BendableLongScore> { @XmlJavaTypeAdapter(BendableLongScoreJaxbXmlAdapter.class) private BendableLongScore score; @SuppressWarnings("unused") private TestBendableLongScoreWrapper() { } public TestBendableLongScoreWrapper(BendableLongScore score) { this.score = score; } @Override public BendableLongScore getScore() { return score; } } }
apache-2.0
malcolmgreaves/berkeleylm
src/edu/berkeley/nlp/lm/map/HashNgramMap.java
23115
package edu.berkeley.nlp.lm.map; import java.util.Arrays; import java.util.Collections; import java.util.List; import edu.berkeley.nlp.lm.ConfigOptions; import edu.berkeley.nlp.lm.ContextEncodedNgramLanguageModel.LmContextInfo; import edu.berkeley.nlp.lm.array.CustomWidthArray; import edu.berkeley.nlp.lm.array.LongArray; import edu.berkeley.nlp.lm.collections.Iterators; import edu.berkeley.nlp.lm.util.Annotations.OutputParameter; import edu.berkeley.nlp.lm.util.Annotations.PrintMemoryCount; import edu.berkeley.nlp.lm.util.Logger; import edu.berkeley.nlp.lm.util.LongRef; import edu.berkeley.nlp.lm.values.ValueContainer; /** * * @author adampauls * * @param <T> */ public final class HashNgramMap<T> extends AbstractNgramMap<T> implements ContextEncodedNgramMap<T> { /** * */ private static final long serialVersionUID = 1L; @PrintMemoryCount private ExplicitWordHashMap[] explicitMaps; @PrintMemoryCount private final ImplicitWordHashMap[] implicitMaps; @PrintMemoryCount private final UnigramHashMap implicitUnigramMap; private long[] initCapacities; private final double maxLoadFactor; private final boolean isExplicit; private final boolean reversed; private final boolean storeSuffixOffsets; public static <T> HashNgramMap<T> createImplicitWordHashNgramMap(final ValueContainer<T> values, final ConfigOptions opts, final LongArray[] numNgramsForEachWord, final boolean reversed) { return new HashNgramMap<T>(values, opts, numNgramsForEachWord, reversed); } private HashNgramMap(final ValueContainer<T> values, final ConfigOptions opts, final LongArray[] numNgramsForEachWord, final boolean reversed) { super(values, opts); this.reversed = reversed; this.maxLoadFactor = opts.hashTableLoadFactor; this.storeSuffixOffsets = values.storeSuffixoffsets(); final int maxNgramOrder = numNgramsForEachWord.length; explicitMaps = null; isExplicit = false; implicitMaps = new ImplicitWordHashMap[maxNgramOrder - 1]; final long numWords = numNgramsForEachWord[0].size(); implicitUnigramMap = new UnigramHashMap(numWords, this); initCapacities = null; final long maxSize = getMaximumSize(numNgramsForEachWord); // a little ugly: store word ranges for all orders in the same array to increase cache locality // also, if we can, store two ints per long for cache locality final boolean fitsInInt = maxSize < Integer.MAX_VALUE; final int logicalNumRangeEntries = (maxNgramOrder - 1) * (int) numWords; final long[] wordRanges = new long[fitsInInt ? (logicalNumRangeEntries / 2 + logicalNumRangeEntries % 2) : logicalNumRangeEntries]; values.setMap(this); values.setSizeAtLeast(numWords, 0); for (int ngramOrder = 1; ngramOrder < maxNgramOrder; ++ngramOrder) { final long numNgramsForPreviousOrder = ngramOrder == 1 ? numWords : implicitMaps[ngramOrder - 2].getCapacity(); implicitMaps[ngramOrder - 1] = new ImplicitWordHashMap(numNgramsForEachWord[ngramOrder], wordRanges, ngramOrder, maxNgramOrder - 1, numNgramsForPreviousOrder, (int) numWords, this, fitsInInt, !opts.storeRankedProbBackoffs); values.setSizeAtLeast(implicitMaps[ngramOrder - 1].getCapacity(), ngramOrder); } } private long getMaximumSize(final LongArray[] numNgramsForEachWord) { long max = Long.MIN_VALUE; for (int ngramOrder = 0; ngramOrder < numNgramsForEachWord.length; ++ngramOrder) { max = Math.max(max, getSizeOfOrder(numNgramsForEachWord[ngramOrder])); } return max; } private long getSizeOfOrder(final LongArray numNgramsForEachWord) { long currStart = 0; for (int w = (0); w < numNgramsForEachWord.size(); ++w) { currStart += getRangeSizeForWord(numNgramsForEachWord, w); } return currStart; } /** * @param numNgramsForEachWord * @param w * @return */ long getRangeSizeForWord(final LongArray numNgramsForEachWord, int w) { final long numNgrams = numNgramsForEachWord.get(w); final long rangeSize = numNgrams <= 3 ? numNgrams : Math.round(numNgrams * 1.0 / maxLoadFactor); return rangeSize; } /** * Note: Explicit HashNgramMap can grow beyond maxNgramOrder * * @param <T> * @param values * @param opts * @param maxNgramOrder * @param reversed * @return */ public static <T> HashNgramMap<T> createExplicitWordHashNgramMap(final ValueContainer<T> values, final ConfigOptions opts, final int maxNgramOrder, final boolean reversed) { return new HashNgramMap<T>(values, opts, maxNgramOrder, reversed); } private HashNgramMap(final ValueContainer<T> values, final ConfigOptions opts, final int maxNgramOrder, final boolean reversed) { super(values, opts); this.reversed = reversed; this.storeSuffixOffsets = values.storeSuffixoffsets(); this.maxLoadFactor = opts.hashTableLoadFactor; implicitMaps = null; implicitUnigramMap = null; isExplicit = true; explicitMaps = new ExplicitWordHashMap[maxNgramOrder]; initCapacities = new long[maxNgramOrder]; Arrays.fill(initCapacities, 100); values.setMap(this); } private HashNgramMap(final ValueContainer<T> values, final ConfigOptions opts, final long[] newCapacities, final boolean reversed, final ExplicitWordHashMap[] partialMaps) { super(values, opts); this.reversed = reversed; this.storeSuffixOffsets = values.storeSuffixoffsets(); this.maxLoadFactor = opts.hashTableLoadFactor; implicitMaps = null; implicitUnigramMap = null; isExplicit = true; explicitMaps = Arrays.copyOf(partialMaps, newCapacities.length); this.initCapacities = newCapacities; values.setMap(this); } /** * @param values * @param newCapacities * @param ngramOrder * @return */ private ExplicitWordHashMap initMap(final long newCapacity, final int ngramOrder) { final ExplicitWordHashMap newMap = new ExplicitWordHashMap(newCapacity); explicitMaps[ngramOrder] = newMap; values.setSizeAtLeast(explicitMaps[ngramOrder].getCapacity(), ngramOrder); return newMap; } @Override public long put(final int[] ngram, final int startPos, final int endPos, final T val) { return putHelp(ngram, startPos, endPos, val, false); } /** * @param ngram * @param startPos * @param endPos * @param val * @return */ private long putHelp(final int[] ngram, final int startPos, final int endPos, final T val, final boolean forcedNew) { final int ngramOrder = endPos - startPos - 1; HashMap map = getHashMapForOrder(ngramOrder); if (!forcedNew && map instanceof ExplicitWordHashMap && map.getLoadFactor() >= maxLoadFactor) { rehash(ngramOrder, map.getCapacity() * 3 / 2, 1); map = getHashMapForOrder(ngramOrder); } final long key = getKey(ngram, startPos, endPos); if (key < 0) return -1L; return putHelp(map, ngram, startPos, endPos, key, val, forcedNew); } /** * @param ngramOrder * @return */ private HashMap getHashMapForOrder(final int ngramOrder) { HashMap map = getMap(ngramOrder); if (map == null) { final long newCapacity = initCapacities[ngramOrder]; assert newCapacity >= 0 : "Bad capacity " + newCapacity + " for order " + ngramOrder; map = initMap(newCapacity, ngramOrder); } return map; } /** * Warning: does not rehash if load factor is exceeded, must call * rehashIfNecessary explicitly. This is so that the offsets returned remain * valid. Basically, you should not use this function unless you really know * what you're doing. * * @param ngram * @param startPos * @param endPos * @param contextOffset * @param val * @return */ public long putWithOffset(final int[] ngram, final int startPos, final int endPos, final long contextOffset, final T val) { final int ngramOrder = endPos - startPos - 1; final long key = combineToKey(ngram[endPos - 1], contextOffset); final HashMap map = getHashMapForOrder(ngramOrder); return putHelp(map, ngram, startPos, endPos, key, val, false); } /** * Warning: does not rehash if load factor is exceeded, must call * rehashIfNecessary explicitly. This is so that the offsets returned remain * valid. Basically, you should not use this function unless you really know * what you're doing. * * @param ngram * @param startPos * @param endPos * @param contextOffset * @param val * @return */ public long putWithOffsetAndSuffix(final int[] ngram, final int startPos, final int endPos, final long contextOffset, final long suffixOffset, final T val) { final int ngramOrder = endPos - startPos - 1; final long key = combineToKey(ngram[endPos - 1], contextOffset); final HashMap map = getHashMapForOrder(ngramOrder); return putHelpWithSuffixIndex(map, ngram, startPos, endPos, key, val, false, suffixOffset); } public void rehashIfNecessary(int num) { if (explicitMaps == null) return; for (int ngramOrder = 0; ngramOrder < explicitMaps.length; ++ngramOrder) { if (explicitMaps[ngramOrder] == null) initCapacities[ngramOrder] = Math.max(100, num) * 3/2; else if (explicitMaps[ngramOrder].getLoadFactor(num) >= maxLoadFactor) { rehash(ngramOrder, (explicitMaps[ngramOrder].getCapacity() + num) * 3 / 2, num); return; } } } private long putHelp(final HashMap map, final int[] ngram, final int startPos, final int endPos, final long key, final T val, final boolean forcedNew) { final long suffixIndex = storeSuffixOffsets ? getSuffixOffset(ngram, startPos, endPos) : -1L; return putHelpWithSuffixIndex(map, ngram, startPos, endPos, key, val, forcedNew, suffixIndex); } /** * @param map * @param ngram * @param startPos * @param endPos * @param key * @param val * @param forcedNew * @param suffixIndex * @return */ private long putHelpWithSuffixIndex(final HashMap map, final int[] ngram, final int startPos, final int endPos, final long key, final T val, final boolean forcedNew, final long suffixIndex) { final int ngramOrder = endPos - startPos - 1; final long oldSize = map.size(); final long index = map.put(key); final boolean addWorked = values.add(ngram, startPos, endPos, ngramOrder, index, contextOffsetOf(key), wordOf(key), val, suffixIndex, map.size() > oldSize || forcedNew); if (!addWorked) return -1; return index; } @Override public long getValueAndOffset(final long contextOffset, final int contextOrder, final int word, @OutputParameter final T outputVal) { return getOffsetForContextEncoding(contextOffset, contextOrder, word, outputVal); } @Override public long getOffset(final long contextOffset, final int contextOrder, final int word) { return getOffsetForContextEncoding(contextOffset, contextOrder, word, null); } @Override public int[] getNgramFromContextEncoding(final long contextOffset, final int contextOrder, final int word) { final int[] ret = new int[Math.max(1, contextOrder + 2)]; getNgramFromContextEncodingHelp(contextOffset, contextOrder, word, ret); return ret; } /** * @param contextOffset * @param contextOrder * @param word * @param scratch * @return */ private void getNgramFromContextEncodingHelp(final long contextOffset, final int contextOrder, final int word, final int[] scratch) { if (contextOrder < 0) { scratch[0] = word; } else { long contextOffset_ = contextOffset; int word_ = word; scratch[reversed ? 0 : (scratch.length - 1)] = word_; for (int i = 0; i <= contextOrder; ++i) { final int ngramOrder = contextOrder - i; final long key = getKey(contextOffset_, ngramOrder); contextOffset_ = contextOffsetOf(key); word_ = wordOf(key); scratch[reversed ? (i + 1) : (scratch.length - i - 2)] = word_; } } } public int getNextWord(final long offset, final int ngramOrder) { return wordOf(getKey(offset, ngramOrder)); } public long getNextContextOffset(final long offset, final int ngramOrder) { return contextOffsetOf(getKey(offset, ngramOrder)); } /** * Gets the "key" (word + context offset) for a given offset * * @param contextOffset_ * @param ngramOrder * @return */ private long getKey(final long offset, final int ngramOrder) { return getMap(ngramOrder).getKey(offset); } public int getFirstWordForOffset(final long offset, final int ngramOrder) { final long key = getMap(ngramOrder).getKey(offset); if (ngramOrder == 0) return wordOf(key); else return getFirstWordForOffset(contextOffsetOf(key), ngramOrder - 1); } public int getLastWordForOffset(final long offset, final int ngramOrder) { final long key = getMap(ngramOrder).getKey(offset); return wordOf(key); } public int[] getNgramForOffset(final long offset, final int ngramOrder) { final int[] ret = new int[ngramOrder + 1]; return getNgramForOffset(offset, ngramOrder, ret); } public int[] getNgramForOffset(final long offset, final int ngramOrder, final int[] ret) { long offset_ = offset; for (int i = 0; i <= ngramOrder; ++i) { final long key = getMap(ngramOrder - i).getKey(offset_); offset_ = contextOffsetOf(key); final int word_ = wordOf(key); ret[reversed ? (i) : (ngramOrder - i)] = word_; } return ret; } /** * @param contextOffset_ * @param contextOrder * @param word * @param logFailure * @return */ private long getOffsetForContextEncoding(final long contextOffset_, final int contextOrder, final int word, @OutputParameter final T outputVal) { if (word < 0) return -1; final int ngramOrder = contextOrder + 1; final long contextOffset = contextOffset_ >= 0 ? contextOffset_ : 0; final long key = combineToKey(word, contextOffset); final long offset = getOffsetHelpFromMap(ngramOrder, key); if (outputVal != null && offset >= 0) { values.getFromOffset(offset, ngramOrder, outputVal); } return offset; } private long getOffsetHelpFromMap(int ngramOrder, long key) { if (isExplicit) { return (ngramOrder >= explicitMaps.length || explicitMaps[ngramOrder] == null) ? -1 : explicitMaps[ngramOrder].getOffset(key); } return ngramOrder == 0 ? implicitUnigramMap.getOffset(key) : implicitMaps[ngramOrder - 1].getOffset(key); } private void rehash(final int changedNgramOrder, final long newCapacity, final int numAdding) { assert isExplicit; final long[] newCapacities = new long[explicitMaps.length]; Arrays.fill(newCapacities, -1L); assert changedNgramOrder >= 0; long largestCapacity = 0L; for (int ngramOrder = 0; ngramOrder < explicitMaps.length; ++ngramOrder) { if (explicitMaps[ngramOrder] == null) break; if (ngramOrder < changedNgramOrder) { newCapacities[ngramOrder] = explicitMaps[ngramOrder].getCapacity(); } else if (ngramOrder == changedNgramOrder) { newCapacities[ngramOrder] = newCapacity; } else { newCapacities[ngramOrder] = explicitMaps[ngramOrder].getLoadFactor(numAdding) >= maxLoadFactor / 2 ? ((explicitMaps[ngramOrder].getCapacity() + numAdding) * 3 / 2) : explicitMaps[ngramOrder].getCapacity(); largestCapacity = Math.max(largestCapacity, newCapacities[ngramOrder]); } assert newCapacities[ngramOrder] >= 0 : "Bad capacity " + newCapacities[ngramOrder]; } final ValueContainer<T> newValues = values.createFreshValues(newCapacities); final HashNgramMap<T> newMap = new HashNgramMap<T>(newValues, opts, newCapacities, reversed, Arrays.copyOf(explicitMaps, changedNgramOrder)); for (int ngramOrder = 0; ngramOrder < explicitMaps.length; ++ngramOrder) { final ExplicitWordHashMap currHashMap = explicitMaps[ngramOrder]; if (currHashMap == null) { // We haven't initialized this map yet, but make sure there is enough space when we do. initCapacities[ngramOrder] = largestCapacity; continue; } final ExplicitWordHashMap newHashMap = (ExplicitWordHashMap) newMap.getHashMapForOrder(ngramOrder); final T val = values.getScratchValue(); final int[] scratchArray = new int[ngramOrder + 1]; for (long actualIndex = 0; actualIndex < currHashMap.getCapacity(); ++actualIndex) { final long key = currHashMap.getKey(actualIndex); if (currHashMap.isEmptyKey(key)) continue; getNgramFromContextEncodingHelp(contextOffsetOf(key), ngramOrder - 1, wordOf(key), scratchArray); final long newKey = newMap.getKey(scratchArray, 0, scratchArray.length); assert newKey >= 0 : "Failure for old n-gram " + Arrays.toString(scratchArray) + " :: " + newKey; final long index = newHashMap.put(newKey); assert index >= 0; final long suffixIndex = storeSuffixOffsets ? newMap.getSuffixOffset(scratchArray, 0, scratchArray.length) : -1L; assert !storeSuffixOffsets || suffixIndex >= 0 : "Could not find suffix offset for " + Arrays.toString(scratchArray); values.getFromOffset(actualIndex, ngramOrder, val); final boolean addWorked = newMap.values.add(scratchArray, 0, scratchArray.length, ngramOrder, index, contextOffsetOf(newKey), wordOf(newKey), val, suffixIndex, true); assert addWorked; } values.clearStorageForOrder(ngramOrder); } System.arraycopy(newMap.explicitMaps, 0, explicitMaps, 0, newMap.explicitMaps.length); values.setFromOtherValues(newValues); values.setMap(this); } /** * @param ngram * @param startPos * @param endPos * @return */ private long getOffsetFromRawNgram(final int[] ngram, final int startPos, final int endPos) { if (containsOutOfVocab(ngram, startPos, endPos)) return -1; final int ngramOrder = endPos - startPos - 1; if (ngramOrder >= getMaxNgramOrder()) return -1; final long key = getKey(ngram, startPos, endPos); if (key < 0) return -1; final HashMap currMap = getMap(ngramOrder); if (currMap == null) return -1; final long index = currMap.getOffset(key); return index; } @Override public LmContextInfo getOffsetForNgram(final int[] ngram, final int startPos, final int endPos) { final LmContextInfo lmContextInfo = new LmContextInfo(); for (int start = endPos - 1; start >= startPos; --start) { final long offset = getOffsetFromRawNgram(ngram, start, endPos); if (offset < 0) break; lmContextInfo.offset = offset; lmContextInfo.order = endPos - start - 1; } return lmContextInfo; } /** * Like {@link #getOffsetForNgram(int[], int, int)}, but assumes that the * full n-gram is in the map (i.e. does not back off to the largest suffix * which is in the model). * * @param ngram * @param startPos * @param endPos * @return */ public long getOffsetForNgramInModel(final int[] ngram, final int startPos, final int endPos) { return getOffsetFromRawNgram(ngram, startPos, endPos); } @Override public void handleNgramsFinished(final int justFinishedOrder) { } @Override public void initWithLengths(final List<Long> numNGrams) { } @Override public void trim() { for (int ngramOrder = 0; ngramOrder < getMaxNgramOrder(); ++ngramOrder) { final HashMap currMap = getMap(ngramOrder); if (currMap == null) break; values.trimAfterNgram(ngramOrder, currMap.getCapacity()); Logger.logss("Load factor for " + (ngramOrder + 1) + ": " + currMap.getLoadFactor()); } values.trim(); } /** * @param ngram * @param endPos * @return */ private long getSuffixOffset(final int[] ngram, final int startPos, final int endPos) { if (endPos - startPos == 1) return 0; final long offset = getOffsetFromRawNgram(ngram, reversed ? startPos : (startPos + 1), reversed ? (endPos - 1) : endPos); return offset; } /** * Gets the offset of the context for an n-gram (represented by offset) * * @param offset * @return */ public long getPrefixOffset(final long offset, final int ngramOrder) { if (ngramOrder == 0) return -1; return contextOffsetOf(getKey(offset, ngramOrder)); } private long getKey(final int[] ngram, final int startPos, final int endPos) { long contextOffset = 0; for (int ngramOrder = 0; ngramOrder < endPos - startPos - 1; ++ngramOrder) { final int currNgramPos = reversed ? (endPos - ngramOrder - 1) : (startPos + ngramOrder); contextOffset = getOffsetForContextEncoding(contextOffset, ngramOrder - 1, ngram[currNgramPos], null); if (contextOffset == -1L) { return -1; } } return combineToKey(headWord(ngram, startPos, endPos), contextOffset); } private int headWord(final int[] ngram, final int startPos, final int endPos) { return reversed ? ngram[startPos] : ngram[endPos - 1]; } @Override public int getMaxNgramOrder() { return explicitMaps == null ? (implicitMaps.length + 1) : explicitMaps.length; } @Override public long getNumNgrams(final int ngramOrder) { return getMap(ngramOrder).size(); } @Override public Iterable<Entry<T>> getNgramsForOrder(final int ngramOrder) { final HashMap map = getMap(ngramOrder); if (map == null) return Collections.emptyList(); else return Iterators.able(new Iterators.Transform<Long, Entry<T>>(map.keys().iterator()) { @Override protected Entry<T> transform(final Long next) { final long offset = next; final T val = values.getScratchValue(); values.getFromOffset(offset, ngramOrder, val); return new Entry<T>(getNgramForOffset(offset, ngramOrder), val); } }); } public Iterable<Long> getNgramOffsetsForOrder(final int ngramOrder) { final HashMap map = getMap(ngramOrder); if (map == null) return Collections.emptyList(); else return map.keys(); } private HashMap getMap(int ngramOrder) { if (explicitMaps == null) { return ngramOrder == 0 ? implicitUnigramMap : implicitMaps[ngramOrder - 1]; } if (ngramOrder >= explicitMaps.length) { int oldLength = explicitMaps.length; explicitMaps = Arrays.copyOf(explicitMaps, explicitMaps.length * 2); initCapacities = Arrays.copyOf(initCapacities, initCapacities.length * 2); Arrays.fill(initCapacities, oldLength, initCapacities.length, 100); } return explicitMaps[ngramOrder]; } public boolean isReversed() { return reversed; } @Override public boolean wordHasBigrams(final int word) { return getMaxNgramOrder() < 2 ? false : (explicitMaps == null ? implicitMaps[0].hasContexts(word) : explicitMaps[1].hasContexts(word)); } @Override public boolean contains(final int[] ngram, final int startPos, final int endPos) { return getOffsetFromRawNgram(ngram, startPos, endPos) >= 0; } @Override public T get(int[] ngram, int startPos, int endPos) { final long offset = getOffsetFromRawNgram(ngram, startPos, endPos); if (offset < 0) { return null; } else { final T val = values.getScratchValue(); values.getFromOffset(offset, endPos - startPos - 1, val); return val; } } public long getTotalSize() { long ret = 0L; for (int ngramOrder = 0; ngramOrder < getMaxNgramOrder(); ++ngramOrder) { final HashMap currMap = getMap(ngramOrder); if (currMap == null) break; ret += currMap.size(); } return ret; } @Override public CustomWidthArray getValueStoringArray(final int ngramOrder) { return (ngramOrder == 0 || isExplicit) ? null : implicitMaps[ngramOrder - 1].keys; } @Override public void clearStorage() { if (implicitMaps != null) { for (int i = 0; i < implicitMaps.length; ++i) { implicitMaps[i] = null; } } if (explicitMaps != null) { for (int i = 0; i < explicitMaps.length; ++i) { explicitMaps[i] = null; } } } double getLoadFactor() { return maxLoadFactor; } }
apache-2.0
lvweiwolf/poi-3.16
src/java/org/apache/poi/hssf/model/WorkbookRecordList.java
5694
/* ==================================================================== 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.poi.hssf.model; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.poi.hssf.record.Record; public final class WorkbookRecordList implements Iterable<Record> { private List<Record> records = new ArrayList<Record>(); private int protpos = 0; // holds the position of the protect record. private int bspos = 0; // holds the position of the last bound sheet. private int tabpos = 0; // holds the position of the tabid record private int fontpos = 0; // hold the position of the last font record private int xfpos = 0; // hold the position of the last extended font record private int backuppos = 0; // holds the position of the backup record. private int namepos = 0; // holds the position of last name record private int supbookpos = 0; // holds the position of sup book private int externsheetPos = 0;// holds the position of the extern sheet private int palettepos = -1; // hold the position of the palette, if applicable public void setRecords(List<Record> records) { this.records = records; } public int size() { return records.size(); } public Record get(int i) { return records.get(i); } public void add(int pos, Record r) { records.add(pos, r); if (getProtpos() >= pos) setProtpos( protpos + 1 ); if (getBspos() >= pos) setBspos( bspos + 1 ); if (getTabpos() >= pos) setTabpos( tabpos + 1 ); if (getFontpos() >= pos) setFontpos( fontpos + 1 ); if (getXfpos() >= pos) setXfpos( xfpos + 1 ); if (getBackuppos() >= pos) setBackuppos( backuppos + 1 ); if (getNamepos() >= pos) setNamepos(namepos+1); if (getSupbookpos() >= pos) setSupbookpos(supbookpos+1); if ((getPalettepos() != -1) && (getPalettepos() >= pos)) setPalettepos( palettepos + 1 ); if (getExternsheetPos() >= pos) setExternsheetPos(getExternsheetPos() + 1); } public List<Record> getRecords() { return records; } public Iterator<Record> iterator() { return records.iterator(); } /** * Find the given record in the record list by identity and removes it * * @param record the identical record to be searched for */ public void remove( Object record ) { // can't use List.indexOf here because it checks the records for equality and not identity int i = 0; for (Record r : records) { if (r == record) { remove(i); break; } i++; } } public void remove( int pos ) { records.remove(pos); if (getProtpos() >= pos) setProtpos( protpos - 1 ); if (getBspos() >= pos) setBspos( bspos - 1 ); if (getTabpos() >= pos) setTabpos( tabpos - 1 ); if (getFontpos() >= pos) setFontpos( fontpos - 1 ); if (getXfpos() >= pos) setXfpos( xfpos - 1 ); if (getBackuppos() >= pos) setBackuppos( backuppos - 1 ); if (getNamepos() >= pos) setNamepos(getNamepos()-1); if (getSupbookpos() >= pos) setSupbookpos(getSupbookpos()-1); if ((getPalettepos() != -1) && (getPalettepos() >= pos)) setPalettepos( palettepos - 1 ); if (getExternsheetPos() >= pos) setExternsheetPos( getExternsheetPos() -1); } public int getProtpos() { return protpos; } public void setProtpos(int protpos) { this.protpos = protpos; } public int getBspos() { return bspos; } public void setBspos(int bspos) { this.bspos = bspos; } public int getTabpos() { return tabpos; } public void setTabpos(int tabpos) { this.tabpos = tabpos; } public int getFontpos() { return fontpos; } public void setFontpos(int fontpos) { this.fontpos = fontpos; } public int getXfpos() { return xfpos; } public void setXfpos(int xfpos) { this.xfpos = xfpos; } public int getBackuppos() { return backuppos; } public void setBackuppos(int backuppos) { this.backuppos = backuppos; } public int getPalettepos() { return palettepos; } public void setPalettepos(int palettepos) { this.palettepos = palettepos; } /** * Returns the namepos. * @return int */ public int getNamepos() { return namepos; } /** * Returns the supbookpos. * @return int */ public int getSupbookpos() { return supbookpos; } /** * Sets the namepos. * @param namepos The namepos to set */ public void setNamepos(int namepos) { this.namepos = namepos; } /** * Sets the supbookpos. * @param supbookpos The supbookpos to set */ public void setSupbookpos(int supbookpos) { this.supbookpos = supbookpos; } /** * Returns the externsheetPos. * @return int */ public int getExternsheetPos() { return externsheetPos; } /** * Sets the externsheetPos. * @param externsheetPos The externsheetPos to set */ public void setExternsheetPos(int externsheetPos) { this.externsheetPos = externsheetPos; } }
apache-2.0
jroper/netty
transport/src/main/java/io/netty/channel/EventLoopException.java
463
package io.netty.channel; public class EventLoopException extends ChannelException { private static final long serialVersionUID = -8969100344583703616L; public EventLoopException() { } public EventLoopException(String message, Throwable cause) { super(message, cause); } public EventLoopException(String message) { super(message); } public EventLoopException(Throwable cause) { super(cause); } }
apache-2.0
Jiemamy/factory-enhancer
src/test/java/org/jiemamy/utils/enhancer/aspect/AfterIntIncrementHandler.java
1209
/* * Copyright 2009 Jiemamy Project and the Others. * * 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.jiemamy.utils.enhancer.aspect; import org.jiemamy.utils.enhancer.Invocation; import org.jiemamy.utils.enhancer.InvocationHandler; /** * 戻り値に1加算する。 * @version $Date$ * @author Suguru ARAKAWA (Gluegent, Inc.) */ public class AfterIntIncrementHandler implements InvocationHandler { /** * @return proceed() + 1 */ public Object handle(Invocation invocation) throws Throwable { int result = (Integer) invocation.proceed(); return result + 1; } /** * @return {@code return++} */ @Override public String toString() { return "return++"; } }
apache-2.0
JoelMarcey/buck
starlark/src/test/java/net/starlark/java/syntax/NodePrinterTest.java
14386
/* * Portions Copyright (c) Facebook, Inc. and its affiliates. * * 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. */ // Copyright 2017 The Bazel Authors. 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 net.starlark.java.syntax; import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Joiner; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests {@link Node#toString} and {@code NodePrinter}. */ @RunWith(JUnit4.class) public final class NodePrinterTest { private static StarlarkFile parseFile(String... lines) throws SyntaxError.Exception { ParserInput input = ParserInput.fromLines(lines); StarlarkFile file = StarlarkFile.parse(input); if (!file.ok()) { throw new SyntaxError.Exception(file.errors()); } return file; } private static Statement parseStatement(String... lines) throws SyntaxError.Exception { return parseFile(lines).getStatements().get(0); } private static Expression parseExpression(String... lines) throws SyntaxError.Exception { return Expression.parse(ParserInput.fromLines(lines)); } private static String join(String... lines) { return Joiner.on("\n").join(lines); } /** * Asserts that the given node's pretty print at a given indent level matches the given string. */ private static void assertPrettyMatches(Node node, int indentLevel, String expected) { StringBuilder buf = new StringBuilder(); new NodePrinter(buf, indentLevel).printNode(node); assertThat(buf.toString()).isEqualTo(expected); } /** Asserts that the given node's pretty print with no indent matches the given string. */ private static void assertPrettyMatches(Node node, String expected) { assertPrettyMatches(node, 0, expected); } /** Asserts that the given node's pretty print with one indent matches the given string. */ private static void assertIndentedPrettyMatches(Node node, String expected) { assertPrettyMatches(node, 1, expected); } /** Asserts that the given node's {@code toString} matches the given string. */ private static void assertTostringMatches(Node node, String expected) { assertThat(node.toString()).isEqualTo(expected); } /** * Parses the given string as an expression, and asserts that its pretty print matches the given * string. */ private static void assertExprPrettyMatches(String source, String expected) throws SyntaxError.Exception { Expression node = parseExpression(source); assertPrettyMatches(node, expected); } /** * Parses the given string as an expression, and asserts that its {@code toString} matches the * given string. */ private static void assertExprTostringMatches(String source, String expected) throws SyntaxError.Exception { Expression node = parseExpression(source); assertThat(node.toString()).isEqualTo(expected); } /** * Parses the given string as an expression, and asserts that both its pretty print and {@code * toString} return the original string. */ private static void assertExprBothRoundTrip(String source) throws SyntaxError.Exception { assertExprPrettyMatches(source, source); assertExprTostringMatches(source, source); } /** * Parses the given string as a statement, and asserts that its pretty print with one indent * matches the given string. */ private static void assertStmtIndentedPrettyMatches(String source, String expected) throws SyntaxError.Exception { Statement node = parseStatement(source); assertIndentedPrettyMatches(node, expected); } /** * Parses the given string as an statement, and asserts that its {@code toString} matches the * given string. */ private static void assertStmtTostringMatches(String source, String expected) throws SyntaxError.Exception { Statement node = parseStatement(source); assertThat(node.toString()).isEqualTo(expected); } // Expressions. @Test public void abstractComprehension() throws SyntaxError.Exception { // Covers DictComprehension and ListComprehension. assertExprBothRoundTrip("[z for y in x if True for z in y]"); assertExprBothRoundTrip("{z: x for y in x if True for z in y}"); } @Test public void binaryOperatorExpression() throws SyntaxError.Exception { assertExprPrettyMatches("1 + 2", "(1 + 2)"); assertExprTostringMatches("1 + 2", "1 + 2"); assertExprPrettyMatches("1 + (2 * 3)", "(1 + (2 * 3))"); assertExprTostringMatches("1 + (2 * 3)", "1 + 2 * 3"); } @Test public void conditionalExpression() throws SyntaxError.Exception { assertExprBothRoundTrip("1 if True else 2"); } @Test public void dictExpression() throws SyntaxError.Exception { assertExprBothRoundTrip("{1: \"a\", 2: \"b\"}"); } @Test public void dotExpression() throws SyntaxError.Exception { assertExprBothRoundTrip("o.f"); } @Test public void funcallExpression() throws SyntaxError.Exception { assertExprBothRoundTrip("f()"); assertExprBothRoundTrip("f(a)"); assertExprBothRoundTrip("f(a, b = B, c = C, *d, **e)"); assertExprBothRoundTrip("o.f()"); } @Test public void identifier() throws SyntaxError.Exception { assertExprBothRoundTrip("foo"); } @Test public void indexExpression() throws SyntaxError.Exception { assertExprBothRoundTrip("a[i]"); } @Test public void integerLiteral() throws SyntaxError.Exception { assertExprBothRoundTrip("5"); } @Test public void listLiteralShort() throws SyntaxError.Exception { assertExprBothRoundTrip("[]"); assertExprBothRoundTrip("[5]"); assertExprBothRoundTrip("[5, 6]"); assertExprBothRoundTrip("()"); assertExprBothRoundTrip("(5,)"); assertExprBothRoundTrip("(5, 6)"); } @Test public void listLiteralLong() throws SyntaxError.Exception { // List literals with enough elements to trigger the abbreviated toString() format. assertExprPrettyMatches("[1, 2, 3, 4, 5, 6]", "[1, 2, 3, 4, 5, 6]"); assertExprTostringMatches("[1, 2, 3, 4, 5, 6]", "[1, 2, 3, 4, +2 more]"); assertExprPrettyMatches("(1, 2, 3, 4, 5, 6)", "(1, 2, 3, 4, 5, 6)"); assertExprTostringMatches("(1, 2, 3, 4, 5, 6)", "(1, 2, 3, 4, +2 more)"); } @Test public void listLiteralNested() throws SyntaxError.Exception { // Make sure that the inner list doesn't get abbreviated when the outer list is printed using // prettyPrint(). assertExprPrettyMatches( "[1, 2, 3, [10, 20, 30, 40, 50, 60], 4, 5, 6]", "[1, 2, 3, [10, 20, 30, 40, 50, 60], 4, 5, 6]"); // It doesn't matter as much what toString does. assertExprTostringMatches("[1, 2, 3, [10, 20, 30, 40, 50, 60], 4, 5, 6]", "[1, 2, 3, +4 more]"); } @Test public void sliceExpression() throws SyntaxError.Exception { assertExprBothRoundTrip("a[b:c:d]"); assertExprBothRoundTrip("a[b:c]"); assertExprBothRoundTrip("a[b:]"); assertExprBothRoundTrip("a[:c:d]"); assertExprBothRoundTrip("a[:c]"); assertExprBothRoundTrip("a[::d]"); assertExprBothRoundTrip("a[:]"); } @Test public void stringLiteral() throws SyntaxError.Exception { assertExprBothRoundTrip("\"foo\""); assertExprBothRoundTrip("\"quo\\\"ted\""); } @Test public void unaryOperatorExpression() throws SyntaxError.Exception { assertExprPrettyMatches("not True", "not (True)"); assertExprTostringMatches("not True", "not True"); assertExprPrettyMatches("-5", "-(5)"); assertExprTostringMatches("-5", "-5"); } // Statements. @Test public void assignmentStatement() throws SyntaxError.Exception { assertStmtIndentedPrettyMatches( "x = y", // " x = y\n"); assertStmtTostringMatches( "x = y", // "x = y\n"); } @Test public void augmentedAssignmentStatement() throws SyntaxError.Exception { assertStmtIndentedPrettyMatches("x += y", " x += y\n"); assertStmtTostringMatches("x += y", "x += y\n"); } @Test public void expressionStatement() throws SyntaxError.Exception { assertStmtIndentedPrettyMatches("5", " 5\n"); assertStmtTostringMatches("5", "5\n"); } @Test public void defStatement() throws SyntaxError.Exception { assertStmtIndentedPrettyMatches( join( "def f(x):", // " print(x)"), join( " def f(x):", // " print(x)", "")); assertStmtTostringMatches( join( "def f(x):", // " print(x)"), "def f(x): ...\n"); assertStmtIndentedPrettyMatches( join( "def f(a, b=B, *c, d=D, **e):", // " print(x)"), join( " def f(a, b=B, *c, d=D, **e):", // " print(x)", "")); assertStmtTostringMatches( join( "def f(a, b=B, *c, d=D, **e):", // " print(x)"), "def f(a, b=B, *c, d=D, **e): ...\n"); assertStmtIndentedPrettyMatches( join( "def f():", // " pass"), join( " def f():", // " pass", "")); assertStmtTostringMatches( join( "def f():", // " pass"), "def f(): ...\n"); } @Test public void flowStatement() throws SyntaxError.Exception { assertStmtIndentedPrettyMatches( join( "def f():", // " pass", " continue", " break"), join( " def f():", // " pass", " continue", " break", "")); } @Test public void forStatement() throws SyntaxError.Exception { assertStmtIndentedPrettyMatches( join( "for x in y:", // " print(x)"), join( " for x in y:", // " print(x)", "")); assertStmtTostringMatches( join( "for x in y:", // " print(x)"), "for x in y: ...\n"); assertStmtIndentedPrettyMatches( join( "for x in y:", // " pass"), join( " for x in y:", // " pass", "")); assertStmtTostringMatches( join( "for x in y:", // " pass"), "for x in y: ...\n"); } @Test public void ifStatement() throws SyntaxError.Exception { assertStmtIndentedPrettyMatches( join( "if True:", // " print(x)"), join( " if True:", // " print(x)", "")); assertStmtTostringMatches( join( "if True:", // " print(x)"), "if True: ...\n"); assertStmtIndentedPrettyMatches( join( "if True:", // " print(x)", "elif False:", " print(y)", "else:", " print(z)"), join( " if True:", " print(x)", " elif False:", " print(y)", " else:", " print(z)", "")); assertStmtTostringMatches( join( "if True:", // " print(x)", "elif False:", " print(y)", "else:", " print(z)"), "if True: ...\n"); } @Test public void loadStatement() throws SyntaxError.Exception { assertStmtIndentedPrettyMatches( "load(\"foo.bzl\", a=\"A\", \"B\")", // " load(\"foo.bzl\", a=\"A\", \"B\")\n"); assertStmtTostringMatches( "load(\"foo.bzl\", a=\"A\", \"B\")\n", // "load(\"foo.bzl\", a=\"A\", \"B\")\n"); } @Test public void returnStatement() throws SyntaxError.Exception { assertStmtIndentedPrettyMatches( "return \"foo\"", // " return \"foo\"\n"); assertStmtTostringMatches( "return \"foo\"", // "return \"foo\"\n"); assertStmtIndentedPrettyMatches( "return None", // " return None\n"); assertStmtTostringMatches( "return None", // "return None\n"); assertStmtIndentedPrettyMatches( "return", // " return\n"); assertStmtTostringMatches( "return", // "return\n"); } // Miscellaneous. @Test public void file() throws SyntaxError.Exception { Node node = parseFile("print(x)\nprint(y)"); assertIndentedPrettyMatches( node, join( " print(x)", // " print(y)", "")); assertTostringMatches(node, "<StarlarkFile with 2 statements>"); } @Test public void comment() throws SyntaxError.Exception { ParserInput input = ParserInput.fromLines( "# foo", // "expr # bar"); Parser.ParseResult r = Parser.parseFile(input, FileOptions.DEFAULT); Comment c0 = r.comments.get(0); assertIndentedPrettyMatches(c0, " # foo"); assertTostringMatches(c0, "# foo"); Comment c1 = r.comments.get(1); assertIndentedPrettyMatches(c1, " # bar"); assertTostringMatches(c1, "# bar"); } /* Not tested explicitly because they're covered implicitly by tests for other nodes: * - DictExpression.Entry * - Argument / Parameter * - IfStatements */ }
apache-2.0
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/model/v2/util/itemDetail/subobject/InfixUpgrade.java
580
package me.xhsun.guildwars2wrapper.model.v2.util.itemDetail.subobject; import java.util.List; /** * For more info on Infix upgrade API go <a href="https://wiki.guildwars2.com/wiki/API:2/items#Infix_upgrade_subobject">here</a><br/> * Infix upgrade model class * * @author xhsun * @see InfixAttribute infix attribute * @see Buff infix buff * @since 2017-02-10 */ public class InfixUpgrade { private List<InfixAttribute> attributes; private Buff buff; public List<InfixAttribute> getAttributes() { return attributes; } public Buff getBuff() { return buff; } }
apache-2.0
michaelcouck/ikube
code/core/src/test/java/ikube/toolkit/MailerTest.java
976
package ikube.toolkit; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Spy; import static org.junit.Assert.assertTrue; import ikube.AbstractTest; /** * @author Michael Couck * @version 01.00 * @since 21-11-2010 */ public class MailerTest extends AbstractTest { @Spy @InjectMocks private Mailer mailer; @Test public void sendMail() throws Exception { // This must just pass mailer.setAuth("true"); mailer.setMailHost("smtp.gmail.com"); mailer.setPassword("caherline"); mailer.setPort("465"); mailer.setProtocol("pop3"); mailer.setRecipients("ikube.notifications@gmail.com"); mailer.setSender("ikube.notifications@gmail.com"); mailer.setUser("ikube.notifications"); boolean sent = mailer.sendMail("MailerTest : subject", "MailerTest : message"); assertTrue("This mail should be sent : ", sent); } }
apache-2.0
dibakarece/DMAudioStreamer
app/src/main/java/dm/audiostreamerdemo/widgets/CircleImageView.java
10072
/* * This is the source code of DMAudioStreaming for Android v. 1.0.0. * You should have received a copy of the license in this archive (see LICENSE). * Copyright @Dibakar_Mistry(dibakar.ece@gmail.com), 2017. */ package dm.audiostreamerdemo.widgets; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.widget.ImageView; import dm.audiostreamerdemo.R; public class CircleImageView extends ImageView { private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP; // Default Values private static final float DEFAULT_BORDER_WIDTH = 4; private static final float DEFAULT_SHADOW_RADIUS = 8.0f; // Properties private float borderWidth; private int canvasSize; private float shadowRadius; private int shadowColor = Color.BLACK; // Object used to draw private Bitmap image; private Drawable drawable; private Paint paint; private Paint paintBorder; //region Constructor & Init Method public CircleImageView(final Context context) { this(context, null); } public CircleImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } private void init(Context context, AttributeSet attrs, int defStyleAttr) { // Init paint paint = new Paint(); paint.setAntiAlias(true); paintBorder = new Paint(); paintBorder.setAntiAlias(true); // Load the styled attributes and set their properties TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyleAttr, 0); // Init Border if (attributes.getBoolean(R.styleable.CircleImageView_border, true)) { float defaultBorderSize = DEFAULT_BORDER_WIDTH * getContext().getResources().getDisplayMetrics().density; setBorderWidth(attributes.getDimension(R.styleable.CircleImageView_border_width, defaultBorderSize)); setBorderColor(attributes.getColor(R.styleable.CircleImageView_border_color, Color.WHITE)); } // Init Shadow if (attributes.getBoolean(R.styleable.CircleImageView_shadow, false)) { shadowRadius = DEFAULT_SHADOW_RADIUS; drawShadow(attributes.getFloat(R.styleable.CircleImageView_shadow_radius, shadowRadius), attributes.getColor(R.styleable.CircleImageView_shadow_color, shadowColor)); } } //endregion //region Set Attr Method public void setBorderWidth(float borderWidth) { this.borderWidth = borderWidth; requestLayout(); invalidate(); } public void setBorderColor(int borderColor) { if (paintBorder != null) paintBorder.setColor(borderColor); invalidate(); } public void addShadow() { if (shadowRadius == 0) shadowRadius = DEFAULT_SHADOW_RADIUS; drawShadow(shadowRadius, shadowColor); invalidate(); } public void setShadowRadius(float shadowRadius) { drawShadow(shadowRadius, shadowColor); invalidate(); } public void setShadowColor(int shadowColor) { drawShadow(shadowRadius, shadowColor); invalidate(); } @Override public ScaleType getScaleType() { return SCALE_TYPE; } @Override public void setScaleType(ScaleType scaleType) { if (scaleType != SCALE_TYPE) { throw new IllegalArgumentException(String.format("ScaleType %s not supported. ScaleType.CENTER_CROP is used by default. So you don't need to use ScaleType.", scaleType)); } } //endregion //region Draw Method @Override public void onDraw(Canvas canvas) { // Load the bitmap loadBitmap(); // Check if image isn't null if (image == null) return; if (!isInEditMode()) { canvasSize = canvas.getWidth(); if (canvas.getHeight() < canvasSize) { canvasSize = canvas.getHeight(); } } // circleCenter is the x or y of the view's center // radius is the radius in pixels of the cirle to be drawn // paint contains the shader that will texture the shape int circleCenter = (int) (canvasSize - (borderWidth * 2)) / 2; // Draw Border canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth - (shadowRadius + shadowRadius / 2), paintBorder); // Draw CircularImageView canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter - (shadowRadius + shadowRadius / 2), paint); } private void loadBitmap() { if (this.drawable == getDrawable()) return; this.drawable = getDrawable(); this.image = drawableToBitmap(this.drawable); updateShader(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); canvasSize = w; if (h < canvasSize) canvasSize = h; if (image != null) updateShader(); } private void drawShadow(float shadowRadius, int shadowColor) { this.shadowRadius = shadowRadius; this.shadowColor = shadowColor; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { setLayerType(LAYER_TYPE_SOFTWARE, paintBorder); } paintBorder.setShadowLayer(shadowRadius, 0.0f, shadowRadius / 2, shadowColor); } private void updateShader() { if (image == null) return; // Crop Center Image image = cropBitmap(image); // Create Shader BitmapShader shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); // Center Image in Shader Matrix matrix = new Matrix(); matrix.setScale((float) canvasSize / (float) image.getWidth(), (float) canvasSize / (float) image.getHeight()); shader.setLocalMatrix(matrix); // Set Shader in Paint paint.setShader(shader); } private Bitmap cropBitmap(Bitmap bitmap) { Bitmap bmp; if (bitmap.getWidth() >= bitmap.getHeight()) { bmp = Bitmap.createBitmap( bitmap, bitmap.getWidth() / 2 - bitmap.getHeight() / 2, 0, bitmap.getHeight(), bitmap.getHeight()); } else { bmp = Bitmap.createBitmap( bitmap, 0, bitmap.getHeight() / 2 - bitmap.getWidth() / 2, bitmap.getWidth(), bitmap.getWidth()); } return bmp; } private Bitmap drawableToBitmap(Drawable drawable) { if (drawable == null) { return null; } else if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } int intrinsicWidth = drawable.getIntrinsicWidth(); int intrinsicHeight = drawable.getIntrinsicHeight(); if (!(intrinsicWidth > 0 && intrinsicHeight > 0)) return null; try { // Create Bitmap object out of the drawable Bitmap bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (OutOfMemoryError e) { // Simply return null of failed bitmap creations Log.e(getClass().toString(), "Encountered OutOfMemoryError while generating bitmap!"); return null; } } //endregion //region Mesure Method @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = measureWidth(widthMeasureSpec); int height = measureHeight(heightMeasureSpec); /*int imageSize = (width < height) ? width : height; setMeasuredDimension(imageSize, imageSize);*/ setMeasuredDimension(width, height); } private int measureWidth(int measureSpec) { int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // The parent has determined an exact size for the child. result = specSize; } else if (specMode == MeasureSpec.AT_MOST) { // The child can be as large as it wants up to the specified size. result = specSize; } else { // The parent has not imposed any constraint on the child. result = canvasSize; } return result; } private int measureHeight(int measureSpecHeight) { int result; int specMode = MeasureSpec.getMode(measureSpecHeight); int specSize = MeasureSpec.getSize(measureSpecHeight); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else if (specMode == MeasureSpec.AT_MOST) { // The child can be as large as it wants up to the specified size. result = specSize; } else { // Measure the text (beware: ascent is a negative number) result = canvasSize; } return (result + 2); } //endregion }
apache-2.0
inbloom/secure-data-service
sli/api/src/main/java/org/slc/sli/api/security/context/ResponseTooLargeException.java
927
/* * Copyright 2012-2013 inBloom, Inc. and its affiliates. * * 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.slc.sli.api.security.context; /** * Represents the error detected by the API when too much data is requested. * * @author kmyers * */ public class ResponseTooLargeException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; }
apache-2.0
gerrit-review/gerrit
java/com/google/gerrit/server/account/GetUsername.java
1303
// Copyright (C) 2013 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.google.gerrit.server.account; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.RestReadView; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class GetUsername implements RestReadView<AccountResource> { @Inject public GetUsername() {} @Override public String apply(AccountResource rsrc) throws AuthException, ResourceNotFoundException { String username = rsrc.getUser().getAccount().getUserName(); if (username == null) { throw new ResourceNotFoundException(); } return username; } }
apache-2.0
dougm/ant-contrib-cpptasks
src/main/java/net/sf/antcontrib/cpptasks/SourceHistory.java
1647
/* * * Copyright 2002-2004 The Ant-Contrib 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 net.sf.antcontrib.cpptasks; import java.io.File; import java.io.IOException; /** * The history of a source file used to build a target * * @author Curt Arnold */ public final class SourceHistory { private final long lastModified; private final String relativePath; /** * Constructor * * @param relativePath String * @param lastModified long */ public SourceHistory(String relativePath, long lastModified) { if (relativePath == null) { throw new NullPointerException("relativePath"); } this.relativePath = relativePath; this.lastModified = lastModified; } public String getAbsolutePath(File baseDir) { try { return new File(baseDir, relativePath).getCanonicalPath(); } catch (IOException ex) { } return relativePath; } public long getLastModified() { return lastModified; } public String getRelativePath() { return relativePath; } }
apache-2.0
sprklinginfo/camelinaction2
chapter14/payload/src/test/java/camelinaction/SpringMessageSigningWithKeyStoreParamsTest.java
1895
/** * 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 camelinaction; import org.apache.camel.Exchange; import org.apache.camel.test.spring.CamelSpringTestSupport; import org.junit.Test; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringMessageSigningWithKeyStoreParamsTest extends CamelSpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/message-signing.xml"}); } @Test public void testSignAndVerifyMessage() throws Exception { getMockEndpoint("mock:signed").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:verified").expectedBodiesReceived("Hello World"); template.sendBody("direct:sign", "Hello World"); assertMockEndpointsSatisfied(); Exchange exchange = getMockEndpoint("mock:signed").getReceivedExchanges().get(0); assertNotNull(exchange.getIn().getHeader("CamelDigitalSignature")); } }
apache-2.0
bserdar/check-release-plugin
src/test/java/com/redhat/plugin/checkrelease/XMLComparatorTest.java
2125
package com.redhat.plugin.checkrelease; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.xml.parsers.*; import org.w3c.dom.*; import java.io.*; import java.util.*; public class XMLComparatorTest { private String testit(String s1,String s2) throws Exception { return testit(new StringBufferInputStream(s1), new StringBufferInputStream(s2)); } private String testit(InputStream s1,InputStream s2) throws Exception { XMLFileComparator cmp=new XMLFileComparator(null); return cmp.compare(s1,s2); } @Test public void iteratortest() throws Exception { final String s1="<el1><el2 attr1=\"1\"></el2></el1>"; DocumentBuilder b=DocumentBuilderFactory. newInstance().newDocumentBuilder(); Document doc=b.parse(new StringBufferInputStream(s1)); DepthFirstIterator itr=new DepthFirstIterator(doc.getDocumentElement()); Assert.assertEquals("el1",itr.next().getNodeName()); Assert.assertEquals("el2",itr.next().getNodeName()); Assert.assertNull(itr.next()); } @Test public void testSame() throws Exception { final String s1="<el1><el2 attr1=\"1\"></el2></el1>"; Assert.assertNull(testit(s1,s1)); } @Test public void testWsSame() throws Exception { final String s1="<el1><el2 attr1=\"1\"></el2></el1>"; final String s2="<el1> <el2 attr1=\"1\"> </el2> </el1>"; Assert.assertNull(testit(s1,s2)); } @Test public void testWsCommSame() throws Exception { final String s1="<el1><el2 attr1=\"1\"><!--some comments--></el2></el1>"; final String s2="<el1> <el2 attr1=\"1\"> </el2> </el1>"; Assert.assertNull(testit(s1,s2)); } @Test public void testDiff() throws Exception { final String s1="<el1><el2 attr1=\"1\">x<!--some comments--></el2></el1>"; final String s2="<el1> <el2 attr1=\"1\"> </el2> </el1>"; Assert.assertNotNull(testit(s1,s2)); System.out.println(testit(s1,s2)); } }
apache-2.0
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/ProductServiceInterfaceupdateProducts.java
2227
package com.google.api.ads.dfp.jaxws.v201511; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Updates the specified {@link Product} objects. * Note non-updatable fields will not be backfilled. * * @param products the products to update * @return the updated products * * * <p>Java class for updateProducts element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="updateProducts"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="products" type="{https://www.google.com/apis/ads/publisher/v201511}Product" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "products" }) @XmlRootElement(name = "updateProducts") public class ProductServiceInterfaceupdateProducts { protected List<Product> products; /** * Gets the value of the products property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the products property. * * <p> * For example, to add a new item, do as follows: * <pre> * getProducts().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Product } * * */ public List<Product> getProducts() { if (products == null) { products = new ArrayList<Product>(); } return this.products; } }
apache-2.0
dbflute-test/dbflute-test-active-hangar
src/main/java/org/docksidestage/hangar/dbflute/bsentity/dbmeta/ProductCategoryDbm.java
12673
package org.docksidestage.hangar.dbflute.bsentity.dbmeta; import java.util.List; import java.util.Map; import org.dbflute.Entity; import org.dbflute.optional.OptionalEntity; import org.dbflute.dbmeta.AbstractDBMeta; import org.dbflute.dbmeta.info.*; import org.dbflute.dbmeta.name.*; import org.dbflute.dbmeta.property.PropertyGateway; import org.dbflute.dbway.DBDef; import org.docksidestage.hangar.dbflute.allcommon.*; import org.docksidestage.hangar.dbflute.exentity.*; /** * The DB meta of PRODUCT_CATEGORY. (Singleton) * @author DBFlute(AutoGenerator) */ public class ProductCategoryDbm extends AbstractDBMeta { // =================================================================================== // Singleton // ========= private static final ProductCategoryDbm _instance = new ProductCategoryDbm(); private ProductCategoryDbm() {} public static ProductCategoryDbm getInstance() { return _instance; } // =================================================================================== // Current DBDef // ============= public String getProjectName() { return DBCurrent.getInstance().projectName(); } public String getProjectPrefix() { return DBCurrent.getInstance().projectPrefix(); } public String getGenerationGapBasePrefix() { return DBCurrent.getInstance().generationGapBasePrefix(); } public DBDef getCurrentDBDef() { return DBCurrent.getInstance().currentDBDef(); } // =================================================================================== // Property Gateway // ================ // ----------------------------------------------------- // Column Property // --------------- protected final Map<String, PropertyGateway> _epgMap = newHashMap(); { xsetupEpg(); } protected void xsetupEpg() { setupEpg(_epgMap, et -> ((ProductCategory)et).getProductCategoryCode(), (et, vl) -> ((ProductCategory)et).setProductCategoryCode((String)vl), "productCategoryCode"); setupEpg(_epgMap, et -> ((ProductCategory)et).getProductCategoryName(), (et, vl) -> ((ProductCategory)et).setProductCategoryName((String)vl), "productCategoryName"); setupEpg(_epgMap, et -> ((ProductCategory)et).getParentCategoryCode(), (et, vl) -> ((ProductCategory)et).setParentCategoryCode((String)vl), "parentCategoryCode"); } public PropertyGateway findPropertyGateway(String prop) { return doFindEpg(_epgMap, prop); } // ----------------------------------------------------- // Foreign Property // ---------------- protected final Map<String, PropertyGateway> _efpgMap = newHashMap(); { xsetupEfpg(); } @SuppressWarnings("unchecked") protected void xsetupEfpg() { setupEfpg(_efpgMap, et -> ((ProductCategory)et).getProductCategorySelf(), (et, vl) -> ((ProductCategory)et).setProductCategorySelf((OptionalEntity<ProductCategory>)vl), "productCategorySelf"); } public PropertyGateway findForeignPropertyGateway(String prop) { return doFindEfpg(_efpgMap, prop); } // =================================================================================== // Table Info // ========== protected final String _tableDbName = "PRODUCT_CATEGORY"; protected final String _tableDispName = "PRODUCT_CATEGORY"; protected final String _tablePropertyName = "productCategory"; protected final TableSqlName _tableSqlName = new TableSqlName("MAIHAMADB.PUBLIC.PRODUCT_CATEGORY", _tableDbName); { _tableSqlName.xacceptFilter(DBFluteConfig.getInstance().getTableSqlNameFilter()); } public String getTableDbName() { return _tableDbName; } public String getTableDispName() { return _tableDispName; } public String getTablePropertyName() { return _tablePropertyName; } public TableSqlName getTableSqlName() { return _tableSqlName; } protected final String _tableAlias = "商品カテゴリ"; public String getTableAlias() { return _tableAlias; } protected final String _tableComment = "商品のカテゴリを表現するマスタ。自己参照FKの階層になっている。"; public String getTableComment() { return _tableComment; } // =================================================================================== // Column Info // =========== protected final ColumnInfo _columnProductCategoryCode = cci("PRODUCT_CATEGORY_CODE", "PRODUCT_CATEGORY_CODE", null, "商品カテゴリコード", String.class, "productCategoryCode", null, true, false, true, "CHAR", 3, 0, null, null, false, null, "自分のテーブルの別のレコードからも参照される。", null, "productList,productCategorySelfList", null, false); protected final ColumnInfo _columnProductCategoryName = cci("PRODUCT_CATEGORY_NAME", "PRODUCT_CATEGORY_NAME", null, "商品カテゴリ名称", String.class, "productCategoryName", null, false, false, true, "VARCHAR", 50, 0, null, null, false, null, null, null, null, null, false); protected final ColumnInfo _columnParentCategoryCode = cci("PARENT_CATEGORY_CODE", "PARENT_CATEGORY_CODE", null, "親カテゴリコード", String.class, "parentCategoryCode", null, false, false, false, "CHAR", 3, 0, null, null, false, null, "最上位の場合はデータなし。まさひく自己参照FKカラム!", "productCategorySelf", null, null, false); /** * (商品カテゴリコード)PRODUCT_CATEGORY_CODE: {PK, NotNull, CHAR(3)} * @return The information object of specified column. (NotNull) */ public ColumnInfo columnProductCategoryCode() { return _columnProductCategoryCode; } /** * (商品カテゴリ名称)PRODUCT_CATEGORY_NAME: {NotNull, VARCHAR(50)} * @return The information object of specified column. (NotNull) */ public ColumnInfo columnProductCategoryName() { return _columnProductCategoryName; } /** * (親カテゴリコード)PARENT_CATEGORY_CODE: {IX, CHAR(3), FK to PRODUCT_CATEGORY} * @return The information object of specified column. (NotNull) */ public ColumnInfo columnParentCategoryCode() { return _columnParentCategoryCode; } protected List<ColumnInfo> ccil() { List<ColumnInfo> ls = newArrayList(); ls.add(columnProductCategoryCode()); ls.add(columnProductCategoryName()); ls.add(columnParentCategoryCode()); return ls; } { initializeInformationResource(); } // =================================================================================== // Unique Info // =========== // ----------------------------------------------------- // Primary Element // --------------- protected UniqueInfo cpui() { return hpcpui(columnProductCategoryCode()); } public boolean hasPrimaryKey() { return true; } public boolean hasCompoundPrimaryKey() { return false; } // =================================================================================== // Relation Info // ============= // cannot cache because it uses related DB meta instance while booting // (instead, cached by super's collection) // ----------------------------------------------------- // Foreign Property // ---------------- /** * (商品カテゴリ)PRODUCT_CATEGORY by my PARENT_CATEGORY_CODE, named 'productCategorySelf'. * @return The information object of foreign property. (NotNull) */ public ForeignInfo foreignProductCategorySelf() { Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnParentCategoryCode(), ProductCategoryDbm.getInstance().columnProductCategoryCode()); return cfi("FK_PRODUCT_CATEGORY_PARENT", "productCategorySelf", this, ProductCategoryDbm.getInstance(), mp, 0, org.dbflute.optional.OptionalEntity.class, false, false, false, false, null, null, false, "productCategorySelfList", false); } // ----------------------------------------------------- // Referrer Property // ----------------- /** * (商品)PRODUCT by PRODUCT_CATEGORY_CODE, named 'productList'. * @return The information object of referrer property. (NotNull) */ public ReferrerInfo referrerProductList() { Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnProductCategoryCode(), ProductDbm.getInstance().columnProductCategoryCode()); return cri("FK_PRODUCT_PRODUCT_CATEGORY", "productList", this, ProductDbm.getInstance(), mp, false, "productCategory"); } /** * (商品カテゴリ)PRODUCT_CATEGORY by PARENT_CATEGORY_CODE, named 'productCategorySelfList'. * @return The information object of referrer property. (NotNull) */ public ReferrerInfo referrerProductCategorySelfList() { Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnProductCategoryCode(), ProductCategoryDbm.getInstance().columnParentCategoryCode()); return cri("FK_PRODUCT_CATEGORY_PARENT", "productCategorySelfList", this, ProductCategoryDbm.getInstance(), mp, false, "productCategorySelf"); } // =================================================================================== // Various Info // ============ // =================================================================================== // Type Name // ========= public String getEntityTypeName() { return "org.docksidestage.hangar.dbflute.exentity.ProductCategory"; } public String getConditionBeanTypeName() { return "org.docksidestage.hangar.dbflute.cbean.ProductCategoryCB"; } public String getBehaviorTypeName() { return "org.docksidestage.hangar.dbflute.exbhv.ProductCategoryBhv"; } // =================================================================================== // Object Type // =========== public Class<ProductCategory> getEntityType() { return ProductCategory.class; } // =================================================================================== // Object Instance // =============== public ProductCategory newEntity() { return new ProductCategory(); } // =================================================================================== // Map Communication // ================= public void acceptPrimaryKeyMap(Entity et, Map<String, ? extends Object> mp) { doAcceptPrimaryKeyMap((ProductCategory)et, mp); } public void acceptAllColumnMap(Entity et, Map<String, ? extends Object> mp) { doAcceptAllColumnMap((ProductCategory)et, mp); } public Map<String, Object> extractPrimaryKeyMap(Entity et) { return doExtractPrimaryKeyMap(et); } public Map<String, Object> extractAllColumnMap(Entity et) { return doExtractAllColumnMap(et); } }
apache-2.0
jacek-rzrz/RxJava
src/main/java/rx/internal/util/SynchronizedQueue.java
3969
/** * Copyright 2014 Netflix, 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 rx.internal.util; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; /** * Intended for use when the `sun.misc.Unsafe` implementations can't be used. * * @param <T> */ public class SynchronizedQueue<T> implements Queue<T>, Cloneable { private final Queue<T> list = new LinkedList<T>(); private final int size; public SynchronizedQueue() { this.size = -1; } public SynchronizedQueue(int size) { this.size = size; } @Override public synchronized boolean isEmpty() { // NOPMD return list.isEmpty(); } @Override public synchronized boolean contains(Object o) { // NOPMD return list.contains(o); } @Override public synchronized Iterator<T> iterator() { // NOPMD return list.iterator(); } @Override public synchronized int size() { // NOPMD return list.size(); } @Override public synchronized boolean add(T e) { // NOPMD return list.add(e); } @Override public synchronized boolean remove(Object o) { // NOPMD return list.remove(o); } @Override public synchronized boolean containsAll(Collection<?> c) { // NOPMD return list.containsAll(c); } @Override public synchronized boolean addAll(Collection<? extends T> c) { // NOPMD return list.addAll(c); } @Override public synchronized boolean removeAll(Collection<?> c) { // NOPMD return list.removeAll(c); } @Override public synchronized boolean retainAll(Collection<?> c) { // NOPMD return list.retainAll(c); } @Override public synchronized void clear() { // NOPMD list.clear(); } @Override public synchronized String toString() { // NOPMD return list.toString(); } @Override public int hashCode() { return list.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } SynchronizedQueue<?> other = (SynchronizedQueue<?>) obj; if (!list.equals(other.list)) { return false; } return true; } @Override public synchronized T peek() { // NOPMD return list.peek(); } @Override public synchronized T element() { // NOPMD return list.element(); } @Override public synchronized T poll() { // NOPMD return list.poll(); } @Override public synchronized T remove() { // NOPMD return list.remove(); } @Override public synchronized boolean offer(T e) { // NOPMD if (size > -1 && list.size() + 1 > size) { return false; } return list.offer(e); } @Override public synchronized Object clone() { // NOPMD SynchronizedQueue<T> q = new SynchronizedQueue<T>(size); q.addAll(list); return q; } @Override public synchronized Object[] toArray() { // NOPMD return list.toArray(); } @Override public synchronized <R> R[] toArray(R[] a) { // NOPMD return list.toArray(a); } }
apache-2.0
hongyan99/chart-faces
chartfaces/src/test/java/org/javaq/chartfaces/viewspec/impl/LegendSpecCalculatorTest.java
1379
package org.javaq.chartfaces.viewspec.impl; import junit.framework.Assert; import org.javaq.chartfaces.api.Box; import org.javaq.chartfaces.api.IChartPart; import org.javaq.chartfaces.component.impl.UIChart; import org.javaq.chartfaces.viewspec.IPartSpecCalculator; import org.junit.Test; public class LegendSpecCalculatorTest extends SpecCalculatorTestBase { private static final String LEGEND_ID = "alegend"; private static final String LEGEND_WIDTH = "100px"; private static final String LEGEND_HEIGHT = "60px"; @Test public void testComputeViewBox() throws Exception { final UIChart chart = createChart(); final IChartPart part = createPart(); final LegendSpecCalculator creator = (LegendSpecCalculator) createSpecCreator( chart, part); final Box box = creator.computeViewBox(part); Assert.assertNotNull(box); // for position = "top" (the default for a legend), width is calculated Assert.assertEquals(1540, box.getWidth()); Assert.assertEquals(60, box.getHeight()); } @Override protected IChartPart createPart() { return createLegend(LegendSpecCalculatorTest.LEGEND_ID, LegendSpecCalculatorTest.LEGEND_WIDTH, LegendSpecCalculatorTest.LEGEND_HEIGHT); } @Override protected IPartSpecCalculator createSpecCreator(final SpecHelper helper) { return new LegendSpecCalculator(helper); } }
apache-2.0
philipphager/disclosure-android-app
app/src/main/java/de/philipphager/disclosure/feature/analyser/app/usecase/AnalyseUsedPermissions.java
1448
package de.philipphager.disclosure.feature.analyser.app.usecase; import de.philipphager.disclosure.database.app.model.App; import de.philipphager.disclosure.feature.sync.db.usecases.FetchNewPermissions; import de.philipphager.disclosure.feature.sync.db.usecases.FetchRequestedPermissions; import de.philipphager.disclosure.service.PermissionService; import java.util.List; import javax.inject.Inject; import rx.Observable; import timber.log.Timber; public class AnalyseUsedPermissions { private final PermissionService permissionService; private final FetchNewPermissions fetchNewPermissions; private final FetchRequestedPermissions fetchRequestedPermissions; @Inject public AnalyseUsedPermissions(PermissionService permissionService, FetchNewPermissions fetchNewPermissions, FetchRequestedPermissions fetchRequestedPermissions) { this.permissionService = permissionService; this.fetchNewPermissions = fetchNewPermissions; this.fetchRequestedPermissions = fetchRequestedPermissions; } public Observable<List<?>> analyse(App app) { Timber.d("analysing permissions used by %s", app); return Observable.concat( fetchNewPermissions.run(app) .doOnNext(permissionService::insertOrUpdate) .doOnError(Timber::e), fetchRequestedPermissions.run(app) .doOnNext(permissionService::insertForApp) .doOnError(Timber::e) ).ignoreElements(); } }
apache-2.0
jbonot/CMPUT391GroupProject
classes/proj1/ImageInfo.java
222
package proj1; import java.sql.Date; public class ImageInfo { public String subject; public String place; public String description; public String owner; public Date date; public String group; public int groupId; }
apache-2.0
powerslider/GeekIT
app/src/main/java/com/ceco/geekit/app/net/BookArrayJsonDeserializer.java
1380
package com.ceco.geekit.app.net; import com.ceco.geekit.app.model.BookSearchResultsItem; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import java.lang.reflect.Type; /** * @author Tsvetan Dimitrov <tsvetan.dimitrov23@gmail.com> * @since 25 May 2015 */ public class BookArrayJsonDeserializer implements JsonDeserializer<BookSearchResultsItem[]> { private JsonArray booksArray; @Override public BookSearchResultsItem[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { this.booksArray = (JsonArray) json.getAsJsonObject().get("Books"); BookSearchResultsItem[] bookSearchResultsItems = new BookSearchResultsItem[booksArray.size()]; for (int i = 0; i < booksArray.size(); i++) { bookSearchResultsItems[i] = new BookSearchResultsItem( getValueFor("ID", i), getValueFor("Title", i), getValueFor("Image", i)); } return bookSearchResultsItems; } private String getValueFor(String key, int i) { return booksArray.get(i) .getAsJsonObject() .get(key) .getAsString(); } }
apache-2.0
syntelos/gwtcc
src/com/google/gwt/core/ext/typeinfo/JEnumConstant.java
912
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.core.ext.typeinfo; /** * An enumeration constant declared in an enumerated type. */ public interface JEnumConstant extends JField { /** * Returns the ordinal value for this enumeration constant. * * @return ordinal value for this enumeration constant */ int getOrdinal(); }
apache-2.0
szydra/first-repository
src/main/java/google/dao/SqliteResultDao.java
2897
package google.dao; import static google.dao.SqlHelper.*; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Repository; import google.model.Result; @Repository class SqliteResultDao implements ResultDao { private static final Logger log = LogManager.getLogger(SqliteResultDao.class); @Override public void insert(Result result) { try (Sqlite sqlite = new Sqlite()) { sqlite.executeUpdate(getSqlForInsert(result)); log.debug("Zapytanie {} dodano do bazy danych.", result.getQuery()); } catch (SQLException sqle) { throw new DaoException("Podczas dodawania zapytania " + result.getQuery() + " do bazy danych wystąpił błąd.", sqle); } } @Override public List<Result> findAll() { List<Result> results = new ArrayList<>(); try (Sqlite sqlite = new Sqlite(); Statement statement = sqlite.getStatement(); ResultSet resultSet = statement.executeQuery(getSqlForSelectAll())) { while (resultSet.next()) { Result result = new Result(resultSet.getString(COLUMN_QUERY)); result.setDate(LocalDate.parse(resultSet.getString(COLUMN_DATE))); result.setNumberOfResults(resultSet.getLong(COLUMN_NUMBER)); results.add(result); log.debug("Zapytanie {} pobrano z bazy danych.", result.getQuery()); } } catch (SQLException sqle) { throw new DaoException("Błąd bazy danych podczas odczytu wszystkich zapytań.", sqle); } return results; } @Override public Optional<Result> find(String query) { try (Sqlite sqlite = new Sqlite(); Statement statement = sqlite.getStatement(); ResultSet resultSet = statement.executeQuery(getSqlForSingleSelect(query))) { if (resultSet.next()) { log.debug("Zapytanie {} znajduje się w bazie danych.", query); return Optional.of(new Result(query, resultSet.getLong(COLUMN_NUMBER), resultSet.getString(COLUMN_DATE))); } } catch (SQLException sqle) { throw new DaoException("Błąd pobierania danych dla zapytania" + query, sqle); } return Optional.empty(); } @Override public void deleteAll() { try (Sqlite sqlite = new Sqlite()) { sqlite.executeUpdate(getSqlForDeleteAll()); } catch (SQLException sqle) { throw new DaoException("Błąd podczas czyszczenia bazy danych.", sqle); } } @Override public void delete(Result result) { delete(result.getQuery()); } @Override public void delete(String query) { try (Sqlite sqlite = new Sqlite()) { sqlite.executeUpdate(getSqlForDelete(query)); log.debug("Zapytanie {} usunięto z bazy danych.", query); } catch (SQLException sqle) { throw new DaoException("Błąd podczas usuwania zapytania " + query, sqle); } } }
apache-2.0
ringoluo/mapdb
src/test/java/examples/CacheOffHeapAdvanced.java
1946
package examples; import org.mapdb.*; import java.util.Random; /** * This example shows how-to create off-heap cache, * where entries expire when maximal store size is reached. * * It also shows howto get basic statistics about store size. * * It is more advanced version of previous example. * It uses more settings, bypasses general serialization for best performance * and discussed other performance tunning * */ public class CacheOffHeapAdvanced { public static void main(String[] args) { final double cacheSizeInGB = 1.0; //first create store DB db = DBMaker .memoryDirectDB() .transactionDisable() //some additional options for DB // .asyncWriteEnable() // .cacheSize(100000) .make(); HTreeMap cache = db .hashMapCreate("cache") .expireStoreSize(cacheSizeInGB) .counterEnable() //disable this if cache.size() is not used //use proper serializers to and improve performance .keySerializer(Serializer.LONG) .valueSerializer(Serializer.BYTE_ARRAY) .make(); //generates random key and values Random r = new Random(); //used to print store statistics Store store = Store.forDB(db); // insert some stuff in cycle for(long counter=1; counter<1e8; counter++){ long key = r.nextLong(); byte[] value = new byte[1000]; r.nextBytes(value); cache.put(key,value); if(counter%1e5==0){ System.out.printf("Map size: %,d, counter %,d, curr store size: %,d, store free size: %,d\n", cache.sizeLong(), counter, store.getCurrSize(), store.getFreeSize()); } } // and close to release memory db.close(); } }
apache-2.0
ManfredTremmel/gwt-bean-validators
gwt-bean-validators/src/test/java/de/knightsoftnet/validators/shared/testcases/HibernatePeselTestCases.java
2928
/* * 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 de.knightsoftnet.validators.shared.testcases; import de.knightsoftnet.validators.shared.beans.HibernatePeselTestBean; import java.util.ArrayList; import java.util.List; /** * get test cases for Pesel test. * * @author Manfred Tremmel * */ public class HibernatePeselTestCases { /** * get empty test bean. * * @return empty test bean */ public static final HibernatePeselTestBean getEmptyTestBean() { return new HibernatePeselTestBean(null); } /** * get correct test beans. * * @return correct test beans */ public static final List<HibernatePeselTestBean> getCorrectTestBeans() { final List<HibernatePeselTestBean> correctCases = new ArrayList<>(); correctCases.add(new HibernatePeselTestBean("92041903790")); correctCases.add(new HibernatePeselTestBean("44051401359")); correctCases.add(new HibernatePeselTestBean("70100619901")); correctCases.add(new HibernatePeselTestBean("80082107231")); correctCases.add(new HibernatePeselTestBean("00301202868")); correctCases.add(new HibernatePeselTestBean("00271100559")); correctCases.add(new HibernatePeselTestBean("12241301417")); correctCases.add(new HibernatePeselTestBean("12252918020")); correctCases.add(new HibernatePeselTestBean("12262911406")); return correctCases; } /** * get wrong test beans. * * @return wrong test beans */ public static final List<HibernatePeselTestBean> getWrongTestBeans() { final List<HibernatePeselTestBean> wrongCases = new ArrayList<>(); wrongCases.add(new HibernatePeselTestBean("44051401358")); wrongCases.add(new HibernatePeselTestBean("92041903791")); wrongCases.add(new HibernatePeselTestBean("80082107232")); wrongCases.add(new HibernatePeselTestBean("80062210349")); wrongCases.add(new HibernatePeselTestBean("00301202866")); wrongCases.add(new HibernatePeselTestBean("00271100557")); wrongCases.add(new HibernatePeselTestBean("12241301418")); wrongCases.add(new HibernatePeselTestBean("12252918029")); wrongCases.add(new HibernatePeselTestBean("12262911402")); return wrongCases; } }
apache-2.0
jdgwartney/vsphere-ws
java/JAXWS/samples/com/vmware/vim25/FaultToleranceSecondaryConfigInfo.java
1667
package com.vmware.vim25; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for FaultToleranceSecondaryConfigInfo complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="FaultToleranceSecondaryConfigInfo"> * &lt;complexContent> * &lt;extension base="{urn:vim25}FaultToleranceConfigInfo"> * &lt;sequence> * &lt;element name="primaryVM" type="{urn:vim25}ManagedObjectReference"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "FaultToleranceSecondaryConfigInfo", propOrder = { "primaryVM" }) public class FaultToleranceSecondaryConfigInfo extends FaultToleranceConfigInfo { @XmlElement(required = true) protected ManagedObjectReference primaryVM; /** * Gets the value of the primaryVM property. * * @return * possible object is * {@link ManagedObjectReference } * */ public ManagedObjectReference getPrimaryVM() { return primaryVM; } /** * Sets the value of the primaryVM property. * * @param value * allowed object is * {@link ManagedObjectReference } * */ public void setPrimaryVM(ManagedObjectReference value) { this.primaryVM = value; } }
apache-2.0
samtingleff/dgrid
java/src/api/com/dgrid/service/DGridSystemsAdapter.java
363
package com.dgrid.service; public interface DGridSystemsAdapter { public static final String NAME = "systemsAdapter"; public long getVmUptime(); public double getSystemLoadAverage(); public long getFreeMemory(); public long getUsedMemory(); public int getActiveThreadCount(); public void restart(); public void shutdown(); public void halt(); }
apache-2.0
CMPUT301W14T05/Team5GeoTopics
GeoTopicsActivity/src/ca/ualberta/cs/team5geotopics/UserController.java
1288
package ca.ualberta.cs.team5geotopics; import android.graphics.Bitmap; public class UserController { private User mUser; public UserController() { this.mUser = User.getInstance(); } public UserController(User user){ this.mUser = user; } /** * Used to add OR remove a comment ID from the bookmark's list. If the ID * exists its removed, else its added. * * @param ID * The comment ID */ public void bookmark(CommentModel comment) { mUser.bookmark(comment); } /** * This method is used to tell the user model that we are viewing a specific * comment. This allows us to remove it from the want to read bookmarks list * upon reading. * * @param comment * The comment we are reading */ public void readingComment(CommentModel comment) { if (mUser.inBookmarks(comment)) { mUser.removeBookmark(comment); } } /** * Used to add OR remove a comment ID from the favourites's list. If the ID * exists its removed, else its added. * * @param ID * The comment ID */ public void favourite(CommentModel comment) { mUser.favourite(comment); } public void updateProfile(String userName, String contactInfo, String bio, Bitmap profile){ mUser.update(userName, contactInfo, bio, profile); } }
apache-2.0
heiko-braun/wildfly-swarm
ejb/test/src/test/java/org/wildfly/swarm/ejb/EJBArqSingletonTest.java
1792
/** * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * 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.wildfly.swarm.ejb; import javax.ejb.EJB; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.swarm.ContainerFactory; import org.wildfly.swarm.container.Container; import org.wildfly.swarm.container.JARArchive; /** * @author Bob McWhirter */ @RunWith(Arquillian.class) public class EJBArqSingletonTest implements ContainerFactory { @Deployment(testable = false) public static Archive createDeployment() { JARArchive deployment = ShrinkWrap.create(JARArchive.class); deployment.addClass( MySingleton.class ); deployment.addClass( MySingletonBean.class ); return deployment; } @Override public Container newContainer(String... args) throws Exception { return new Container().fraction( EJBFraction.createDefaultFraction() ); } @Test @RunAsClient public void testNothing() { // nothing } }
apache-2.0
Sellegit/j2objc
runtime/src/main/java/apple/messageui/MFMessageComposeViewControllerDelegate.java
782
package apple.messageui; import java.io.*; import java.nio.*; import java.util.*; import com.google.j2objc.annotations.*; import com.google.j2objc.runtime.*; import com.google.j2objc.runtime.block.*; import apple.audiotoolbox.*; import apple.corefoundation.*; import apple.coregraphics.*; import apple.coreservices.*; import apple.foundation.*; import apple.uikit.*; @Library("MessageUI/MessageUI.h") @Mapping("MFMessageComposeViewControllerDelegate") public interface MFMessageComposeViewControllerDelegate extends NSObjectProtocol { @Mapping("messageComposeViewController:didFinishWithResult:") void didFinish(MFMessageComposeViewController controller, @Representing("MessageComposeResult") long result); /*<adapter>*/ /*</adapter>*/ }
apache-2.0
FauDroids/BoxClub
app/src/main/java/org/faudroids/boxclub/ui/WindowUtils.java
1140
package org.faudroids.boxclub.ui; import android.annotation.TargetApi; import android.os.Build; import android.view.View; import android.view.Window; final class WindowUtils { private static final boolean immersiveAvailable; private static final boolean immersiveStickyAvailable; static { immersiveAvailable = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN); immersiveStickyAvailable = (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT); } /** * Starts the fullscreen immersive mode if API level is sufficient. * @return whether API level was sufficient */ @TargetApi(Build.VERSION_CODES.KITKAT) public boolean startImmersiveMode(Window window) { if (immersiveAvailable) { int visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN; if (immersiveStickyAvailable) visibility |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; window.getDecorView().setSystemUiVisibility(visibility); return true; } return false; } }
apache-2.0
dernasherbrezon/jradio
src/main/java/ru/r2cloud/jradio/at03/StacieOperationalMode.java
629
package ru.r2cloud.jradio.at03; import java.util.HashMap; import java.util.Map; public enum StacieOperationalMode { NORMAL(0), SLEEP(2), BEACON(3), DEPLOYMENT(4), SHUTDOWN(8); private final int code; private static final Map<Integer, StacieOperationalMode> typeByCode = new HashMap<>(); static { for (StacieOperationalMode cur : StacieOperationalMode.values()) { typeByCode.put(cur.getCode(), cur); } } private StacieOperationalMode(int code) { this.code = code; } public int getCode() { return code; } public static StacieOperationalMode valueOfCode(int code) { return typeByCode.get(code); } }
apache-2.0
jbertram/activemq-artemis-old
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementControlHelper.java
8878
/** * 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.activemq.artemis.tests.integration.management; import javax.jms.Queue; import javax.jms.Topic; import javax.management.MBeanServer; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.management.AcceptorControl; import org.apache.activemq.artemis.api.core.management.AddressControl; import org.apache.activemq.artemis.api.core.management.BridgeControl; import org.apache.activemq.artemis.api.core.management.BroadcastGroupControl; import org.apache.activemq.artemis.api.core.management.ClusterConnectionControl; import org.apache.activemq.artemis.api.core.management.DivertControl; import org.apache.activemq.artemis.api.core.management.ActiveMQServerControl; import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; import org.apache.activemq.artemis.api.core.management.QueueControl; import org.apache.activemq.artemis.api.jms.management.ConnectionFactoryControl; import org.apache.activemq.artemis.api.jms.management.JMSQueueControl; import org.apache.activemq.artemis.api.jms.management.JMSServerControl; import org.apache.activemq.artemis.api.jms.management.TopicControl; public class ManagementControlHelper { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- public static AcceptorControl createAcceptorControl(final String name, final MBeanServer mbeanServer) throws Exception { return (AcceptorControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getAcceptorObjectName(name), AcceptorControl.class, mbeanServer); } public static BroadcastGroupControl createBroadcastGroupControl(final String name, final MBeanServer mbeanServer) throws Exception { return (BroadcastGroupControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getBroadcastGroupObjectName(name), BroadcastGroupControl.class, mbeanServer); } public static BridgeControl createBridgeControl(final String name, final MBeanServer mbeanServer) throws Exception { return (BridgeControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getBridgeObjectName(name), BridgeControl.class, mbeanServer); } public static DivertControl createDivertControl(final String name, final MBeanServer mbeanServer) throws Exception { return (DivertControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getDivertObjectName(name), DivertControl.class, mbeanServer); } public static ClusterConnectionControl createClusterConnectionControl(final String name, final MBeanServer mbeanServer) throws Exception { return (ClusterConnectionControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getClusterConnectionObjectName(name), ClusterConnectionControl.class, mbeanServer); } public static ActiveMQServerControl createActiveMQServerControl(final MBeanServer mbeanServer) throws Exception { return (ActiveMQServerControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getActiveMQServerObjectName(), ActiveMQServerControl.class, mbeanServer); } public static QueueControl createQueueControl(final SimpleString address, final SimpleString name, final MBeanServer mbeanServer) throws Exception { return (QueueControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getQueueObjectName(address, name), QueueControl.class, mbeanServer); } public static AddressControl createAddressControl(final SimpleString address, final MBeanServer mbeanServer) throws Exception { return (AddressControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getAddressObjectName(address), AddressControl.class, mbeanServer); } public static JMSQueueControl createJMSQueueControl(final Queue queue, final MBeanServer mbeanServer) throws Exception { return ManagementControlHelper.createJMSQueueControl(queue.getQueueName(), mbeanServer); } public static JMSQueueControl createJMSQueueControl(final String name, final MBeanServer mbeanServer) throws Exception { return (JMSQueueControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(name), JMSQueueControl.class, mbeanServer); } public static JMSServerControl createJMSServerControl(final MBeanServer mbeanServer) throws Exception { return (JMSServerControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getJMSServerObjectName(), JMSServerControl.class, mbeanServer); } public static ConnectionFactoryControl createConnectionFactoryControl(final String name, final MBeanServer mbeanServer) throws Exception { return (ConnectionFactoryControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getConnectionFactoryObjectName(name), ConnectionFactoryControl.class, mbeanServer); } public static TopicControl createTopicControl(final Topic topic, final MBeanServer mbeanServer) throws Exception { return (TopicControl)ManagementControlHelper.createProxy(ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(topic.getTopicName()), TopicControl.class, mbeanServer); } // Constructors -------------------------------------------------- // Public -------------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- private static Object createProxy(final ObjectName objectName, final Class mbeanInterface, final MBeanServer mbeanServer) { return MBeanServerInvocationHandler.newProxyInstance(mbeanServer, objectName, mbeanInterface, false); } // Inner classes ------------------------------------------------- }
apache-2.0
Gigaspaces/xap-openspaces
src/main/java/org/openspaces/admin/space/Spaces.java
6323
/* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openspaces.admin.space; import org.openspaces.admin.AdminAware; import org.openspaces.admin.StatisticsMonitor; import org.openspaces.admin.space.events.*; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Spaces holds all the currently discovered {@link Space}s. * * <p>Provides simple means to get all the current Space, as well as as registering for * Space lifecycle (added and removed) events. * * <p>Provides the ability to start a statistics monitor on all current Space using * {@link #startStatisticsMonitor()}. Newly discovered Space will automatically use * the statistics monitor as well. * * @author kimchy */ public interface Spaces extends Iterable<Space>, AdminAware, StatisticsMonitor { /** * Returns all the currently discovered {@link org.openspaces.admin.space.Space}s. */ Space[] getSpaces(); /** * Returns a space based on its uid. */ Space getSpaceByUID(String uid); /** * Returns a space based on its name. */ Space getSpaceByName(String name); /** * Returns a map of {@link org.openspaces.admin.space.Space}s keyed by their names. */ Map<String, Space> getNames(); /** * Waits indefinitely till the provided Space name is discovered. * * @param spaceName The space name to wait for */ Space waitFor(String spaceName); /** * Waits for the given timeout (in time unit) till the space name is discovered. * Returns <code>true</code> if the space is discovered, <code>false</code> * if the timeout expired. */ Space waitFor(String spaceName, long timeout, TimeUnit timeUnit); /** * Returns an event manager allowing to add {@link org.openspaces.admin.space.events.SpaceAddedEventListener}s. */ SpaceAddedEventManager getSpaceAdded(); /** * Returns an event manager allowing to remove {@link org.openspaces.admin.space.events.SpaceAddedEventListener}s. */ SpaceRemovedEventManager getSpaceRemoved(); /** * Adds a {@link org.openspaces.admin.space.events.SpaceLifecycleEventListener} to be notified * when a {@link org.openspaces.admin.space.Space} is added and removed. */ void addLifecycleListener(SpaceLifecycleEventListener eventListener); /** * Removes a {@link org.openspaces.admin.space.events.SpaceLifecycleEventListener} to be notified * when a {@link org.openspaces.admin.space.Space} is added and removed. */ void removeLifecycleListener(SpaceLifecycleEventListener eventListener); /** * Returns an event manager allowing to globally add {@link org.openspaces.admin.space.events.SpaceInstanceAddedEventListener} * that will be called for any space instance discovered. */ SpaceInstanceAddedEventManager getSpaceInstanceAdded(); /** * Returns an event manager allowing to globally remove {@link org.openspaces.admin.space.events.SpaceInstanceAddedEventListener} * that will be called for any space instance discovered. */ SpaceInstanceRemovedEventManager getSpaceInstanceRemoved(); /** * Allows to add a {@link org.openspaces.admin.space.events.SpaceInstanceLifecycleEventListener} hthat will be called * for any space instance discovered. */ void addLifecycleListener(SpaceInstanceLifecycleEventListener eventListener); /** * Allows to remove a {@link org.openspaces.admin.space.events.SpaceInstanceLifecycleEventListener} hthat will be called * for any space instance discovered. */ void removeLifecycleListener(SpaceInstanceLifecycleEventListener eventListener); /** * Returns an event manager allowing to globally register for {@link org.openspaces.admin.space.events.SpaceModeChangedEvent}s * that happen on any Space instance currently discovered. */ SpaceModeChangedEventManager getSpaceModeChanged(); /** * Returns an event manager allowing to globally register for {@link org.openspaces.admin.space.events.ReplicationStatusChangedEvent}s * that happen on any Space instance currently discovered. */ ReplicationStatusChangedEventManager getReplicationStatusChanged(); /** * Returns an event manager allowing to register for {@link org.openspaces.admin.space.events.SpaceStatisticsChangedEvent}s * that occur on all the currently discovered {@link org.openspaces.admin.space.Space}s. * * <p>Note, {@link #startStatisticsMonitor()} must be called in order to start monitor statistics. */ SpaceStatisticsChangedEventManager getSpaceStatisticsChanged(); /** * Returns an event manager allowing to register for {@link org.openspaces.admin.space.events.SpaceInstanceStatisticsChangedEvent}s * that occur on all the currently discovered {@link org.openspaces.admin.space.SpaceInstance}s. * * <p>Note, {@link #startStatisticsMonitor()} must be called in order to start monitoring statistics. */ SpaceInstanceStatisticsChangedEventManager getSpaceInstanceStatisticsChanged(); }
apache-2.0
kostin88/cm_api
java/src/main/java/com/cloudera/api/model/ApiHostInstallArguments.java
7798
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, 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 com.cloudera.api.model; import com.cloudera.api.ApiUtils; import com.google.common.base.Objects; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; /** * Arguments to perform installation on one * or more hosts */ @XmlRootElement(name = "hostInstallArgs") public class ApiHostInstallArguments { private List<String> hostNames; private Integer sshPort; private String userName; private String password; private String privateKey; private String passphrase; private Integer parallelInstallCount; private String cmRepoUrl; private String gpgKeyCustomUrl; private String javaInstallStrategy = "AUTO"; private boolean unlimitedJCE = false; public ApiHostInstallArguments() { // For JAX-B } public String toString() { return Objects.toStringHelper(this) .add("hostNames", hostNames) .add("sshPort", sshPort) .add("userName", userName) .add("password", password) .add("privateKey", privateKey) .add("passphrase", passphrase) .add("parallelInstallCount", parallelInstallCount) .add("cmRepoUrl", cmRepoUrl) .add("gpgKeyCustomUrl", gpgKeyCustomUrl) .add("javaInstallStrategy", javaInstallStrategy) .toString(); } @Override public boolean equals(Object o) { ApiHostInstallArguments that = ApiUtils.baseEquals(this, o); return this == that || (that != null && Objects.equal(hostNames, that.getHostNames()) && Objects.equal(sshPort, that.getSshPort()) && Objects.equal(userName, that.getUserName()) && Objects.equal(password, that.getPassword()) && Objects.equal(privateKey, that.getPrivateKey()) && Objects.equal(passphrase, that.getPassphrase()) && Objects.equal(parallelInstallCount, that.getParallelInstallCount()) && Objects.equal(cmRepoUrl, that.getCmRepoUrl()) && Objects.equal(gpgKeyCustomUrl, that.getGpgKeyCustomUrl()) && Objects.equal(javaInstallStrategy, that.getJavaInstallStrategy())); } @Override public int hashCode() { return Objects.hashCode(hostNames, userName, password, privateKey, passphrase, gpgKeyCustomUrl); } /** * List of hosts to configure for use with Cloudera Manager. * A host may be specified by a hostname (FQDN) or an * IP address. */ @XmlElementWrapper(name = "hostNames") public List<String> getHostNames() { return hostNames; } public void setHostNames(List<String> hostNames) { this.hostNames = hostNames; } /** * SSH port. If unset, defaults to 22. */ @XmlElement public Integer getSshPort() { return sshPort; } public void setSshPort(Integer sshPort) { this.sshPort = sshPort; } /** * The username used to authenticate with the hosts. * Root access to your hosts is required to install Cloudera packages. * The installer will connect to your hosts via SSH and log in either * directly as root or as another user with password-less sudo * privileges to become root. */ @XmlElement public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } /** * The password used to authenticate with the hosts. * Specify either this or a private key. * For password-less login, use an empty string as * password. */ @XmlElement public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } /** * The private key to authenticate with the hosts. * Specify either this or a password. * <br> * The private key, if specified, needs to be a * standard PEM-encoded key as a single string, with all line breaks * replaced with the line-feed control character '\n'. * <br> * A value will typically look like the following string: * <br> * -----BEGIN RSA PRIVATE KEY-----\n[base-64 encoded key]\n-----END RSA PRIVATE KEY----- * <br> */ @XmlElement public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } /** * The passphrase associated with the private key * used to authenticate with the hosts (optional). */ @XmlElement public String getPassphrase() { return passphrase; } public void setPassphrase(String passphrase) { this.passphrase = passphrase; } /** * Number of simultaneous installations. * Defaults to 10. Running a large number of * installations at once can consume large * amounts of network bandwidth and other system * resources. */ @XmlElement public Integer getParallelInstallCount() { return parallelInstallCount; } public void setParallelInstallCount(Integer parallelInstallCount) { this.parallelInstallCount = parallelInstallCount; } /** * The Cloudera Manager repository URL to use (optional). * Example for SLES, Redhat or other RPM based distributions: * http://archive.cloudera.com/cm5/redhat/5/x86_64/cm/5/ * Example for Ubuntu or other Debian based distributions: * "deb http://archive.cloudera.com/cm5/ubuntu/lucid/amd64/cm lucid-cm5 contrib" */ @XmlElement public String getCmRepoUrl() { return cmRepoUrl; } public void setCmRepoUrl(String cmRepoUrl) { this.cmRepoUrl = cmRepoUrl; } /** * The Cloudera Manager public GPG key (optional). * Example for SLES, Redhat or other RPM based distributions: * http://archive.cloudera.com/cm5/redhat/5/x86_64/cm/RPM-GPG-KEY-cloudera * Example for Ubuntu or other Debian based distributions: * http://archive.cloudera.com/cm5/ubuntu/lucid/amd64/cm/archive.key */ @XmlElement public String getGpgKeyCustomUrl() { return gpgKeyCustomUrl; } public void setGpgKeyCustomUrl(String gpgKeyCustomUrl) { this.gpgKeyCustomUrl = gpgKeyCustomUrl; } /** * Added in v8: Strategy to use for JDK installation. Valid values are * 1. AUTO (default): Cloudera Manager will install the JDK versions that are * required when the "AUTO" option is selected. * Cloudera Manager may overwrite any of the existing JDK installations. * 2. NONE: Cloudera Manager will not install any JDK when "NONE" option is selected. * It should be used if an existing JDK installation has to be used. */ @XmlElement public String getJavaInstallStrategy() { return javaInstallStrategy; } public void setJavaInstallStrategy(String javaInstallStrategy) { this.javaInstallStrategy = javaInstallStrategy; } /** * Added in v8: Flag for unlimited strength JCE policy files installation * If unset, defaults to false */ @XmlElement public boolean isUnlimitedJCE() { return unlimitedJCE; } public void setUnlimitedJCE(boolean unlimitedJCE) { this.unlimitedJCE = unlimitedJCE; } }
apache-2.0
google-code-export/google-api-dfp-java
src/com/google/api/ads/dfp/v201311/PopulateAudienceSegments.java
2790
/** * PopulateAudienceSegments.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.google.api.ads.dfp.v201311; /** * Action that can be performed on {@link FirstPartyAudienceSegment} * objects to populate them based * on last 30 days of traffic. */ public class PopulateAudienceSegments extends com.google.api.ads.dfp.v201311.AudienceSegmentAction implements java.io.Serializable { public PopulateAudienceSegments() { } public PopulateAudienceSegments( java.lang.String audienceSegmentActionType) { super( audienceSegmentActionType); } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof PopulateAudienceSegments)) return false; PopulateAudienceSegments other = (PopulateAudienceSegments) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(PopulateAudienceSegments.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "PopulateAudienceSegments")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
smanvi-pivotal/geode
geode-core/src/test/java/org/apache/geode/cache/query/internal/index/IndexMaintainceJUnitTest.java
19402
/* * 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. */ /* * IndexMaintainceJUnitTest.java * * Created on February 24, 2005, 5:47 PM */ package org.apache.geode.cache.query.internal.index; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Collection; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runners.MethodSorters; import org.apache.geode.cache.Cache; import org.apache.geode.cache.Region; import org.apache.geode.cache.query.CacheUtils; import org.apache.geode.cache.query.Index; import org.apache.geode.cache.query.IndexExistsException; import org.apache.geode.cache.query.IndexNameConflictException; import org.apache.geode.cache.query.IndexStatistics; import org.apache.geode.cache.query.IndexType; import org.apache.geode.cache.query.Query; import org.apache.geode.cache.query.QueryService; import org.apache.geode.cache.query.RegionNotFoundException; import org.apache.geode.cache.query.SelectResults; import org.apache.geode.cache.query.Utils; import org.apache.geode.cache.query.data.Portfolio; import org.apache.geode.cache.query.functional.StructSetOrResultsSet; import org.apache.geode.cache.query.internal.QueryObserverAdapter; import org.apache.geode.cache.query.internal.QueryObserverHolder; import org.apache.geode.test.dunit.ThreadUtils; import org.apache.geode.test.junit.categories.IntegrationTest; /** * */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(IntegrationTest.class) public class IndexMaintainceJUnitTest { @Before public void setUp() throws Exception { if (!isInitDone) { init(); } } @After public void tearDown() throws Exception {} static QueryService qs; static boolean isInitDone = false; static Region region; static IndexProtocol index; protected boolean indexUsed = false; private static void init() { try { Cache cache = CacheUtils.getCache(); region = CacheUtils.createRegion("portfolio", Portfolio.class); region.put("0", new Portfolio(0)); region.put("1", new Portfolio(1)); region.put("2", new Portfolio(2)); region.put("3", new Portfolio(3)); qs = cache.getQueryService(); index = (IndexProtocol) qs.createIndex("statusIndex", IndexType.FUNCTIONAL, "status", "/portfolio"); assertTrue(index instanceof CompactRangeIndex); } catch (Exception e) { e.printStackTrace(); } isInitDone = true; } @Test public void test000BUG32452() throws IndexNameConflictException, IndexExistsException, RegionNotFoundException { Index i1 = qs.createIndex("tIndex", IndexType.FUNCTIONAL, "vals.secId", "/portfolio pf, pf.positions.values vals"); Index i2 = qs.createIndex("dIndex", IndexType.FUNCTIONAL, "pf.getCW(pf.ID)", "/portfolio pf"); Index i3 = qs.createIndex("fIndex", IndexType.FUNCTIONAL, "sIter", "/portfolio pf, pf.collectionHolderMap[(pf.ID).toString()].arr sIter"); Index i4 = qs.createIndex("cIndex", IndexType.FUNCTIONAL, "pf.collectionHolderMap[(pf.ID).toString()].arr[pf.ID]", "/portfolio pf"); Index i5 = qs.createIndex("inIndex", IndexType.FUNCTIONAL, "kIter.secId", "/portfolio['0'].positions.values kIter"); Index i6 = qs.createIndex("sIndex", IndexType.FUNCTIONAL, "pos.secId", "/portfolio.values val, val.positions.values pos"); Index i7 = qs.createIndex("p1Index", IndexType.PRIMARY_KEY, "pkid", "/portfolio pf"); Index i8 = qs.createIndex("p2Index", IndexType.PRIMARY_KEY, "pk", "/portfolio pf"); if (!i1.getCanonicalizedFromClause() .equals("/portfolio index_iter1, index_iter1.positions.values index_iter2") || !i1.getCanonicalizedIndexedExpression().equals("index_iter2.secId") || !i1.getFromClause().equals("/portfolio pf, pf.positions.values vals") || !i1.getIndexedExpression().equals("vals.secId")) { fail("Mismatch found among fromClauses or IndexedExpressions"); } if (!i2.getCanonicalizedFromClause().equals("/portfolio index_iter1") || !i2.getCanonicalizedIndexedExpression().equals("index_iter1.getCW(index_iter1.ID)") || !i2.getFromClause().equals("/portfolio pf") || !i2.getIndexedExpression().equals("pf.getCW(pf.ID)")) { fail("Mismatch found among fromClauses or IndexedExpressions"); } if (!i3.getCanonicalizedFromClause().equals( "/portfolio index_iter1, index_iter1.collectionHolderMap[index_iter1.ID.toString()].arr index_iter3") || !i3.getCanonicalizedIndexedExpression().equals("index_iter3") || !i3.getFromClause() .equals("/portfolio pf, pf.collectionHolderMap[(pf.ID).toString()].arr sIter") || !i3.getIndexedExpression().equals("sIter")) { fail("Mismatch found among fromClauses or IndexedExpressions"); } if (!i4.getCanonicalizedFromClause().equals("/portfolio index_iter1") || !i4.getCanonicalizedIndexedExpression().equals( "index_iter1.collectionHolderMap[index_iter1.ID.toString()].arr[index_iter1.ID]") || !i4.getFromClause().equals("/portfolio pf") || !i4.getIndexedExpression() .equals("pf.collectionHolderMap[(pf.ID).toString()].arr[pf.ID]")) { fail("Mismatch found among fromClauses or IndexedExpressions"); } if (!i5.getCanonicalizedFromClause().equals("/portfolio['0'].positions.values index_iter4") || !i5.getCanonicalizedIndexedExpression().equals("index_iter4.secId") || !i5.getFromClause().equals("/portfolio['0'].positions.values kIter") || !i5.getIndexedExpression().equals("kIter.secId")) { fail("Mismatch found among fromClauses or IndexedExpressions"); } if (!i6.getCanonicalizedFromClause() .equals("/portfolio.values index_iter5, index_iter5.positions.values index_iter6") || !i6.getCanonicalizedIndexedExpression().equals("index_iter6.secId") || !i6.getFromClause().equals("/portfolio.values val, val.positions.values pos") || !i6.getIndexedExpression().equals("pos.secId")) { fail("Mismatch found among fromClauses or IndexedExpressions"); } if (!i7.getCanonicalizedFromClause().equals("/portfolio index_iter1") || !i7.getCanonicalizedIndexedExpression().equals("index_iter1.pkid") || !i7.getFromClause().equals("/portfolio pf") || !i7.getIndexedExpression().equals("pkid")) { fail("Mismatch found among fromClauses or IndexedExpressions"); } if (!i8.getCanonicalizedFromClause().equals("/portfolio index_iter1") || !i8.getCanonicalizedIndexedExpression().equals("index_iter1.pk") || !i8.getFromClause().equals("/portfolio pf") || !i8.getIndexedExpression().equals("pk")) { fail("Mismatch found among fromClauses or IndexedExpressions"); } qs.removeIndex(i1); qs.removeIndex(i2); qs.removeIndex(i3); qs.removeIndex(i4); qs.removeIndex(i5); qs.removeIndex(i6); qs.removeIndex(i7); qs.removeIndex(i8); Index i9 = qs.createIndex("p3Index", IndexType.PRIMARY_KEY, "getPk", "/portfolio pf"); if (!i9.getCanonicalizedFromClause().equals("/portfolio index_iter1") || !i9.getCanonicalizedIndexedExpression().equals("index_iter1.pk") || !i9.getFromClause().equals("/portfolio pf") || !i9.getIndexedExpression().equals("getPk")) { fail("Mismatch found among fromClauses or IndexedExpressions"); } qs.removeIndex(i9); } @Test public void test001AddEntry() throws Exception { CacheUtils.log(((CompactRangeIndex) index).dump()); IndexStatistics stats = index.getStatistics(); assertEquals(4, stats.getNumberOfValues()); // org.apache.geode.internal.util. // DebuggerSupport.waitForJavaDebugger(region.getCache().getLogger()); region.put("4", new Portfolio(4)); CacheUtils.log(((CompactRangeIndex) index).dump()); stats = index.getStatistics(); assertEquals(5, stats.getNumberOfValues()); // Set results = new HashSet(); // index.query("active", OQLLexerTokenTypes.TOK_EQ, results, new ExecutionContext(null, // CacheUtils.getCache())); SelectResults results = region.query("status = 'active'"); assertEquals(3, results.size()); } // !!!:ezoerner:20081030 disabled because modifying an object in place // and then putting it back into the cache breaks a CompactRangeIndex. // @todo file a ticket on this issue @Ignore @Test public void test002UpdateEntry() throws Exception { IndexStatistics stats = index.getStatistics(); CacheUtils.log(((CompactRangeIndex) index).dump()); Portfolio p = (Portfolio) region.get("4"); p.status = "inactive"; region.put("4", p); assertEquals(5, stats.getNumberOfValues()); // Set results = new HashSet(); // index.query("active", OQLLexerTokenTypes.TOK_EQ, results,new ExecutionContext(null, // CacheUtils.getCache())); SelectResults results = region.query("status = 'active'"); assertEquals(2, results.size()); } @Test public void test003InvalidateEntry() throws Exception { IndexStatistics stats = index.getStatistics(); region.invalidate("4"); assertEquals(4, stats.getNumberOfValues()); // Set results = new HashSet(); // index.query("active", OQLLexerTokenTypes.TOK_EQ, results,new ExecutionContext(null, // CacheUtils.getCache())); SelectResults results = region.query("status = 'active'"); assertEquals(2, results.size()); } @Test public void test004DestroyEntry() throws Exception { IndexStatistics stats = index.getStatistics(); region.put("4", new Portfolio(4)); region.destroy("4"); assertEquals(4, stats.getNumberOfValues()); // Set results = new HashSet(); // index.query("active", OQLLexerTokenTypes.TOK_EQ, results,new ExecutionContext(null, // CacheUtils.getCache())); SelectResults results = region.query("status = 'active'"); assertEquals(2, results.size()); } // This test has a meaning only for Trunk code as it checks for Map implementation // Asif : Tests for Region clear operations on Index in a Local VM @Test public void test005IndexClearanceOnMapClear() { try { CacheUtils.restartCache(); IndexMaintainceJUnitTest.isInitDone = false; init(); Query q = qs.newQuery("SELECT DISTINCT * FROM /portfolio where status = 'active'"); QueryObserverHolder.setInstance(new QueryObserverAdapter() { public void afterIndexLookup(Collection coll) { IndexMaintainceJUnitTest.this.indexUsed = true; } }); SelectResults set = (SelectResults) q.execute(); if (set.size() == 0 || !this.indexUsed) { fail("Either Size of the result set is zero or Index is not used "); } this.indexUsed = false; region.clear(); set = (SelectResults) q.execute(); if (set.size() != 0 || !this.indexUsed) { fail("Either Size of the result set is not zero or Index is not used "); } } catch (Exception e) { e.printStackTrace(); fail(e.toString()); } finally { IndexMaintainceJUnitTest.isInitDone = false; CacheUtils.restartCache(); } } // Asif : Tests for Region clear operations on Index in a Local VM for cases // when a clear // operation & region put operation occur concurrentlty @Test public void test006ConcurrentMapClearAndRegionPutOperation() { try { CacheUtils.restartCache(); IndexMaintainceJUnitTest.isInitDone = false; init(); Query q = qs.newQuery("SELECT DISTINCT * FROM /portfolio where status = 'active'"); QueryObserverHolder.setInstance(new QueryObserverAdapter() { public void afterIndexLookup(Collection coll) { IndexMaintainceJUnitTest.this.indexUsed = true; } public void beforeRerunningIndexCreationQuery() { // Spawn a separate thread here which does a put opertion on region Thread th = new Thread(new Runnable() { public void run() { // Assert that the size of region is now 0 assertTrue(IndexMaintainceJUnitTest.region.size() == 0); IndexMaintainceJUnitTest.region.put("" + 8, new Portfolio(8)); } }); th.start(); ThreadUtils.join(th, 30 * 1000); assertTrue(IndexMaintainceJUnitTest.region.size() == 1); } }); SelectResults set = (SelectResults) q.execute(); if (set.size() == 0 || !this.indexUsed) { fail("Either Size of the result set is zero or Index is not used "); } this.indexUsed = false; region.clear(); set = (SelectResults) q.execute(); if (set.size() != 1 || !this.indexUsed) { fail("Either Size of the result set is not one or Index is not used "); } } catch (Exception e) { e.printStackTrace(); fail(e.toString()); } finally { IndexMaintainceJUnitTest.isInitDone = false; CacheUtils.restartCache(); } } @Test public void test007IndexUpdate() { try { CacheUtils.restartCache(); IndexMaintainceJUnitTest.isInitDone = false; init(); qs.removeIndexes(); index = (IndexProtocol) qs.createIndex("statusIndex", IndexType.FUNCTIONAL, "pos.secId", "/portfolio p , p.positions.values pos"); String queryStr = "Select distinct pf from /portfolio pf , pf.positions.values ps where ps.secId='SUN'"; Query query = qs.newQuery(queryStr); SelectResults rs = (SelectResults) query.execute(); int size1 = rs.size(); for (int i = 4; i < 50; ++i) { region.put("" + i, new Portfolio(i)); } rs = (SelectResults) query.execute(); int size2 = rs.size(); assertTrue(size2 > size1); } catch (Exception e) { e.printStackTrace(); fail("Test failed due to exception=" + e); } finally { IndexMaintainceJUnitTest.isInitDone = false; CacheUtils.restartCache(); } } /** * Test to compare range and compact index. They should return the same results. */ @Test public void test008RangeAndCompactRangeIndex() { try { // CacheUtils.restartCache(); if (!IndexMaintainceJUnitTest.isInitDone) { init(); } qs.removeIndexes(); String[] queryStr = new String[] {"Select status from /portfolio pf where status='active'", "Select pf.ID from /portfolio pf where pf.ID > 2 and pf.ID < 100", "Select * from /portfolio pf where pf.position1.secId > '2'",}; String[] queryFields = new String[] {"status", "ID", "position1.secId",}; for (int i = 0; i < queryStr.length; i++) { // Clear indexes if any. qs.removeIndexes(); // initialize region. region.clear(); for (int k = 0; k < 10; k++) { region.put("" + k, new Portfolio(k)); } for (int j = 0; j < 1; j++) { // With different region size. // Update Region. for (int k = 0; k < (j * 100); k++) { region.put("" + k, new Portfolio(k)); } // Create compact index. IndexManager.TEST_RANGEINDEX_ONLY = false; index = (IndexProtocol) qs.createIndex(queryFields[i] + "Index", IndexType.FUNCTIONAL, queryFields[i], "/portfolio"); // Execute Query. SelectResults[][] rs = new SelectResults[1][2]; Query query = qs.newQuery(queryStr[i]); rs[0][0] = (SelectResults) query.execute(); // remove compact index. qs.removeIndexes(); // Create Range Index. IndexManager.TEST_RANGEINDEX_ONLY = true; index = (IndexProtocol) qs.createIndex(queryFields[i] + "rIndex", IndexType.FUNCTIONAL, queryFields[i], "/portfolio"); query = qs.newQuery(queryStr[i]); rs[0][1] = (SelectResults) query.execute(); CacheUtils.log( "#### rs1 size is : " + (rs[0][0]).size() + " rs2 size is : " + (rs[0][1]).size()); StructSetOrResultsSet ssORrs = new StructSetOrResultsSet(); ssORrs.CompareQueryResultsWithoutAndWithIndexes(rs, 1, queryStr); } } } catch (Exception e) { e.printStackTrace(); fail("Test failed due to exception=" + e); } finally { IndexManager.TEST_RANGEINDEX_ONLY = false; IndexMaintainceJUnitTest.isInitDone = false; CacheUtils.restartCache(); } } /** * Test to compare range and compact index. They should return the same results. */ @Test public void test009AcquringCompactRangeIndexEarly() { try { // CacheUtils.restartCache(); if (!IndexMaintainceJUnitTest.isInitDone) { init(); } qs.removeIndexes(); String[] queryStr = new String[] {"Select status from /portfolio pf where status='active'", "Select * from /portfolio pf, pf.positions.values pos where pf.ID > 10 and pf.status='active'", "Select pf.ID from /portfolio pf where pf.ID > 2 and pf.ID < 100", "Select * from /portfolio pf where pf.position1.secId > '2'", "Select * from /portfolio pf, pf.positions.values pos where pos.secId > '2'",}; // initialize region. region.clear(); for (int k = 0; k < 10; k++) { region.put("" + k, new Portfolio(k)); } // Create range and compact-range indexes. qs.createIndex("id2Index ", IndexType.FUNCTIONAL, "pf.ID", "/portfolio pf"); qs.createIndex("id2PosIndex ", IndexType.FUNCTIONAL, "pf.ID", "/portfolio pf, pf.positions.values"); qs.createIndex("status2PosIndex ", IndexType.FUNCTIONAL, "pos.secId", "/portfolio pf, pf.positions.values pos"); // Set the acquire compact range index flag to true // IndexManager.TEST_ACQUIRE_COMPACTINDEX_LOCKS_EARLY = true; // Update Region. for (int k = 0; k < 100; k++) { region.put("" + k, new Portfolio(k)); } for (int i = 0; i < queryStr.length; i++) { // Execute Query. SelectResults[][] rs = new SelectResults[1][2]; Query query = qs.newQuery(queryStr[i]); rs[0][0] = (SelectResults) query.execute(); } } catch (Exception e) { e.printStackTrace(); fail("Test failed due to exception=" + e); } finally { // IndexManager.TEST_ACQUIRE_COMPACTINDEX_LOCKS_EARLY = false; IndexMaintainceJUnitTest.isInitDone = false; CacheUtils.restartCache(); } } }
apache-2.0
tanliu/ElectronicRecord
ElecRecord/src/com/zhbit/transform/PolstatusTransform.java
2164
package com.zhbit.transform; import java.lang.management.PlatformLoggingMXBean; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import com.zhbit.entity.Politicalstatus; import com.zhbit.entity.StuStatus; import com.zhbit.entity.excel.PolstatusExcel; import org.apache.commons.lang3.StringUtils; public class PolstatusTransform implements BaseTransfrom{ //将excel类的实体转化成存入数据库时的实体对象 @Override public List<Object> toDBEntity(List excelObjs) { // TODO Auto-generated method stub //创建list集合 存放 对象 List<Object> Polstatus = new ArrayList<Object>(); //将对应的Excel实体类对象转化为真正的实体对象 for(Object object:excelObjs){ PolstatusExcel polstatusExcel=(PolstatusExcel)object;//进行类型转换 Politicalstatus politicalstatus=new Politicalstatus(); //设置一个默认stu_id politicalstatus.setStuId("9527"); //设定创建时间 Timestamp createtime = new Timestamp(System.currentTimeMillis()); politicalstatus.setCreateTime(createtime); //设定好对应的各个属性值 并判断不为空 if(!StringUtils.isEmpty(polstatusExcel.getStudentNo())){ politicalstatus.setStudentNo(polstatusExcel.getStudentNo());} if(!StringUtils.isEmpty(polstatusExcel.getStuName())){ politicalstatus.setStuName(polstatusExcel.getStuName());} if(!StringUtils.isEmpty(polstatusExcel.getPoliticalStatus())){ politicalstatus.setPoliticalStatus(polstatusExcel.getPoliticalStatus());} if(!StringUtils.isEmpty(polstatusExcel.getMemo())){ politicalstatus.setMemo(polstatusExcel.getMemo());} //设定入党日期 if(!StringUtils.isEmpty((polstatusExcel.getJoinDate()))){ politicalstatus.setJoinDate(Timestamp.valueOf(polstatusExcel.getJoinDate().trim()+" 00:00:00"));} //将此对象放入集合Polstatus中 Polstatus.add(politicalstatus); } //返回对象集合 return Polstatus; } @Override public List<Object> toExcelObj(List dbObjs) { // TODO Auto-generated method stub return null; } }
apache-2.0
stealthcode/RxJavaMulti
src/main/java/rx/TriObservable.java
45
package rx; public class TriObservable { }
apache-2.0
AntimatterResearch/kurento-room
kurento-room-client/src/main/java/org/kurento/room/client/KurentoRoomClient.java
9517
/* * (C) Copyright 2015 Kurento (http://kurento.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 org.kurento.room.client; import static org.kurento.room.internal.ProtocolElements.CUSTOMREQUEST_METHOD; import static org.kurento.room.internal.ProtocolElements.JOINROOM_DATACHANNELS_PARAM; import static org.kurento.room.internal.ProtocolElements.JOINROOM_METHOD; import static org.kurento.room.internal.ProtocolElements.JOINROOM_PEERID_PARAM; import static org.kurento.room.internal.ProtocolElements.JOINROOM_PEERSTREAMID_PARAM; import static org.kurento.room.internal.ProtocolElements.JOINROOM_PEERSTREAMS_PARAM; import static org.kurento.room.internal.ProtocolElements.JOINROOM_ROOM_PARAM; import static org.kurento.room.internal.ProtocolElements.JOINROOM_USER_PARAM; import static org.kurento.room.internal.ProtocolElements.LEAVEROOM_METHOD; import static org.kurento.room.internal.ProtocolElements.ONICECANDIDATE_CANDIDATE_PARAM; import static org.kurento.room.internal.ProtocolElements.ONICECANDIDATE_EPNAME_PARAM; import static org.kurento.room.internal.ProtocolElements.ONICECANDIDATE_METHOD; import static org.kurento.room.internal.ProtocolElements.ONICECANDIDATE_SDPMIDPARAM; import static org.kurento.room.internal.ProtocolElements.ONICECANDIDATE_SDPMLINEINDEX_PARAM; import static org.kurento.room.internal.ProtocolElements.PUBLISHVIDEO_DOLOOPBACK_PARAM; import static org.kurento.room.internal.ProtocolElements.PUBLISHVIDEO_METHOD; import static org.kurento.room.internal.ProtocolElements.PUBLISHVIDEO_SDPANSWER_PARAM; import static org.kurento.room.internal.ProtocolElements.PUBLISHVIDEO_SDPOFFER_PARAM; import static org.kurento.room.internal.ProtocolElements.RECEIVEVIDEO_METHOD; import static org.kurento.room.internal.ProtocolElements.RECEIVEVIDEO_SDPANSWER_PARAM; import static org.kurento.room.internal.ProtocolElements.RECEIVEVIDEO_SDPOFFER_PARAM; import static org.kurento.room.internal.ProtocolElements.RECEIVEVIDEO_SENDER_PARAM; import static org.kurento.room.internal.ProtocolElements.SENDMESSAGE_MESSAGE_PARAM; import static org.kurento.room.internal.ProtocolElements.SENDMESSAGE_ROOM_METHOD; import static org.kurento.room.internal.ProtocolElements.SENDMESSAGE_ROOM_PARAM; import static org.kurento.room.internal.ProtocolElements.SENDMESSAGE_USER_PARAM; import static org.kurento.room.internal.ProtocolElements.UNPUBLISHVIDEO_METHOD; import static org.kurento.room.internal.ProtocolElements.UNSUBSCRIBEFROMVIDEO_METHOD; import static org.kurento.room.internal.ProtocolElements.UNSUBSCRIBEFROMVIDEO_SENDER_PARAM; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.kurento.jsonrpc.client.JsonRpcClient; import org.kurento.jsonrpc.client.JsonRpcClientWebSocket; import org.kurento.jsonrpc.client.JsonRpcWSConnectionListener; import org.kurento.room.client.internal.JsonRoomUtils; import org.kurento.room.client.internal.Notification; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * Java client for the room server. * * @author <a href="mailto:rvlad@naevatec.com">Radu Tom Vlad</a> */ public class KurentoRoomClient { private static final Logger log = LoggerFactory.getLogger(KurentoRoomClient.class); private JsonRpcClient client; private ServerJsonRpcHandler handler; public KurentoRoomClient(String wsUri) { this(new JsonRpcClientWebSocket(wsUri, new JsonRpcWSConnectionListener() { @Override public void reconnected(boolean sameServer) { } @Override public void disconnected() { log.warn("JsonRpcWebsocket connection: Disconnected"); } @Override public void connectionFailed() { log.warn("JsonRpcWebsocket connection: Connection failed"); } @Override public void connected() { } @Override public void reconnecting() { log.warn("JsonRpcWebsocket connection: is reconnecting"); } }, new SslContextFactory(true))); } public KurentoRoomClient(JsonRpcClient client) { this.client = client; this.handler = new ServerJsonRpcHandler(); this.client.setServerRequestHandler(this.handler); } public KurentoRoomClient(JsonRpcClient client, ServerJsonRpcHandler handler) { this.client = client; this.handler = handler; this.client.setServerRequestHandler(this.handler); } public void close() throws IOException { this.client.close(); } public Map<String, List<String>> joinRoom(String roomName, String userName, Boolean dataChannels) throws IOException { JsonObject params = new JsonObject(); params.addProperty(JOINROOM_ROOM_PARAM, roomName); params.addProperty(JOINROOM_USER_PARAM, userName); if (dataChannels != null) { params.addProperty(JOINROOM_DATACHANNELS_PARAM, dataChannels); } JsonElement result = client.sendRequest(JOINROOM_METHOD, params); Map<String, List<String>> peers = new HashMap<String, List<String>>(); JsonArray jsonPeers = JsonRoomUtils.getResponseProperty(result, "value", JsonArray.class); if (jsonPeers.size() > 0) { Iterator<JsonElement> peerIt = jsonPeers.iterator(); while (peerIt.hasNext()) { JsonElement peer = peerIt.next(); String peerId = JsonRoomUtils .getResponseProperty(peer, JOINROOM_PEERID_PARAM, String.class); List<String> streams = new ArrayList<String>(); JsonArray jsonStreams = JsonRoomUtils.getResponseProperty(peer, JOINROOM_PEERSTREAMS_PARAM, JsonArray.class, true); if (jsonStreams != null) { Iterator<JsonElement> streamIt = jsonStreams.iterator(); while (streamIt.hasNext()) { streams.add(JsonRoomUtils.getResponseProperty(streamIt.next(), JOINROOM_PEERSTREAMID_PARAM, String.class)); } } peers.put(peerId, streams); } } return peers; } public void leaveRoom() throws IOException { client.sendRequest(LEAVEROOM_METHOD, new JsonObject()); } public String publishVideo(String sdpOffer, boolean doLoopback) throws IOException { JsonObject params = new JsonObject(); params.addProperty(PUBLISHVIDEO_SDPOFFER_PARAM, sdpOffer); params.addProperty(PUBLISHVIDEO_DOLOOPBACK_PARAM, doLoopback); JsonElement result = client.sendRequest(PUBLISHVIDEO_METHOD, params); return JsonRoomUtils.getResponseProperty(result, PUBLISHVIDEO_SDPANSWER_PARAM, String.class); } public void unpublishVideo() throws IOException { client.sendRequest(UNPUBLISHVIDEO_METHOD, new JsonObject()); } // sender should look like 'username_streamId' public String receiveVideoFrom(String sender, String sdpOffer) throws IOException { JsonObject params = new JsonObject(); params.addProperty(RECEIVEVIDEO_SENDER_PARAM, sender); params.addProperty(RECEIVEVIDEO_SDPOFFER_PARAM, sdpOffer); JsonElement result = client.sendRequest(RECEIVEVIDEO_METHOD, params); return JsonRoomUtils.getResponseProperty(result, RECEIVEVIDEO_SDPANSWER_PARAM, String.class); } // sender should look like 'username_streamId' public void unsubscribeFromVideo(String sender) throws IOException { JsonObject params = new JsonObject(); params.addProperty(UNSUBSCRIBEFROMVIDEO_SENDER_PARAM, sender); client.sendRequest(UNSUBSCRIBEFROMVIDEO_METHOD, params); } public void onIceCandidate(String endpointName, String candidate, String sdpMid, int sdpMLineIndex) throws IOException { JsonObject params = new JsonObject(); params.addProperty(ONICECANDIDATE_EPNAME_PARAM, endpointName); params.addProperty(ONICECANDIDATE_CANDIDATE_PARAM, candidate); params.addProperty(ONICECANDIDATE_SDPMIDPARAM, sdpMid); params.addProperty(ONICECANDIDATE_SDPMLINEINDEX_PARAM, sdpMLineIndex); client.sendRequest(ONICECANDIDATE_METHOD, params); } public void sendMessage(String userName, String roomName, String message) throws IOException { JsonObject params = new JsonObject(); params.addProperty(SENDMESSAGE_USER_PARAM, userName); params.addProperty(SENDMESSAGE_ROOM_PARAM, roomName); params.addProperty(SENDMESSAGE_MESSAGE_PARAM, message); client.sendRequest(SENDMESSAGE_ROOM_METHOD, params); } public JsonElement customRequest(JsonObject customReqParams) throws IOException { return client.sendRequest(CUSTOMREQUEST_METHOD, customReqParams); } /** * Polls the notifications list maintained by this client to obtain new events sent by server. * This method blocks until there is a notification to return. This is a one-time operation for * the returned element. * * @return a server notification object, null when interrupted while waiting */ public Notification getServerNotification() { return this.handler.getNotification(); } }
apache-2.0
lessthanoptimal/DeepBoof
modules/main/src/test/java/deepboof/impl/forward/standard/TestFunctionBatchNorm_F64.java
4589
/* * Copyright (c) 2016, Peter Abeles. All Rights Reserved. * * This file is part of DeepBoof * * 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 deepboof.impl.forward.standard; import deepboof.DeepBoofConstants; import deepboof.DeepUnitTest; import deepboof.Function; import deepboof.forward.ChecksForward; import deepboof.misc.TensorFactory_F64; import deepboof.tensors.Tensor_F64; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static deepboof.misc.TensorOps.WT; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Peter Abeles */ public class TestFunctionBatchNorm_F64 extends ChecksForward<Tensor_F64> { // variable to keep track of which configuration was boolean requiresGamma; int N = 5; // number of mini-batch int d0 = 3; // arbitrary other dimensions int d1 = 2; int D = d0 * d1; // total length of other dimensions double EPS = (double)1e-4; public TestFunctionBatchNorm_F64() { super(2); } @Test public void check_two() { for( boolean sub : new boolean[]{false,true}) { FunctionBatchNorm_F64 alg = new FunctionBatchNorm_F64(false); alg.initialize(d0, d1); alg.setEPS(EPS); Tensor_F64 input = TensorFactory_F64.random(random, sub, N, d0, d1); Tensor_F64 params = TensorFactory_F64.random(random, sub, d0, d1, 2); Tensor_F64 output = TensorFactory_F64.random(random, sub, N, d0, d1); Tensor_F64 expected = new Tensor_F64(N, d0, d1); for (int batch = 0; batch < N; batch++) { int indexIn = input.idx(batch, 0, 0); int indexP = params.idx(0,0,0); int indexOut = expected.idx(batch,0,0); for (int i = 0; i < D; i++) { double m = params.d[indexP++]; double v = params.d[indexP++]; expected.d[indexOut++] = (input.d[indexIn++]-m) / Math.sqrt(v+EPS); } } alg.setParameters(WT(params)); alg.forward(input, output); DeepUnitTest.assertEquals(expected,output, DeepBoofConstants.TEST_TOL_F64); } } @Test public void check_four() { for( boolean sub : new boolean[]{false,true}) { FunctionBatchNorm_F64 alg = new FunctionBatchNorm_F64(true); alg.initialize(d0, d1); alg.setEPS(EPS); Tensor_F64 input = TensorFactory_F64.random(random, sub, N, d0, d1); Tensor_F64 params = TensorFactory_F64.random(random, sub, d0, d1, 4); Tensor_F64 output = TensorFactory_F64.random(random, sub, N, d0, d1); Tensor_F64 expected = new Tensor_F64(N, d0, d1); for (int batch = 0; batch < N; batch++) { int indexIn = input.idx(batch, 0, 0); int indexP = params.idx(0,0,0); int indexOut = expected.idx(batch,0,0); for (int i = 0; i < D; i++) { double m = params.d[indexP++]; double v = params.d[indexP++]; double g = params.d[indexP++]; double b = params.d[indexP++]; expected.d[indexOut++] = ((input.d[indexIn++]-m) / Math.sqrt(v+EPS))*g+b; } } alg.setParameters(WT(params)); alg.forward(input, output); DeepUnitTest.assertEquals(expected,output, DeepBoofConstants.TEST_TOL_F64); } } @Override public Function<Tensor_F64> createForwards(int which) { requiresGamma = which != 0; if( which == 0 ) return new FunctionBatchNorm_F64(false); else return new FunctionBatchNorm_F64(true); } @Override public List<Case> createTestInputs() { List<Case> inputs = new ArrayList<>(); inputs.add( new Case( 5,1 )); inputs.add( new Case( 5,2,3,4 )); return inputs; } @Override protected void checkTensorType(Class<Tensor_F64> type) { assertTrue(Tensor_F64.class == type); } @Override protected void checkParameterShapes(int[] input, List<int[]> parameters) { assertEquals(1,parameters.size()); int expected[] = new int[input.length+1]; System.arraycopy(input,0,expected,0,input.length); expected[input.length] = requiresGamma ? 4 : 2;; DeepUnitTest.assertEquals(expected, parameters.get(0)); } @Override protected void checkOutputShapes(int[] input, int[] output) { DeepUnitTest.assertEquals(output, input); } }
apache-2.0
xiangtao/dxwx-transfer
src/main/java/com/axj/apiw/handler/impl/PlaintQueryHandlerImpl.java
2614
package com.axj.apiw.handler.impl; import java.util.Map; import com.axj.apiw.handler.AbstractQueryHandler; import com.axj.apiw.model.FunctionPoint; import com.axj.apiw.model.TUser; import com.axj.apiw.vo.request.MsgIn; import com.axj.apiw.vo.request.MsgInEventClick; import com.axj.apiw.vo.request.MsgInEventLocation; import com.axj.apiw.vo.request.MsgInEventScan; import com.axj.apiw.vo.request.MsgInEventSubscribe; import com.axj.apiw.vo.request.MsgInNormalImage; import com.axj.apiw.vo.request.MsgInNormalLink; import com.axj.apiw.vo.request.MsgInNormalLocation; import com.axj.apiw.vo.request.MsgInNormalText; import com.axj.apiw.vo.request.MsgInNormalVideo; import com.axj.apiw.vo.request.MsgInNormalVoice; import com.axj.apiw.vo.request.MsgInVerify; import com.axj.apiw.vo.response.MsgOut; /** * nothing,empty impl * @author taox * @type PlaintQueryHandlerImpl */ public class PlaintQueryHandlerImpl extends AbstractQueryHandler { @Override public MsgOut handleNormalTextIn(TUser wechat, MsgInNormalText textIn) { return null; } @Override public MsgOut handleNormalImageIn(TUser wechat, MsgInNormalImage textIn) { return null; } @Override public MsgOut handleNormalVoiceIn(TUser wechat, MsgInNormalVoice in) { // TODO Auto-generated method stub return null; } @Override public MsgOut handleNormalVideoIn(TUser wechat, MsgInNormalVideo in) { // TODO Auto-generated method stub return null; } @Override public MsgOut handleNormalLocationIn(TUser wechat, MsgInNormalLocation in) { // TODO Auto-generated method stub return null; } @Override public MsgOut handleNormalLinkIn(TUser wechat, MsgInNormalLink in) { // TODO Auto-generated method stub return null; } @Override public MsgOut handleEventSubOrUnSubscribeIn(TUser wechat, MsgInEventSubscribe in) { // TODO Auto-generated method stub return null; } @Override public MsgOut handleEventScanIn(TUser wechat, MsgInEventScan in) { // TODO Auto-generated method stub return null; } @Override public MsgOut handleEventLocationIn(TUser wechat, MsgInEventLocation in) { // TODO Auto-generated method stub return null; } @Override public MsgOut handleEventClickIn(TUser wechat, MsgInEventClick in) { // TODO Auto-generated method stub return null; } @Override public MsgOut handleVerifyMsgIn(TUser wechat, MsgInVerify in) { // TODO Auto-generated method stub return null; } }
apache-2.0
vityazverev/java_pft
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/HelperBase.java
1347
package ru.stqa.pft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.io.File; /** * Created by Виктор on 22.03.2017. */ public class HelperBase { protected WebDriver wd; public HelperBase(WebDriver wd) { this.wd = wd; } protected void click(By locator) { wd.findElement(locator).click(); } protected void type(By locator, String text) { click(locator); if (text != null) { String existingText = wd.findElement(locator).getAttribute("value"); if (! text.equals(existingText)) { wd.findElement(locator).clear(); wd.findElement(locator).sendKeys(text); } } } public boolean isAlertPresent() { try { wd.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } protected boolean isElementPresent(By locator) { try { wd.findElement(locator); return true; } catch (NoSuchElementException ex){ return false; } } protected void attach(By locator, File file) { if (file != null) { wd.findElement(locator).sendKeys(file.getAbsolutePath()); } } }
apache-2.0
partouf/Chatty-Twitch-Client
src/chatty/util/settings/Setting.java
3959
package chatty.util.settings; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A single setting, holding one value of one of the specified types. The type * and initial (default) value can't be changed, however all other properties * can. The type of the value isn't checked here, the caller has to make sure * to expect only the types of values that were actually saved, the saved type * just helps with this. * * @author tduva */ public class Setting { public static final int UNDEFINED = -1; public static final int BOOLEAN = 0; public static final int STRING = 1; public static final int LONG = 2; public static final int MAP = 3; public static final int LIST = 4; public static final int CHANGED = 5; public static final int NOT_CHANGED = 6; private final Object defaultValue; private final int type; private Object value; private boolean save = true; private String file; /** * Creates a new Setting object with some initial values. * * @param value The initial value and also the default value. * @param type The type of this setting. * @param save Whether this setting should be saved to a file. * @param file The name of the file. Usually the default file. */ public Setting(Object value, int type, boolean save, String file) { this.value = value; if (type == MAP) { this.defaultValue = new HashMap<>((Map)value); } else if (type == LIST) { this.defaultValue = new ArrayList<>((List)value); } else { this.defaultValue = value; } this.save = save; this.type = type; this.file = file; } /** * Returns whether this setting should be saved to a file. * * @return true if it allowed to be saved, false otherwise. */ public boolean allowedToSave() { return save; } /** * Gets the current value of this setting. * * @return */ public Object getValue() { return value; } /** * Checks if this value is of the given type. Types as specified in the * constants in this class. * * @param type * @return */ public boolean isOfType(int type) { return type == this.type; } /** * Gets the type of this setting. * * @return */ public int getType() { return type; } /** * Changes the value if the new one is different from the current value. * * @param value * @return true when a new value was set, false otherwise */ public boolean setValue(Object value) { if (this.value.equals(value)) { return false; } this.value = value; return true; } /** * Reset value to default. * * @return */ public boolean setToDefault() { if (type == MAP) { return setValue(new HashMap<>((Map)defaultValue)); } if (type == LIST) { return setValue(new ArrayList<>((List)defaultValue)); } return setValue(defaultValue); } /** * Set whether this setting should be saved to a file. * * @param save */ public void setSave(boolean save) { this.save = save; } /** * Sets the name of the file this setting should be saved into. * * @param fileName The name of the file. */ public void setFile(String fileName) { this.file = fileName; } /** * Gets the name of the file this setting should be saved into. * * @return The name of the file. */ public String getFile() { return file; } @Override public String toString() { return value.toString(); } }
apache-2.0
cqjjjzr/Laplacian
Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avcodec57/AVSubtitle.java
2255
package org.ffmpeg.avcodec57; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; /** * <i>native declaration : .\libavcodec\avcodec.h:1120</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class AVSubtitle extends Structure { /** 0 = graphics */ public short format; /** relative to packet pts, in ms */ public int start_display_time; /** relative to packet pts, in ms */ public int end_display_time; public int num_rects; /** C type : AVSubtitleRect** */ public org.ffmpeg.avcodec57.AVSubtitleRect.ByReference[] rects; /** < Same as packet pts, in AV_TIME_BASE */ public long pts; public AVSubtitle() { super(); } protected List<String> getFieldOrder() { return Arrays.asList("format", "start_display_time", "end_display_time", "num_rects", "rects", "pts"); } /** * @param format 0 = graphics<br> * @param start_display_time relative to packet pts, in ms<br> * @param end_display_time relative to packet pts, in ms<br> * @param rects C type : AVSubtitleRect**<br> * @param pts < Same as packet pts, in AV_TIME_BASE */ public AVSubtitle(short format, int start_display_time, int end_display_time, int num_rects, org.ffmpeg.avcodec57.AVSubtitleRect.ByReference rects[], long pts) { super(); this.format = format; this.start_display_time = start_display_time; this.end_display_time = end_display_time; this.num_rects = num_rects; if ((rects.length != this.rects.length)) throw new IllegalArgumentException("Wrong array size !"); this.rects = rects; this.pts = pts; } public AVSubtitle(Pointer peer) { super(peer); } public static class ByReference extends AVSubtitle implements Structure.ByReference { }; public static class ByValue extends AVSubtitle implements Structure.ByValue { }; }
apache-2.0
ifnul/ums-backend
is-lnu-converter/src/test/java/org/lnu/is/converter/enrolment/status/EnrolmentStatusResourceConverterTest.java
3180
package org.lnu.is.converter.enrolment.status; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.lnu.is.domain.enrolment.Enrolment; import org.lnu.is.domain.enrolment.status.EnrolmentStatus; import org.lnu.is.domain.enrolment.status.type.EnrolmentStatusType; import org.lnu.is.domain.specoffer.SpecOfferWave; import org.lnu.is.resource.enrolment.status.EnrolmentStatusResource; public class EnrolmentStatusResourceConverterTest { private EnrolmentStatusResourceConverter unit = new EnrolmentStatusResourceConverter(); @Test public void testConvert() throws Exception { // Given Integer isContract = 1; Integer isState = 1; Long enrolmentId = 1L; Enrolment enrolment = new Enrolment(); enrolment.setId(enrolmentId); Long specOfferWaveId = 2L; SpecOfferWave specOfferWave = new SpecOfferWave(); specOfferWave.setId(specOfferWaveId); Long enrolmentStatusTypeId = 3L; EnrolmentStatusType enrolmentStatusType = new EnrolmentStatusType(); enrolmentStatusType.setId(enrolmentStatusTypeId); EnrolmentStatus expected = new EnrolmentStatus(); expected.setEnrolment(enrolment); expected.setSpecOfferWave(specOfferWave); expected.setEnrolmentStatusType(enrolmentStatusType); expected.setIsContract(isContract); expected.setIsState(isState); EnrolmentStatusResource source = new EnrolmentStatusResource(); source.setEnrolmentId(enrolmentId); source.setSpecOfferWaveId(specOfferWaveId); source.setEnrolmentStatusTypeId(enrolmentStatusTypeId); source.setIsContract(isContract); source.setIsState(isState); // When EnrolmentStatus actual = unit.convert(source); // Then assertEquals(expected, actual); } @Test public void testConvertWithEmptyFields() throws Exception { // Given EnrolmentStatus expected = new EnrolmentStatus(); EnrolmentStatusResource source = new EnrolmentStatusResource(); // When EnrolmentStatus actual = unit.convert(source); // Then assertEquals(expected, actual); } @Test public void testConvertAll() throws Exception { // Given Long enrolmentId = 1L; Enrolment enrolment = new Enrolment(); enrolment.setId(enrolmentId); Long specOfferWaveId = 2L; SpecOfferWave specOfferWave = new SpecOfferWave(); specOfferWave.setId(specOfferWaveId); Long enrolmentStatusTypeId = 3L; EnrolmentStatusType enrolmentStatusType = new EnrolmentStatusType(); enrolmentStatusType.setId(enrolmentStatusTypeId); EnrolmentStatus expected = new EnrolmentStatus(); expected.setEnrolment(enrolment); expected.setSpecOfferWave(specOfferWave); expected.setEnrolmentStatusType(enrolmentStatusType); List<EnrolmentStatus> expecteds = Arrays.asList(expected); EnrolmentStatusResource source = new EnrolmentStatusResource(); source.setEnrolmentId(enrolmentId); source.setSpecOfferWaveId(specOfferWaveId); source.setEnrolmentStatusTypeId(enrolmentStatusTypeId); List<EnrolmentStatusResource> sources = Arrays.asList(source); // When List<EnrolmentStatus> actuals = unit.convertAll(sources); // Then assertEquals(expecteds, actuals); } }
apache-2.0
longyuandroid/coolweather
app/src/main/java/com/coolweather/android/service/AutoUpdateService.java
3497
package com.coolweather.android.service; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.os.SystemClock; import android.preference.PreferenceManager; import android.support.annotation.IntDef; import com.coolweather.android.gson.Weather; import com.coolweather.android.util.HttpUtil; import com.coolweather.android.util.Utility; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class AutoUpdateService extends Service { public AutoUpdateService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { updateWeather(); updateBingPic(); AlarmManager manager=(AlarmManager) getSystemService(ALARM_SERVICE); int anHour=8*60*60*1000; long triggerAtTime= SystemClock.elapsedRealtime()+anHour; Intent i = new Intent(this,AutoUpdateService.class); PendingIntent pi=PendingIntent.getService(this,0,i,0); manager.cancel(pi); manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi); return super.onStartCommand(intent,flags,startId); } private void updateWeather(){ SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(this); String weatherString = preferences.getString("weather",null); if(weatherString!=null){ Weather weather= Utility.handleWeatherResopnse(weatherString); String weatherId=weather.basic.weatherId; String weatherUrl="http://guolin.tech/api/weather?cityid="+weatherId+"&key=aa60c630144040e7829ed365ac86b1ce"; HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { String responseText=response.body().string(); Weather weather=Utility.handleWeatherResopnse(responseText); if(weather!=null&&"ok".equals(weather.status)){ SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit(); editor.putString("weather",responseText); editor.apply(); } } }); } } private void updateBingPic(){ String resquestBingPic="http://guolin.tech/api/bing_pic"; HttpUtil.sendOkHttpRequest(resquestBingPic, new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { String bingPic=response.body().string(); SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit(); editor.putString("bing_pic",bingPic); editor.apply(); } }); } }
apache-2.0
Nain57/FirstGame
MyGame/desktop/src/com/buzbuz/mygame/desktop/DesktopLauncher.java
399
package com.buzbuz.mygame.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.buzbuz.mygame.MyGame; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); new LwjglApplication(new MyGame(), config); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-cloud9/src/main/java/com/amazonaws/services/cloud9/model/transform/CreateEnvironmentEC2RequestMarshaller.java
5353
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.cloud9.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.cloud9.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * CreateEnvironmentEC2RequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CreateEnvironmentEC2RequestMarshaller { private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("name").build(); private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("description").build(); private static final MarshallingInfo<String> CLIENTREQUESTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("clientRequestToken").build(); private static final MarshallingInfo<String> INSTANCETYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("instanceType").build(); private static final MarshallingInfo<String> SUBNETID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("subnetId").build(); private static final MarshallingInfo<String> IMAGEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("imageId").build(); private static final MarshallingInfo<Integer> AUTOMATICSTOPTIMEMINUTES_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("automaticStopTimeMinutes").build(); private static final MarshallingInfo<String> OWNERARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("ownerArn").build(); private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("tags").build(); private static final MarshallingInfo<String> CONNECTIONTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("connectionType").build(); private static final MarshallingInfo<Boolean> DRYRUN_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("dryRun").build(); private static final CreateEnvironmentEC2RequestMarshaller instance = new CreateEnvironmentEC2RequestMarshaller(); public static CreateEnvironmentEC2RequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(CreateEnvironmentEC2Request createEnvironmentEC2Request, ProtocolMarshaller protocolMarshaller) { if (createEnvironmentEC2Request == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createEnvironmentEC2Request.getName(), NAME_BINDING); protocolMarshaller.marshall(createEnvironmentEC2Request.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(createEnvironmentEC2Request.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING); protocolMarshaller.marshall(createEnvironmentEC2Request.getInstanceType(), INSTANCETYPE_BINDING); protocolMarshaller.marshall(createEnvironmentEC2Request.getSubnetId(), SUBNETID_BINDING); protocolMarshaller.marshall(createEnvironmentEC2Request.getImageId(), IMAGEID_BINDING); protocolMarshaller.marshall(createEnvironmentEC2Request.getAutomaticStopTimeMinutes(), AUTOMATICSTOPTIMEMINUTES_BINDING); protocolMarshaller.marshall(createEnvironmentEC2Request.getOwnerArn(), OWNERARN_BINDING); protocolMarshaller.marshall(createEnvironmentEC2Request.getTags(), TAGS_BINDING); protocolMarshaller.marshall(createEnvironmentEC2Request.getConnectionType(), CONNECTIONTYPE_BINDING); protocolMarshaller.marshall(createEnvironmentEC2Request.getDryRun(), DRYRUN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
ge0ffrey/camel
components/camel-dozer/src/main/java/org/apache/camel/converter/dozer/DozerTypeConverter.java
3684
/** * 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.camel.converter.dozer; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.TypeConversionException; import org.apache.camel.TypeConverter; import org.apache.camel.support.TypeConverterSupport; import org.dozer.DozerBeanMapper; import org.dozer.Mapper; import org.dozer.metadata.ClassMappingMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <code>DozerTypeConverter</code> is a standard {@link TypeConverter} that * delegates to a {@link Mapper} from the Dozer framework to convert between * types. <code>DozerTypeConverter</code>s are created and installed into a * {@link CamelContext} by an instance of {@link DozerTypeConverterLoader}. * <p> * See <a href="http://dozer.sourceforge.net">dozer project page</a> or more information on configuring Dozer * * @see DozerTypeConverterLoader */ public class DozerTypeConverter extends TypeConverterSupport { private static final Logger LOG = LoggerFactory.getLogger(DozerTypeConverter.class); private final DozerBeanMapper mapper; public DozerTypeConverter(DozerBeanMapper mapper) { this.mapper = mapper; } public DozerBeanMapper getMapper() { return mapper; } @Override public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException { // find the map id, so we can provide that when trying to map from source to destination String mapId = null; if (value != null) { Class<?> sourceType = value.getClass(); Class<?> destType = type; ClassMappingMetadata metadata = mapper.getMappingMetadata().getClassMapping(sourceType, destType); if (metadata != null) { mapId = metadata.getMapId(); } } // if the exchange is null, we have no chance to ensure that the TCCL is the one from the CamelContext if (exchange == null) { return mapper.map(value, type, mapId); } T answer = null; ClassLoader prev = Thread.currentThread().getContextClassLoader(); ClassLoader contextCl = exchange.getContext().getApplicationContextClassLoader(); if (contextCl != null) { // otherwise, we ensure that the TCCL is the correct one LOG.debug("Switching TCCL to: {}.", contextCl); try { Thread.currentThread().setContextClassLoader(contextCl); answer = mapper.map(value, type, mapId); } finally { LOG.debug("Restored TCCL to: {}.", prev); Thread.currentThread().setContextClassLoader(prev); } } else { // just try with the current TCCL as-is answer = mapper.map(value, type, mapId); } return answer; } }
apache-2.0
powerunit/powerunit-eclipse
powerunit-eclipse-plugin/src/main/java/ch/powerunit/poweruniteclipse/helper/TestFragmentSearch.java
4478
package ch.powerunit.poweruniteclipse.helper; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.debug.ui.ILaunchConfigurationDialog; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchMatch; import org.eclipse.jdt.core.search.SearchParticipant; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.core.search.SearchRequestor; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.Display; import ch.powerunit.poweruniteclipse.Messages; public final class TestFragmentSearch { private TestFragmentSearch() { } public static IPackageFragment[] searchPackageFragmentFromProject( IRunnableContext context, IJavaProject project) throws InvocationTargetException, InterruptedException { IJavaElement[] elements = null; if ((project == null) || !project.exists()) { IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace() .getRoot()); if (model != null) { try { elements = model.getJavaProjects(); } catch (JavaModelException e) { // TODO } } } else { elements = new IJavaElement[] { project }; } if (elements == null) { elements = new IJavaElement[] {}; } int constraints = IJavaSearchScope.SOURCES; IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope( elements, constraints); return TestFragmentSearch.searchFragmentClazz(context, searchScope); } public static IPackageFragment[] searchFragmentClazz( IRunnableContext context, final IJavaSearchScope scope) throws InvocationTargetException, InterruptedException { final IPackageFragment[][] res = new IPackageFragment[1][]; IRunnableWithProgress runnable = new IRunnableWithProgress() { @Override public void run(IProgressMonitor pm) throws InvocationTargetException { res[0] = searchFragment(pm, scope); } }; Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { context.run(true, true, runnable); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); return res[0]; } public static IPackageFragment[] searchFragment(IProgressMonitor pm, IJavaSearchScope scope) { pm.beginTask(Messages.PowerUnitLaunchTabFragment_2, 100); int searchTicks = 100; SearchPattern pattern = SearchPattern .createPattern( "*", IJavaSearchConstants.PACKAGE, IJavaSearchConstants.ALL_OCCURRENCES, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); //$NON-NLS-1$ SearchParticipant[] participants = new SearchParticipant[] { SearchEngine .getDefaultSearchParticipant() }; PackageCollector collector = new PackageCollector(); IProgressMonitor searchMonitor = new SubProgressMonitor(pm, searchTicks); try { new SearchEngine().search(pattern, participants, scope, collector, searchMonitor); } catch (CoreException ce) { // TODO } List<IPackageFragment> result = collector.getResult(); return result.toArray(new IPackageFragment[result.size()]); } private static class PackageCollector extends SearchRequestor { private List<IPackageFragment> fResult; public PackageCollector() { fResult = new ArrayList<IPackageFragment>(200); } public List<IPackageFragment> getResult() { return fResult; } @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { Object enclosingElement = match.getElement(); if (enclosingElement instanceof IPackageFragment) { // defensive // code fResult.add((IPackageFragment) enclosingElement); } } } }
apache-2.0
alancnet/artifactory
storage/db/src/main/java/org/artifactory/storage/db/aql/parser/elements/high/level/basic/language/ArchiveDomainsElement.java
1593
package org.artifactory.storage.db.aql.parser.elements.high.level.basic.language; import com.google.common.collect.Lists; import org.artifactory.aql.model.AqlDomainEnum; import org.artifactory.storage.db.aql.parser.elements.ParserElement; import org.artifactory.storage.db.aql.parser.elements.low.level.InternalNameElement; import org.artifactory.storage.db.aql.parser.elements.low.level.LazyParserElement; import java.util.List; import static org.artifactory.aql.model.AqlDomainEnum.archives; import static org.artifactory.aql.model.AqlDomainEnum.items; import static org.artifactory.storage.db.aql.parser.AqlParser.dot; import static org.artifactory.storage.db.aql.parser.AqlParser.itemDomains; /** * @author Gidi Shabat */ public class ArchiveDomainsElement extends LazyParserElement implements DomainProviderElement { @Override protected ParserElement init() { List<ParserElement> list = Lists.newArrayList(); fillWithDomains(list); fillWithSubDomains(list); return fork(list.toArray(new ParserElement[list.size()])); } private void fillWithDomains(List<ParserElement> list) { list.add(new IncludeDomainElement(archives)); } private void fillWithSubDomains(List<ParserElement> list) { list.add(forward(new InternalNameElement(items.signatue), fork(new EmptyIncludeDomainElement(items), forward(dot, itemDomains)))); } @Override public boolean isVisibleInResult() { return true; } @Override public AqlDomainEnum getDomain() { return archives; } }
apache-2.0
welterde/ewok
com/planet_ink/coffee_mud/WebMacros/CatalogItemNext.java
6913
package com.planet_ink.coffee_mud.WebMacros; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2010 Bo Zimmerman 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. */ @SuppressWarnings("unchecked") public class CatalogItemNext extends StdWebMacro { public String name(){return this.getClass().getName().substring(this.getClass().getName().lastIndexOf('.')+1);} public boolean isAdminMacro() {return true;} static final String[] DATA={ "CATALOG_ITEM_NAME", "CATALOG_ITEM_USAGE", "CATALOG_ITEM_LEVEL", "CATALOG_ITEM_CLASS", "CATALOG_ITEM_VALUE", "CATALOG_ITEM_RATE", "CATALOG_ITEM_MASK", "CATALOG_ITEM_LIVE", "CATALOG_ITEM_AREA", }; public static String getCataStat(Item I, CatalogLibrary.CataData data, int x, String optionalColumn) { if((I==null)||(data==null)) return ""; boolean dataRate=(data.getRate()>0.0); switch(x) { case 0: return I.Name(); case 1: return ""+data.numReferences(); case 2: return ""+I.baseEnvStats().level(); case 3: return I.ID(); case 4: return ""+I.baseGoldValue(); case 5: return (dataRate)?CMath.toPct(data.getRate()):""; case 6: return (dataRate)?(data.getMaskStr()==null?"":data.getMaskStr()):""; case 7: return (dataRate)?(""+data.getWhenLive()):""; case 8: return ""+data.mostPopularArea(); default: if((optionalColumn!=null)&&(optionalColumn.length()>0)) { if(I.isStat(optionalColumn)) return I.getStat(optionalColumn); if(I.baseEnvStats().isStat(optionalColumn)) return I.baseEnvStats().getStat(optionalColumn); } break; } return ""; } public String runMacro(ExternalHTTPRequests httpReq, String parm) { Hashtable parms=parseParms(parm); String last=httpReq.getRequestParameter("ITEM"); String optCol=httpReq.getRequestParameter("OPTIONALCOLUMN"); final String optionalColumn; if(optCol==null) optionalColumn=""; else optionalColumn=optCol.trim().toUpperCase(); if(parms.containsKey("RESET")) { if(last!=null) httpReq.removeRequestParameter("ITEM"); for(int d=0;d<DATA.length;d++) httpReq.removeRequestParameter(DATA[d]); if(optionalColumn.length()>0) httpReq.removeRequestParameter("CATALOG_ITEM_"+optionalColumn); return ""; } String lastID=""; Item I=null; String name=null; CatalogLibrary.CataData data=null; String[] names=CMLib.catalog().getCatalogItemNames(); String sortBy=httpReq.getRequestParameter("SORTBY"); if((sortBy!=null)&&(sortBy.length()>0)) { String[] sortedNames=(String[])httpReq.getRequestObjects().get("CATALOG_ITEM_"+sortBy.toUpperCase()); if(sortedNames!=null) names=sortedNames; else { final int sortIndex=CMParms.indexOf(DATA, "CATALOG_ITEM_"+sortBy.toUpperCase()); if((sortIndex>=0)||(sortBy.equalsIgnoreCase(optionalColumn))) { Object[] sortifiable=new Object[names.length]; for(int s=0;s<names.length;s++) sortifiable[s]=new Object[]{ names[s], CMLib.catalog().getCatalogItem(names[s]), CMLib.catalog().getCatalogItemData(names[s])}; Arrays.sort(sortifiable,new Comparator() { public int compare(Object o1, Object o2) { Object[] O1=(Object[])o1; Object[] O2=(Object[])o2; String s1=getCataStat((Item)O1[1],(CatalogLibrary.CataData)O1[2],sortIndex, optionalColumn); String s2=getCataStat((Item)O2[1],(CatalogLibrary.CataData)O2[2],sortIndex, optionalColumn); if(CMath.isNumber(s1)&&CMath.isNumber(s2)) return Double.valueOf(CMath.s_double(s1)).compareTo(Double.valueOf(CMath.s_double(s2))); else return s1.toLowerCase().compareTo(s2.toLowerCase()); } }); for(int s=0;s<names.length;s++) names[s]=(String)((Object[])sortifiable[s])[0]; httpReq.getRequestObjects().put("CATALOG_ITEM_"+sortBy.toUpperCase(),names); } } } for(int s=0;s<names.length;s++) { name="CATALOG-"+names[s].toUpperCase().trim(); if((last==null)||((last.length()>0)&&(last.equals(lastID))&&(!name.equalsIgnoreCase(lastID)))) { data=CMLib.catalog().getCatalogItemData(names[s]); I=CMLib.catalog().getCatalogItem(names[s]); if(I==null) continue; httpReq.addRequestParameters("ITEM",name); for(int d=0;d<DATA.length;d++) httpReq.addRequestParameters(DATA[d],getCataStat(I,data,d,null)); if(optionalColumn.length()>0) httpReq.addRequestParameters("CATALOG_ITEM_"+optionalColumn,getCataStat(I,data,-1,optionalColumn)); return ""; } lastID=name; } httpReq.addRequestParameters("ITEM",""); for(int d=0;d<DATA.length;d++) httpReq.addRequestParameters(DATA[d],""); if(optionalColumn.length()>0) httpReq.addRequestParameters("CATALOG_ITEM_"+optionalColumn,""); if(parms.containsKey("EMPTYOK")) return "<!--EMPTY-->"; return " @break@"; } }
apache-2.0
pdalbora/gosu-lang
gosu-test-api/src/main/java/gw/test/TestClassHelper.java
4963
/* * Copyright 2014 Guidewire Software, Inc. */ package gw.test; import gw.util.StreamUtil; import junit.framework.Test; import junit.framework.TestCase; import org.apache.bcel.classfile.ClassParser; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.LineNumberTable; import org.apache.bcel.classfile.Method; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Helper methods for analyzing methods, and instantiating test classes. */ public class TestClassHelper { private static final Map<Class<?>, List<Method>> cache = new ConcurrentHashMap<Class<?>, List<Method>>(); /** * Returns list of methods according to their order in the source file. * <p/> * Supertype methods go first in the list. * <p/> * Returns empty list if cannot find class file for the specified class. Class file is retrieved by * using {@link Class#getResourceAsStream} so it won't work for classes generated at runtine. * * @param clazz class to analyze * @return list of method names */ @SuppressWarnings("unchecked") public static <T extends TestCase> List<Method> getMethodsSorted(Class<T> clazz) { List<Method> allMethods = cache.get(clazz); if (allMethods != null) { return allMethods; } JavaClass javaClass = parseClass(clazz); if (javaClass == null) { return Collections.emptyList(); } List<Method> currentClassMethods = Arrays.asList(javaClass.getMethods()); Collections.sort(currentClassMethods, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { return getMethodLineNumber(o1).compareTo(getMethodLineNumber(o2)); } }); allMethods = new ArrayList<Method>(); // add method of super class first Class<? super T> superclass = clazz.getSuperclass(); if (superclass != null && !superclass.getClass().equals(TestCase.class)) { allMethods.addAll(getMethodsSorted((Class<? extends TestCase>) superclass)); } allMethods.addAll(currentClassMethods); cache.put(clazz, Collections.unmodifiableList(new ArrayList<Method>(allMethods))); return allMethods; } private static JavaClass parseClass(Class<?> clazz) { String pathToClassFile = "/" + clazz.getName().replace('.', '/') + ".class"; InputStream resourceAsStream = clazz.getResourceAsStream(pathToClassFile); if (resourceAsStream == null) { return null; } try { return new ClassParser(resourceAsStream, pathToClassFile).parse(); } catch (IOException e) { throw new RuntimeException("Error during analyzing byte code of the class " + clazz.getName(), e); } finally { StreamUtil.closeNoThrow(resourceAsStream); } } private static Integer getMethodLineNumber(Method method) { LineNumberTable lineNumberTable = method.getLineNumberTable(); return lineNumberTable == null ? -1 : lineNumberTable.getLineNumberTable()[0].getLineNumber(); } public static <T extends TestCase> Test createTestSuite(Class<T> clazz, Iterable<String> methodNames) { try { Constructor<T> constructor = getConstructor(clazz); junit.framework.TestSuite newSuite = new junit.framework.TestSuite(); for (String name : methodNames) { TestCase test; if (constructor.getParameterTypes().length == 0) { test = constructor.newInstance(); test.setName(name); } else { test = constructor.newInstance(name); } newSuite.addTest(test); } return newSuite; } catch (InstantiationException e) { throw new RuntimeException("Cannot instantiate test class " + clazz.getName(), e); } catch (IllegalAccessException e) { throw new RuntimeException(clazz.getName() + " constructor is not accessible", e); } catch (InvocationTargetException e) { throw new RuntimeException(clazz.getName() + "(String name) constructor threw an exception", e); } } private static <T extends TestCase> Constructor<T> getConstructor(Class<T> clazz) { try { Constructor<T> constructor = clazz.getConstructor(String.class); if (Modifier.isPublic(constructor.getModifiers())) { return constructor; } } catch (NoSuchMethodException e) { } try { Constructor<T> constructor = clazz.getConstructor(); if (Modifier.isPublic(constructor.getModifiers())) { return constructor; } } catch (NoSuchMethodException e) { } throw new RuntimeException("Did not find public " + clazz.getName() + "(String name) or " + clazz.getName() + "() constructor"); } }
apache-2.0
gosu-lang/old-gosu-repo
gosu-xml/src/main/java/gw/internal/schema/gw/xsd/w3c/xmlschema/anonymous/attributes/Import_Namespace.java
2298
package gw.internal.schema.gw.xsd.w3c.xmlschema.anonymous.attributes; /***************************************************************************/ /* THIS IS AUTOGENERATED CODE - DO NOT MODIFY OR YOUR CHANGES WILL BE LOST */ /* THIS CODE CAN BE REGENERATED USING 'xsd-codegen' */ /***************************************************************************/ public class Import_Namespace implements gw.internal.xml.IXmlGeneratedClass { public static final javax.xml.namespace.QName $QNAME = new javax.xml.namespace.QName( "", "namespace", "" ); public static final gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType> TYPE = new gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType>( gw.lang.reflect.TypeSystem.getGlobalLock() ) { @Override protected gw.lang.reflect.IType init() { return gw.lang.reflect.TypeSystem.getByFullName( "gw.xsd.w3c.xmlschema.anonymous.attributes.Import_Namespace" ); } }; private Import_Namespace() { } public static gw.xml.XmlSimpleValue createSimpleValue( java.net.URI value ) { //noinspection RedundantArrayCreation return (gw.xml.XmlSimpleValue) TYPE.get().getTypeInfo().getMethod( "createSimpleValue", gw.lang.reflect.TypeSystem.get( java.net.URI.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { value } ); } public static void set( gw.internal.schema.gw.xsd.w3c.xmlschema.types.complex.AnyType anyType, java.net.URI value ) { //noinspection RedundantArrayCreation TYPE.get().getTypeInfo().getMethod( "set", gw.lang.reflect.TypeSystem.get( gw.internal.schema.gw.xsd.w3c.xmlschema.types.complex.AnyType.class ), gw.lang.reflect.TypeSystem.get( java.net.URI.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { anyType, value } ); } public static void set( gw.xml.XmlElement element, java.net.URI value ) { //noinspection RedundantArrayCreation TYPE.get().getTypeInfo().getMethod( "set", gw.lang.reflect.TypeSystem.get( gw.xml.XmlElement.class ), gw.lang.reflect.TypeSystem.get( java.net.URI.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { element, value } ); } @SuppressWarnings( {"UnusedDeclaration"} ) private static final long FINGERPRINT = -3788403261967307401L; }
apache-2.0
bigboxer23/PiGarage
src/main/java/com/jones/matt/services/GarageDoorActionService.java
1742
package com.jones.matt.services; import com.jones.matt.GarageDoorController; import com.jones.matt.util.GPIOUtils; import com.pi4j.io.gpio.*; import java.util.logging.Logger; /** * Service to open or close the garage door by interfacing with Raspberry Pi's GPIO and * a relay wired to the door opener */ public class GarageDoorActionService extends BaseService { private GpioPinDigitalOutput myPinTrigger; /** * Pin to use for triggering actions */ private static final Pin kActionPin = GPIOUtils.getPin(Integer.getInteger("GPIO.action.pin", 7)); /** * The delay between the "press" and the "let go" */ public static final int kTriggerDelay = Integer.getInteger("triggerDelay", 400); public GarageDoorActionService(GarageDoorController theController) { super(theController); myPinTrigger = GpioFactory.getInstance().provisionDigitalOutputPin(kActionPin, "MyActionPin", PinState.HIGH); } /** * Close the door if it is open */ public void closeDoor() { if(getController().getStatusService().isGarageDoorOpen()) { myLogger.config("Closing the door."); doDoorAction(); getController().getCommunicationService().garageDoorClosed(); } } /** * Open the door if it is already closed */ public void openDoor() { if(!getController().getStatusService().isGarageDoorOpen()) { myLogger.config("Opening the door."); doDoorAction(); getController().getCommunicationService().garageDoorOpened(); } } /** * Trigger the opener to toggle the current state. There * is no status check with this method. */ private void doDoorAction() { myPinTrigger.low(); try { Thread.sleep(kTriggerDelay); } catch (InterruptedException e){} myPinTrigger.high(); } }
apache-2.0
KarloKnezevic/Ferko
src/java/hr/fer/zemris/jcms/web/actions/data/ShowGroupTree2Data.java
2020
package hr.fer.zemris.jcms.web.actions.data; import java.util.List; import hr.fer.zemris.jcms.model.Group; import hr.fer.zemris.jcms.security.GroupSupportedPermission; import hr.fer.zemris.jcms.web.actions.data.support.IMessageLogger; import hr.fer.zemris.util.Tree; public class ShowGroupTree2Data extends BaseCourseInstance { private Group parent; private String courseInstanceID; private Tree<Group, GroupSupportedPermission> accessibleGroupsTree; private List<Group> privateGroups; private String treeAsJSON; private Long parentID; private boolean allowMultipleAddition; private String text; public ShowGroupTree2Data(IMessageLogger messageLogger) { super(messageLogger); } public String getText() { return text; } public void setText(String text) { this.text = text; } public Long getParentID() { return parentID; } public void setParentID(Long parentID) { this.parentID = parentID; } public boolean getAllowMultipleAddition() { return allowMultipleAddition; } public void setAllowMultipleAddition(boolean allowMultipleAddition) { this.allowMultipleAddition = allowMultipleAddition; } public Group getParent() { return parent; } public void setParent(Group parent) { this.parent = parent; } public Tree<Group, GroupSupportedPermission> getAccessibleGroupsTree() { return accessibleGroupsTree; } public void setAccessibleGroupsTree(Tree<Group, GroupSupportedPermission> accessibleGroupsTree) { this.accessibleGroupsTree = accessibleGroupsTree; } public List<Group> getPrivateGroups() { return privateGroups; } public void setPrivateGroups(List<Group> privateGroups) { this.privateGroups = privateGroups; } public String getCourseInstanceID() { return courseInstanceID; } public void setCourseInstanceID(String courseInstanceID) { this.courseInstanceID = courseInstanceID; } public String getTreeAsJSON() { return treeAsJSON; } public void setTreeAsJSON(String treeAsJSON) { this.treeAsJSON = treeAsJSON; } }
apache-2.0
hairlun/radix-android
src/com/yuntongxun/ecdemo/ui/interphone/InterPhoneBannerView.java
2586
package com.yuntongxun.ecdemo.ui.interphone; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.patr.radix.R; /** * 实时对讲状态通知显示 * com.yuntongxun.ecdemo.ui.interphone in ECDemo_Android * Created by Jorstin on 2015/7/16. */ public class InterPhoneBannerView extends LinearLayout { /**实时对讲状态通知显示*/ private TextView mTipsView; /**实时对讲在线人数/总人数*/ private TextView mCountView; /**实时对讲图标*/ private ImageView mPersonView; /**实时对讲参与总数*/ private int mCount; /**实时对讲在线总数*/ private int mOnlineCount; public InterPhoneBannerView(Context context) { this(context, null); } public InterPhoneBannerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public InterPhoneBannerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs); initBannerView(); } private void initBannerView() { View.inflate(getContext(), R.layout.ec_inter_phone_banner, this); mTipsView = (TextView) findViewById(R.id.notice_tips); mCountView = (TextView) findViewById(R.id.count_tv); mPersonView = (ImageView) findViewById(R.id.ic_person); } /** * 设置参与实时对讲人数 * @param count 参与实时对讲人数 */ public void setCount(int count) { if(count < 0) { count = 0; } mCount = count; invalidateCountView(); } /** * 设置当前在线总数 * @param onlineCount 在线总数 */ public void setOnlineCount(int onlineCount) { if(onlineCount < 0) { onlineCount = 0; } mOnlineCount = onlineCount; invalidateCountView(); } /** * 设置实时对讲状态 * @param id */ public void setTips(int id) { if(id > 0) { setTips(getResources().getString(id)); } } /** * 设置实时对讲状态 * @param text */ public void setTips(String text) { mTipsView.setText(text); } /** * 设置界面显示人数对比 */ private void invalidateCountView() { mCountView.setText(mOnlineCount + "/" + mCount); } public void setOnLineCount(int online,int all){ mCountView.setText(online + "/" + all); } }
apache-2.0
NickAndroid/sinaBlog
2014/librarys/lv_anmi_library/src/com/haarman/listviewanimations/itemmanipulation/contextualundo/ContextualUndoAdapter.java
8060
/* * Copyright 2013 Frankie Sardo * Copyright 2013 Niek Haarman * * 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.haarman.listviewanimations.itemmanipulation.contextualundo; import static com.nineoldandroids.view.ViewHelper.setAlpha; import static com.nineoldandroids.view.ViewHelper.setTranslationX; import static com.nineoldandroids.view.ViewPropertyAnimator.animate; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ListView; import com.haarman.listviewanimations.BaseAdapterDecorator; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import com.nineoldandroids.animation.ValueAnimator; import com.nineoldandroids.view.ViewHelper; /** * Warning: a stable id for each item in the adapter is required. The decorated * adapter should not try to cast convertView to a particular view. The * undoLayout should have the same height as the content row. */ public class ContextualUndoAdapter extends BaseAdapterDecorator implements ContextualUndoListViewTouchListener.Callback { private final int mUndoLayoutId; private final int mUndoActionId; private final int mAnimationTime = 150; private ContextualUndoView mCurrentRemovedView; private long mCurrentRemovedId; private Map<View, Animator> mActiveAnimators = new ConcurrentHashMap<View, Animator>(); private DeleteItemCallback mDeleteItemCallback; public ContextualUndoAdapter(BaseAdapter baseAdapter, int undoLayoutId, int undoActionId) { super(baseAdapter); mUndoLayoutId = undoLayoutId; mUndoActionId = undoActionId; mCurrentRemovedId = -1; } @Override public final View getView(int position, View convertView, ViewGroup parent) { ContextualUndoView contextualUndoView = (ContextualUndoView) convertView; if (contextualUndoView == null) { contextualUndoView = new ContextualUndoView(parent.getContext(), mUndoLayoutId); contextualUndoView.findViewById(mUndoActionId).setOnClickListener(new UndoListener(contextualUndoView)); convertView = contextualUndoView; } View contentView = super.getView(position, contextualUndoView.getContentView(), parent); contextualUndoView.updateContentView(contentView); long itemId = getItemId(position); if (itemId == mCurrentRemovedId) { contextualUndoView.displayUndo(); mCurrentRemovedView = contextualUndoView; } else { contextualUndoView.displayContentView(); } contextualUndoView.setItemId(itemId); return contextualUndoView; } @Override public void setListView(ListView listView) { super.setListView(listView); ContextualUndoListViewTouchListener contextualUndoListViewTouchListener = new ContextualUndoListViewTouchListener(listView, this); listView.setOnTouchListener(contextualUndoListViewTouchListener); listView.setOnScrollListener(contextualUndoListViewTouchListener.makeScrollListener()); listView.setRecyclerListener(new RecycleViewListener()); } @Override public void onViewSwiped(View dismissView, int dismissPosition) { ContextualUndoView contextualUndoView = (ContextualUndoView) dismissView; if (contextualUndoView.isContentDisplayed()) { restoreViewPosition(contextualUndoView); contextualUndoView.displayUndo(); removePreviousContextualUndoIfPresent(); setCurrentRemovedView(contextualUndoView); } else { if (mCurrentRemovedView != null) { performRemoval(); } } } private void restoreViewPosition(View view) { setAlpha(view, 1f); setTranslationX(view, 0); } private void removePreviousContextualUndoIfPresent() { if (mCurrentRemovedView != null) { performRemoval(); } } private void setCurrentRemovedView(ContextualUndoView currentRemovedView) { mCurrentRemovedView = currentRemovedView; mCurrentRemovedId = currentRemovedView.getItemId(); } private void clearCurrentRemovedView() { mCurrentRemovedView = null; mCurrentRemovedId = -1; } @Override public void onListScrolled() { if (mCurrentRemovedView != null) { performRemoval(); } } private void performRemoval() { ValueAnimator animator = ValueAnimator.ofInt(mCurrentRemovedView.getHeight(), 1).setDuration(mAnimationTime); animator.addListener(new RemoveViewAnimatorListenerAdapter(mCurrentRemovedView)); animator.addUpdateListener(new RemoveViewAnimatorUpdateListener(mCurrentRemovedView)); animator.start(); mActiveAnimators.put(mCurrentRemovedView, animator); clearCurrentRemovedView(); } public void setDeleteItemCallback(DeleteItemCallback deleteItemCallback) { mDeleteItemCallback = deleteItemCallback; } public Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); bundle.putLong("mCurrentRemovedId", mCurrentRemovedId); return bundle; } public void onRestoreInstanceState(Parcelable state) { Bundle bundle = (Bundle) state; mCurrentRemovedId = bundle.getLong("mCurrentRemovedId", -1); } public interface DeleteItemCallback { public void deleteItem(int position); } private class RemoveViewAnimatorListenerAdapter extends AnimatorListenerAdapter { private final View mDismissView; private final int mOriginalHeight; public RemoveViewAnimatorListenerAdapter(View dismissView) { mDismissView = dismissView; mOriginalHeight = dismissView.getHeight(); } @Override public void onAnimationEnd(Animator animation) { mActiveAnimators.remove(mDismissView); restoreViewPosition(mDismissView); restoreViewDimension(mDismissView); deleteCurrentItem(); } private void restoreViewDimension(View view) { ViewGroup.LayoutParams lp; lp = view.getLayoutParams(); lp.height = mOriginalHeight; view.setLayoutParams(lp); } private void deleteCurrentItem() { ContextualUndoView contextualUndoView = (ContextualUndoView) mDismissView; int position = getListView().getPositionForView(contextualUndoView); mDeleteItemCallback.deleteItem(position); } } private class RemoveViewAnimatorUpdateListener implements ValueAnimator.AnimatorUpdateListener { private final View mDismissView; private final ViewGroup.LayoutParams mLayoutParams; public RemoveViewAnimatorUpdateListener(View dismissView) { mDismissView = dismissView; mLayoutParams = dismissView.getLayoutParams(); } @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { mLayoutParams.height = (Integer) valueAnimator.getAnimatedValue(); mDismissView.setLayoutParams(mLayoutParams); } }; private class UndoListener implements View.OnClickListener { private final ContextualUndoView mContextualUndoView; public UndoListener(ContextualUndoView contextualUndoView) { mContextualUndoView = contextualUndoView; } @Override public void onClick(View v) { clearCurrentRemovedView(); mContextualUndoView.displayContentView(); moveViewOffScreen(); animateViewComingBack(); } private void moveViewOffScreen() { ViewHelper.setTranslationX(mContextualUndoView, mContextualUndoView.getWidth()); } private void animateViewComingBack() { animate(mContextualUndoView).translationX(0).setDuration(mAnimationTime).setListener(null); } } private class RecycleViewListener implements AbsListView.RecyclerListener { @Override public void onMovedToScrapHeap(View view) { Animator animator = mActiveAnimators.get(view); if (animator != null) { animator.cancel(); } } } }
apache-2.0
pcordemans/AlgorithmsWIP2017
src/algorithms/tree/TestFileSystem.java
1182
package algorithms.tree; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; public class TestFileSystem { @Before public void setUp() throws Exception { } @Test public void testMkdir() { FileSystem myFS = new FileSystem(); myFS.mkdir("user"); ArrayList<FSElement> result = new ArrayList<FSElement>(); result.add(new Directory("user")); assertEquals(result, myFS.dir()); } @Test public void testCD(){ FileSystem myFS = new FileSystem(); myFS.mkdir("user"); myFS.cd("user"); myFS.mkdir("name"); myFS.createFile("test", 5); myFS.cd("name"); ArrayList<FSElement> result = new ArrayList<FSElement>(); assertEquals(result, myFS.dir()); myFS.cd(".."); result.add(new Directory("name")); result.add(new File("test", 5)); assertEquals(result, myFS.dir()); } @Test public void testSize(){ FileSystem myFS = new FileSystem(); myFS.mkdir("user"); myFS.cd("user"); myFS.mkdir("name"); myFS.createFile("test", 5); myFS.cd("name"); assertEquals(1, myFS.size()); myFS.cd(".."); assertEquals(7, myFS.size()); myFS.cd(".."); assertEquals(8, myFS.size()); } }
apache-2.0
Haixing-Hu/commons
src/main/java/com/github/haixing_hu/text/BooleanFormat.java
7391
/* * Copyright (c) 2014 Haixing Hu * * 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.github.haixing_hu.text; import com.github.haixing_hu.lang.CharSequenceUtils; import com.github.haixing_hu.lang.Cloneable; import com.github.haixing_hu.lang.Hash; import com.github.haixing_hu.text.tostring.ToStringBuilder; import static com.github.haixing_hu.lang.Argument.*; import static com.github.haixing_hu.text.ErrorCode.EMPTY_VALUE; /** * The {@link NumberFormat} is used to parse and format boolean values. * * @author Haixing Hu */ public final class BooleanFormat implements Cloneable<BooleanFormat> { private BooleanFormatSymbols symbols; private BooleanFormatOptions options; private final transient ParsingPosition position; private final transient StringBuilder builder; public BooleanFormat() { symbols = new BooleanFormatSymbols(); options = new BooleanFormatOptions(); position = new ParsingPosition(); builder = new StringBuilder(); } public void reset() { symbols.reset(); options.reset(); position.reset(); } public BooleanFormatSymbols getSymbols() { return symbols; } public void setSymbols(final BooleanFormatSymbols symbols) { this.symbols = requireNonNull("symbols", symbols); } public BooleanFormatOptions getOptions() { return options; } public void setOptions(final BooleanFormatOptions options) { this.options = requireNonNull("options", options); } public ParsingPosition getParsePosition() { return position; } public int getParseIndex() { return position.getIndex(); } public int getErrorIndex() { return position.getErrorIndex(); } public int getErrorCode() { return position.getErrorCode(); } public boolean success() { return position.success(); } public boolean fail() { return position.fail(); } /** * Parses a {@code boolean} value. * * @param str * the text segment to be parsed. The parsing starts from the * character at the index {@code 0} and stops at the character * before the index {@code str.length()}. * @return the parsed value. */ public boolean parse(final CharSequence str) { return parse(str, 0, str.length()); } /** * Parses a {@code boolean} value. * * @param str * the text segment to be parsed. The parsing starts from the * character at the index {@code startIndex} and stops at the * character before the index {@code str.length()}. * @param startIndex * the index where to start parsing. * @return the parsed value. */ public boolean parse(final CharSequence str, final int startIndex) { return parse(str, startIndex, str.length()); } /** * Parses a {@code boolean} value. * * @param str * the text segment to be parsed. The parsing starts from the * character at the index {@code startIndex} and stops at the * character before the index {@code endIndex}. * @param startIndex * the index where to start parsing. * @param endIndex * the index where to end parsing. * @return the parsed value. */ public boolean parse(final CharSequence str, final int startIndex, final int endIndex) { // check the index bounds requireIndexInCloseRange(startIndex, 0, str.length()); requireIndexInCloseRange(startIndex, 0, str.length()); // reset the parse position position.reset(startIndex); // skip the leading white space if necessary if (! options.isKeepBlank()) { ParseUtils.skipBlanks(position, str, endIndex); if (position.fail()) { return false; } } final int index = position.getIndex(); if (index >= endIndex) { position.setErrorCode(EMPTY_VALUE); position.setErrorIndex(index); return false; } final char[] binaryDigits = symbols.getBinaryDigits(); final String trueName = symbols.getTrueName(); final String falseName = symbols.getFalseName(); final char ch = str.charAt(index); if (ch == binaryDigits[0]) { position.setIndex(index + 1); return false; } else if (ch == binaryDigits[1]) { position.setIndex(index + 1); return true; } else if (CharSequenceUtils.startsWithIgnoreCase(str, index, endIndex, trueName)) { position.setIndex(index + trueName.length()); return true; } else if (CharSequenceUtils.startsWithIgnoreCase(str, index, endIndex, falseName)) { position.setIndex(index + falseName.length()); return false; } else { position.setErrorCode(EMPTY_VALUE); position.setErrorIndex(index); return false; } } /** * Formats a {@code boolean} value. * * @param value * the value to be formated. * @return the formatted result. */ public String format(final boolean value) { builder.setLength(0); format(value, builder); return builder.toString(); } /** * Formats a {@code boolean} value. * * @param value * the value to be formated. * @param output * the {@link StringBuilder} where to append the formatted result. * @return the output {@link StringBuilder}. */ public StringBuilder format(final boolean value, final StringBuilder output) { if (options.isBoolAlpha()) { final String str = (value ? symbols.getTrueName() : symbols.getFalseName()); output.append(str); } else { final char[] digits = symbols.getBinaryDigits(); final char ch = (value ? digits[1] : digits[0]); output.append(ch); } return output; } @Override public BooleanFormat clone() { final BooleanFormat result = new BooleanFormat(); result.symbols.assign(this.symbols); result.options.assign(this.options); return result; } @Override public int hashCode() { final int multiplier = 17; int code = 2; code = Hash.combine(code, multiplier, symbols); code = Hash.combine(code, multiplier, options); code = Hash.combine(code, multiplier, position); return code; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BooleanFormat other = (BooleanFormat) obj; return symbols.equals(other.symbols) && options.equals(other.options) && position.equals(other.position); } @Override public String toString() { return new ToStringBuilder(this) .appendToString("symbols", symbols.toString()) .appendToString("options", options.toString()) .appendToString("position", position.toString()) .toString(); } }
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Features/Base/src/main/java/ghidra/app/util/bin/format/dwarf4/LEB128.java
9782
/* ### * IP: GHIDRA * * 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 ghidra.app.util.bin.format.dwarf4; import java.io.IOException; import ghidra.app.util.bin.BinaryReader; import ghidra.app.util.bin.ByteArrayProvider; /** * Class to hold result of reading a LEB128 value, along with size and position metadata. * <p> * Note: If a LEB128 value that would result in a native value longer than 64bits is attempted to * be read, an {@link IOException} will be thrown, and the stream's position will be left at the last read byte. * <p> * If this was a valid (but overly large) LEB128, the caller's stream will be left still pointing to LEB data. * <p> */ public class LEB128 { private final long offset; private final long value; private final int byteLength; private LEB128(long offset, long value, int byteLength) { this.offset = offset; this.value = value; this.byteLength = byteLength; } /** * Returns the value as an unsigned int32. If the actual value * is outside the positive range of a java int (ie. 0.. {@link Integer#MAX_VALUE}), * an exception is thrown. * * @return int in the range of 0 to {@link Integer#MAX_VALUE} * @throws IOException if value is outside range */ public int asUInt32() throws IOException { ensureInt32u(value); return (int) value; } /** * Returns the value as an signed int32. If the actual value * is outside the range of a java int (ie. {@link Integer#MIN_VALUE}.. {@link Integer#MAX_VALUE}), * an exception is thrown. * * @return int in the range of {@link Integer#MIN_VALUE} to {@link Integer#MAX_VALUE} * @throws IOException if value is outside range */ public int asInt32() throws IOException { ensureInt32s(value); return (int) value; } /** * Returns the value as a 64bit primitive long. Interpreting the signed-ness of the * value will depend on the way the value was read (ie. if {@link #readSignedValue(BinaryReader)} * vs. {@link #readUnsignedValue(BinaryReader)} was used). * * @return long value. */ public long asLong() { return value; } /** * Returns the offset of the LEB128 value in the stream it was read from. * * @return stream offset of the LEB128 value */ public long getOffset() { return offset; } /** * Returns the number of bytes that were used to store the LEB128 value in the stream * it was read from. * * @return number of bytes used to store the read LEB128 value */ public int getLength() { return byteLength; } @Override public String toString() { return String.format("LEB128: value: %d, offset: %d, byteLength: %d", value, offset, byteLength); } /** * Reads a LEB128 value from the BinaryReader and returns a {@link LEB128} instance * that contains the value along with size and position metadata. * <p> * See {@link #readAsLong(BinaryReader, boolean)}. * * @param reader {@link BinaryReader} to read bytes from * @param isSigned true if the value is signed * @return a {@link LEB128} instance with the read LEB128 value with metadata * @throws IOException if an I/O error occurs or value is outside the range of a java * 64 bit int */ public static LEB128 readValue(BinaryReader reader, boolean isSigned) throws IOException { long offset = reader.getPointerIndex(); long value = LEB128.readAsLong(reader, isSigned); int size = (int) (reader.getPointerIndex() - offset); return new LEB128(offset, value, size); } /** * Reads an unsigned LEB128 value from the BinaryReader and returns a {@link LEB128} instance * that contains the value along with size and position metadata. * <p> * See {@link #readAsLong(BinaryReader, boolean)}. * * @param reader {@link BinaryReader} to read bytes from * @return a {@link LEB128} instance with the read LEB128 value with metadata * @throws IOException if an I/O error occurs or value is outside the range of a java * 64 bit int */ public static LEB128 readUnsignedValue(BinaryReader reader) throws IOException { return readValue(reader, false); } /** * Reads an signed LEB128 value from the BinaryReader and returns a {@link LEB128} instance * that contains the value along with size and position metadata. * <p> * See {@link #readAsLong(BinaryReader, boolean)}. * * @param reader {@link BinaryReader} to read bytes from * @return a {@link LEB128} instance with the read LEB128 value with metadata * @throws IOException if an I/O error occurs or value is outside the range of a java * 64 bit int */ public static LEB128 readSignedValue(BinaryReader reader) throws IOException { return readValue(reader, true); } /** * Reads a LEB128 signed number from the BinaryReader and returns it as a java 32 bit int. * <p> * If the value of the number can not fit in the int type, an {@link IOException} will * be thrown. * * @param reader {@link BinaryReader} to read bytes from * @return signed int32 value * @throws IOException if error reading bytes or value is outside the * range of a signed int32 */ public static int readAsInt32(BinaryReader reader) throws IOException { long tmp = readAsLong(reader, true); ensureInt32s(tmp); return (int) tmp; } /** * Reads a LEB128 unsigned number from the BinaryReader and returns it as a java 32 bit int. * <p> * If the value of the number can not fit in the positive range of the int type, * an {@link IOException} will be thrown. * * @param reader {@link BinaryReader} to read bytes from * @return unsigned int32 value 0..Integer.MAX_VALUE * @throws IOException if error reading bytes or value is outside the * positive range of a java 32 bit int (ie. 0..Integer.MAX_VALUE) */ public static int readAsUInt32(BinaryReader reader) throws IOException { long tmp = readAsLong(reader, false); ensureInt32u(tmp); return (int) tmp; } /** * Reads a LEB128 number from the BinaryReader and returns it as a java 64 bit long int. * <p> * Large unsigned integers that use all 64 bits are be returned in a java native * 'long' type, which is signed. It is up to the caller to treat the value as unsigned. * <p> * Large integers that use more than 64 bits will cause an IOException to be thrown. * <p> * @param reader {@link BinaryReader} to read bytes from * @param isSigned true if the value is signed * @return long integer value. Caller must treat it as unsigned if isSigned parameter was * set to false * @throws IOException if an I/O error occurs or value is outside the range of a java * 64 bit int */ public static long readAsLong(BinaryReader reader, boolean isSigned) throws IOException { int nextByte = 0; int shift = 0; long value = 0; while (true) { nextByte = reader.readNextUnsignedByte(); if (shift == 70 || (isSigned == false && shift == 63 && nextByte > 1)) { throw new IOException( "Unsupported LEB128 value, too large to fit in 64bit java long variable"); } // must cast to long before shifting otherwise shift values greater than 32 cause problems value |= ((long) (nextByte & 0x7F)) << shift; shift += 7; if ((nextByte & 0x80) == 0) { break; } } if ((isSigned) && (shift < Long.SIZE) && ((nextByte & 0x40) != 0)) { // 0x40 is the new 'high' sign bit since 0x80 is the continuation flag value |= (-1L << shift); } return value; } /** * Decodes a LEB128 number from a byte array and returns it as a long. * <p> * See {@link #readAsLong(BinaryReader, boolean)}. * * @param bytes the bytes representing the LEB128 number * @param isSigned true if the value is signed * @return long integer value. Caller must treat it as unsigned if isSigned parameter was * set to false * @throws IOException if error reading bytes or value is outside the * range of a java 64 bit int */ public static long decode(byte[] bytes, boolean isSigned) throws IOException { return decode(bytes, 0, isSigned); } /** * Decodes a LEB128 number from a byte array and returns it as a long. * <p> * See {@link #readAsLong(BinaryReader, boolean)}. * * @param bytes the bytes representing the LEB128 number * @param offset offset in byte array of where to start reading bytes * @param isSigned true if the value is signed * @return long integer value. Caller must treat it as unsigned if isSigned parameter was * set to false * @throws IOException if error reading bytes or value is outside the * range of a java 64 bit int */ public static long decode(byte[] bytes, int offset, boolean isSigned) throws IOException { ByteArrayProvider bap = new ByteArrayProvider(bytes); BinaryReader br = new BinaryReader(bap, true); br.setPointerIndex(offset); return readAsLong(br, isSigned); } private static void ensureInt32u(long value) throws IOException { if (value < 0 || value > Integer.MAX_VALUE) { throw new IOException("LEB128 value out of range for java 32 bit unsigned int: " + Long.toUnsignedString(value)); } } private static void ensureInt32s(long value) throws IOException { if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { throw new IOException( "LEB128 value out of range for java 32 bit signed int: " + Long.toString(value)); } } }
apache-2.0
PurelyApplied/geode
geode-lucene/src/main/java/org/apache/geode/cache/lucene/FlatFormatSerializer.java
5825
/* * 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.geode.cache.lucene; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.logging.log4j.Logger; import org.apache.lucene.document.Document; import org.apache.geode.cache.lucene.internal.repository.serializer.SerializerUtil; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.util.JavaWorkarounds; import org.apache.geode.pdx.PdxInstance; /** * A built-in {@link LuceneSerializer} to parse user's nested object into a flat format, i.e. a * single document. Each nested object will become a set of fields, with field name in format of * contacts.name, contacts.homepage.title. * * Here is a example of usage: * * User needs to explicitly setLuceneSerializer with an instance of this class, and specify nested * objects' indexed fields in following format: * * luceneService.createIndexFactory().setLuceneSerializer(new FlatFormatSerializer()) * .addField("name").addField("contacts.name").addField("contacts.email", new KeywordAnalyzer()) * .addField("contacts.address").addField("contacts.homepage.content") .create(INDEX_NAME, * REGION_NAME); * * Region region = createRegion(REGION_NAME, RegionShortcut.PARTITION); * * When querying, use the same dot-separated index field name, such as contacts.homepage.content * * LuceneQuery query = luceneService.createLuceneQueryFactory().create(INDEX_NAME, REGION_NAME, * "contacts.homepage.content:Hello*", "name"); * * results = query.findPages(); */ public class FlatFormatSerializer implements LuceneSerializer { private final ConcurrentMap<String, List<String>> tokenizedFieldCache = new ConcurrentHashMap<>(); private static final Logger logger = LogService.getLogger(); /** * Recursively serialize each indexed field's value into a field of lucene document. The field * name will be in the same format as its indexed, such as contacts.homepage.content * * @param index lucene index * @param value user object to be serialized into index */ @Override public Collection<Document> toDocuments(LuceneIndex index, Object value) { String[] fields = index.getFieldNames(); Document doc = new Document(); for (String indexedFieldName : fields) { List<String> tokenizedFields = tokenizeField(indexedFieldName); addFieldValue(doc, indexedFieldName, value, tokenizedFields); } if (logger.isDebugEnabled()) { logger.debug("FlatFormatSerializer.toDocuments: " + doc); } return Collections.singleton(doc); } private List<String> tokenizeField(String indexedFieldName) { List<String> tokenizedFields = JavaWorkarounds.computeIfAbsent(tokenizedFieldCache, indexedFieldName, field -> Arrays.asList(indexedFieldName.split("\\."))); return tokenizedFields; } private void addFieldValue(Document doc, String indexedFieldName, Object value, List<String> tokenizedFields) { String currentLevelField = tokenizedFields.get(0); Object fieldValue = getFieldValue(value, currentLevelField); if (fieldValue == null) { return; } if (fieldValue.getClass().isArray()) { for (int i = 0; i < Array.getLength(fieldValue); i++) { Object item = Array.get(fieldValue, i); addFieldValueForNonCollectionObject(doc, indexedFieldName, item, tokenizedFields); } } else if (fieldValue instanceof Collection) { Collection collection = (Collection) fieldValue; for (Object item : collection) { addFieldValueForNonCollectionObject(doc, indexedFieldName, item, tokenizedFields); } } else { addFieldValueForNonCollectionObject(doc, indexedFieldName, fieldValue, tokenizedFields); } } private void addFieldValueForNonCollectionObject(Document doc, String indexedFieldName, Object fieldValue, List<String> tokenizedFields) { if (tokenizedFields.size() == 1) { SerializerUtil.addField(doc, indexedFieldName, fieldValue); } else { addFieldValue(doc, indexedFieldName, fieldValue, tokenizedFields.subList(1, tokenizedFields.size())); } } private Object getFieldValue(Object value, String fieldName) { if (value instanceof PdxInstance) { PdxInstance pdx = (PdxInstance) value; Object fieldValue = null; if (pdx.hasField(fieldName)) { fieldValue = pdx.getField(fieldName); } return fieldValue; } else { Class<?> clazz = value.getClass(); if (fieldName.equals(LuceneService.REGION_VALUE_FIELD) && SerializerUtil.supportedPrimitiveTypes().contains(clazz)) { return value; } try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); return field.get(value); } catch (Exception e) { return null; } } } }
apache-2.0