text
stringlengths
7
1.01M
/* * Copyright 2017 Apereo * * 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.tle.core.legacy.migration; import com.dytech.devlib.PropBagEx; import com.tle.beans.Institution; import com.tle.beans.item.ItemId; import com.tle.common.Check; import com.tle.common.filesystem.FileSystemHelper; import com.tle.common.settings.annotation.Property; import com.tle.core.filesystem.ItemFile; import com.tle.core.guice.Bind; import com.tle.core.hibernate.impl.HibernateMigrationHelper; import com.tle.core.migration.AbstractHibernateSchemaMigration; import com.tle.core.migration.MigrationInfo; import com.tle.core.migration.MigrationResult; import com.tle.core.migration.MigrationStatusLog; import com.tle.core.migration.MigrationStatusLog.LogType; import com.tle.core.plugins.impl.PluginServiceImpl; import com.tle.core.services.FileSystemService; import com.tle.core.xml.service.XmlService; import java.io.Serializable; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import javax.inject.Inject; import javax.inject.Singleton; import javax.persistence.CascadeType; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.MapKey; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import org.hibernate.Query; import org.hibernate.annotations.AccessType; import org.hibernate.annotations.CollectionOfElements; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.Index; import org.hibernate.classic.Session; @Bind @Singleton @SuppressWarnings("nls") public class RemoveAssemblerAndActivityWizard extends AbstractHibernateSchemaMigration { private static final String KEY_PREFIX = PluginServiceImpl.getMyPluginId(RemoveAssemblerAndActivityWizard.class) + ".removeassembler."; @Inject private FileSystemService fileSystemService; @Inject private XmlService xmlService; @Override public MigrationInfo createMigrationInfo() { return new MigrationInfo(KEY_PREFIX + "title", KEY_PREFIX + "description"); } @Override protected Class<?>[] getDomainClasses() { return new Class[] { FakeActivityWizard.class, FakeActivityWizard.WebLink.class, FakeItemdefBlobs.class, FakeBaseEntity.class, FakeBaseEntity.Attribute.class, FakeLanguageBundle.class, FakeLanguageString.class, FakeItemDefinition.class, FakeItem.class, FakePowerSearch.class, FakeAttachment.class, FakeInstitution.class, FakeNavigationNode.class, FakeNavigationTab.class }; } @Override public boolean isBackwardsCompatible() { return false; } @Override protected List<String> getAddSql(HibernateMigrationHelper helper) { return Collections.emptyList(); } @Override protected List<String> getDropModifySql(HibernateMigrationHelper helper) { List<String> sql = helper.getDropTableSql("activity_wizard_links", "activity_wizard"); sql.addAll(helper.getDropColumnSQL("item_definition", "embedded_xslt")); sql.addAll(helper.getDropColumnSQL("item", "folder", "plan_metadata")); sql.addAll(helper.getDropColumnSQL("itemdef_blobs", "confirmation_template")); return sql; } @Override protected int countDataMigrations(HibernateMigrationHelper helper, Session session) { return 3 + count(session, "FROM ItemdefBlobs") + count(session, "FROM PowerSearch") + count(session, "from Attachment where type = 'activity'"); } @Override @SuppressWarnings("unchecked") protected void executeDataMigration( HibernateMigrationHelper helper, MigrationResult result, Session session) throws Exception { // Remove user preferences for the Assembler session .createSQLQuery("DELETE FROM user_preference WHERE preferenceid = 'assembler.preferences'") .executeUpdate(); result.incrementStatus(); // Remove system configuration dealing with the Assembler session .createSQLQuery( "DELETE FROM configuration_property WHERE" + " property LIKE 'assembler.%' OR property LIKE 'webct.%'" + " OR property LIKE 'blackboard.%' OR property = 'soap.timeout'" + " OR property LIKE 'activity-wizard.%'") .executeUpdate(); result.incrementStatus(); // Remove any security privileges for Activity Wizards and the assembler session .createSQLQuery( "DELETE FROM access_entry WHERE privilege LIKE '%_ACTIVITY_WIZARD'" + " OR target_object = 'C:assemblerDrmReference' OR target_object = 'C:assesmblerFileTypes'" + " OR target_object = 'C:assemblerLinks' OR target_object = 'C:lmsexport'" + " OR target_object = 'C:taxonomies' OR target_object = 'C:webct'") .executeUpdate(); result.incrementStatus(); // Remove wizard attributes that don't make sense final List<FakeItemdefBlobs> idbs = session.createQuery("FROM ItemdefBlobs").list(); for (FakeItemdefBlobs idb : idbs) { removeWizardAttributes(idb, session, result); } final List<FakePowerSearch> powerSearches = session.createQuery("FROM PowerSearch").list(); for (FakePowerSearch powerSearch : powerSearches) { removeWizardAttributes(powerSearch, session, result); } session.flush(); session.clear(); convertActivities(session, result); } @SuppressWarnings("unchecked") private void convertActivities(Session session, MigrationResult result) throws Exception { List<Long> itemIds = new ArrayList<Long>( session .createQuery( "select distinct(a.item.id) from Attachment a where a.type = 'activity'") .list()); for (Long itemId : itemIds) { Query query = session.createQuery( "select a, a.item.institution.shortName from Attachment a where a.type = 'activity' and a.item.id = ? order by a.attindex"); query.setParameter(0, itemId); int index = 0; List<Object[]> attList = query.list(); for (Object[] attach : attList) { FakeAttachment activity = (FakeAttachment) attach[0]; String shortName = (String) attach[1]; FakeItem item = activity.item; if (Check.isEmpty(activity.value2) && Check.isEmpty(activity.url)) { activity.type = "html"; // Assembler items would never have had collection bucket folders ItemFile itemFile = new ItemFile(item.uuid, item.version, null); Institution inst = new Institution(); inst.setFilestoreId(shortName); itemFile.setInstitution(inst); String htmlFile = "_activity/" + FileSystemHelper.encode(activity.description + ".html"); String destDir = "_mypages/" + activity.uuid; String destFile = destDir + "/page.html"; if (!fileSystemService.fileExists(itemFile, destFile)) { fileSystemService.mkdir(itemFile, destDir); fileSystemService.rename(itemFile, htmlFile, destFile); } if (fileSystemService.fileExists(itemFile, destFile)) { activity.value1 = Long.toString(fileSystemService.fileLength(itemFile, destFile)); } else { result.addLogEntry( new MigrationStatusLog( LogType.WARNING, KEY_PREFIX + "missingactivity", htmlFile, item.uuid, item.version)); activity.value1 = "0"; } activity.data = null; } else { ItemId itemIdKey; String extra; if (!Check.isEmpty(activity.url)) { String url = activity.url.substring(activity.url.indexOf("/items/") + 7); int verindex = url.indexOf('/'); String uuid = url.substring(0, verindex); int endindex = url.indexOf('/', verindex + 1); int version = Integer.parseInt(url.substring(verindex + 1, endindex)); itemIdKey = new ItemId(uuid, version); extra = URLDecoder.decode(url.substring(endindex + 1), "UTF-8"); // $NON-NLS-1$ if (extra.isEmpty()) { extra = "viewdefault.jsp"; // $NON-NLS-1$ } } else { itemIdKey = new ItemId(activity.value2); extra = activity.value3; } Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put("uuid", itemIdKey.getUuid()); dataMap.put("version", itemIdKey.getVersion()); dataMap.put("type", "p"); activity.type = "custom"; activity.url = extra; activity.value1 = "resource"; activity.value2 = null; activity.value3 = null; activity.data = xmlService.serialiseToXml(dataMap); } FakeNavigationNode node = new FakeNavigationNode(); node.index = index++; node.item = item; node.uuid = UUID.randomUUID().toString(); node.name = activity.description; FakeNavigationTab tab = new FakeNavigationTab(); tab.attachment = activity; tab.node = node; tab.name = "Created for Plan"; tab.tabindex = 0; session.save(node); session.save(tab); session.save(activity); result.incrementStatus(); } session.flush(); session.clear(); } } private void removeWizardAttributes(HasWizard hasWizard, Session session, MigrationResult result) throws Exception { final String wizardXml = hasWizard.getWizard(); if (!Check.isEmpty(wizardXml)) { PropBagEx xml = new PropBagEx(wizardXml); removeAllNodesWithName(xml, "background"); removeAllNodesWithName(xml, "styles"); removeAllNodesWithName(xml, "help"); hasWizard.setWizard(xml.toString()); session.update(hasWizard); session.flush(); } result.incrementStatus(); } private void removeAllNodesWithName(PropBagEx xml, String name) { final Iterator<PropBagEx> x = xml.iterateAllNodesWithName(name); while (x.hasNext()) { x.next(); x.remove(); } } public interface HasWizard { String getWizard(); void setWizard(String wizard); } @AccessType("field") @Entity(name = "ActivityWizard") public static class FakeActivityWizard extends FakeBaseEntity { @CollectionOfElements(fetch = FetchType.LAZY) @Fetch(value = FetchMode.SUBSELECT) @JoinColumn(name = "actwiz_id") List<WebLink> links = new ArrayList<WebLink>(); @Embeddable @AccessType("field") public static class WebLink { @Property(key = "url") String url; @Property(key = "global") boolean global; @Property(key = "title") String title; @Property(key = "description") String description; } } @Entity(name = "BaseEntity") @AccessType("field") @Inheritance(strategy = InheritanceType.JOINED) public static class FakeBaseEntity { @Id long id; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) FakeLanguageBundle description; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) FakeLanguageBundle name; @JoinColumn @ElementCollection(fetch = FetchType.EAGER) @CollectionTable( name = "base_entity_attributes", joinColumns = @JoinColumn(name = "base_entity_id")) @Fetch(value = FetchMode.SUBSELECT) List<Attribute> attributes; @Embeddable @AccessType("field") public static class Attribute implements Serializable { private static final long serialVersionUID = 1L; @Column(length = 64, nullable = false) String key; @Column(name = "value", length = 1024) String value; } } @Entity(name = "LanguageBundle") @AccessType("field") public static class FakeLanguageBundle { @Id long id; @OneToMany(cascade = CascadeType.ALL, mappedBy = "bundle") @Fetch(value = FetchMode.SELECT) @MapKey(name = "locale") Map<String, FakeLanguageString> strings; } @Entity(name = "LanguageString") @AccessType("field") public static class FakeLanguageString { @Id long id; @Column(length = 20, nullable = false) // @Index(name = "localeIndex") String locale; @JoinColumn(nullable = false) @ManyToOne(fetch = FetchType.LAZY) // @Index(name = "bundleIndex") FakeLanguageBundle bundle; } @Entity(name = "ItemDefinition") @AccessType("field") public static class FakeItemDefinition extends FakeBaseEntity { @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @Index(name = "collectionBlobs") FakeItemdefBlobs slow; String embeddedXslt; } @Entity(name = "PowerSearch") @AccessType("field") public static class FakePowerSearch extends FakeBaseEntity implements HasWizard { @Lob private String wizard; @Override public String getWizard() { return wizard; } @Override public void setWizard(String wizard) { this.wizard = wizard; } } @Entity(name = "ItemdefBlobs") @AccessType("field") public static class FakeItemdefBlobs implements Serializable, HasWizard { private static final long serialVersionUID = 1L; @Id long id; @Lob String wizard; @Lob String confirmationTemplate; @Override public String getWizard() { return wizard; } @Override public void setWizard(String wizard) { this.wizard = wizard; } } @Entity(name = "Item") @AccessType("field") public static class FakeItem { @Id @GeneratedValue(strategy = GenerationType.AUTO) long id; String uuid; int version; @Column(length = 40) String folder; String planMetadata; @ManyToOne FakeInstitution institution; } @Entity(name = "Institution") @AccessType("field") public static class FakeInstitution { @Id @GeneratedValue(strategy = GenerationType.AUTO) long id; String shortName; } @Entity(name = "Attachment") @AccessType("field") public static class FakeAttachment { @Id @GeneratedValue(strategy = GenerationType.AUTO) long id; String type; String data; String description; String thumbnail; String url; String uuid; String value1; String value2; String value3; @ManyToOne FakeItem item; int attindex; } @Entity(name = "ItemNavigationNode") @AccessType("field") public static class FakeNavigationNode { @Id @GeneratedValue(strategy = GenerationType.AUTO) long id; @ManyToOne FakeItem item; String icon; String identifier; int index; String name; String uuid; @ManyToOne FakeNavigationNode parent; } @Entity(name = "ItemNavigationTab") @AccessType("field") public static class FakeNavigationTab { @Id @GeneratedValue(strategy = GenerationType.AUTO) long id; int tabindex; String name; String viewer; @ManyToOne FakeAttachment attachment; @ManyToOne FakeNavigationNode node; } }
package com.vansuita.materialabout.builder; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.view.View; import com.vansuita.materialabout.R; import com.vansuita.materialabout.util.ColorUtil; import com.vansuita.materialabout.util.IconUtil; import com.vansuita.materialabout.util.IntentUtil; import com.vansuita.materialabout.views.AboutView; import java.util.LinkedList; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import static com.vansuita.materialabout.R.mipmap.share; /** * Used to build an {@link AboutView}. */ @SuppressWarnings({"WeakerAccess", "unused"}) public final class AboutBuilder { private Context context; private IntentUtil util; private String name; private String subTitle; private String brief; private String appName; private String appTitle; private Bitmap photo; private int photoRes = -1; private Bitmap cover; private int coverRes = -1; private boolean circularPhoto = true; private Bitmap appIcon; private int appIconRes = -1; private int nameColor; private int subTitleColor; private int briefColor; private int iconColor; private int backgroundColor; private boolean showDivider = true; private int dividerColor = 0; private int dividerHeight = 4; private int dividerDashWidth = 15; private int dividerDashGap = 15; private boolean linksAnimated = true; private int linksColumnsCount = 5; private int actionsColumnsCount = 2; private boolean wrapScrollView = false; private boolean showAsCard = true; private LinkedList<Item> links = new LinkedList<>(); private LinkedList<Item> actions = new LinkedList<>(); /** * @deprecated Used {@link #with(Context)} instead. */ @Deprecated AboutBuilder(Context context) { this.context = context; this.util = new IntentUtil(context); } public static AboutBuilder with(Context context) { //noinspection deprecation return new AboutBuilder(context); } public boolean isCircularPhoto() { return circularPhoto; } public void setCircularPhoto(boolean circularPhoto) { this.circularPhoto = circularPhoto; } public int getPhotoRes() { return photoRes; } /** * Sets the developer photo * * @param photo the image * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setPhotoRes(int photo) { photoRes = photo; return this; } public int getCoverRes() { return coverRes; } /** * Sets a about cover * * @param cover the image * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setCoverRes(int cover) { coverRes = cover; return this; } public int getAppIconRes() { return appIconRes; } /** * Sets an icon to display as app icon * * @param icon the app icon * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setAppIconRes(int icon) { appIconRes = icon; return this; } private String getApplicationID() { return context.getPackageName(); } private PackageInfo getPackageInfo() throws PackageManager.NameNotFoundException { return context.getPackageManager().getPackageInfo(getApplicationID(), 0); } /** * Gets the id of the last action added */ public int getLastActionId() { return getLastAction().getId(); } /** * Gets the last action item added */ public Item getLastAction() { return actions.getLast(); } /** * Gets the id of the last link added */ public int getLastLinkId() { return getLastLink().getId(); } /** * Gets the last link item added */ public Item getLastLink() { return links.getLast(); } /** * Displays the app version below the app name * * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setVersionNameAsAppSubTitle() { try { return setAppTitle(context.getString(com.vansuita.materialabout.R.string.version, getPackageInfo().versionName)); } catch (PackageManager.NameNotFoundException e) { return setAppTitle(R.string.error); } } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(Bitmap icon, String label, View.OnClickListener onClickListener) { links.add(new Item(icon, label, onClickListener)); return this; } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(Bitmap icon, String label, Intent intent) { return addLink(icon, label, util.clickIntent(intent)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(Bitmap icon, String label, Uri uri) { return addLink(icon, label, util.clickUri(uri)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(Bitmap icon, String label, String url) { return addLink(icon, label, Uri.parse(url)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(Bitmap icon, int label, View.OnClickListener onClickListener) { return addLink(icon, context.getString(label), onClickListener); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(Bitmap icon, int label, Intent intent) { return addLink(icon, label, util.clickIntent(intent)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(Bitmap icon, int label, Uri uri) { return addLink(icon, label, util.clickUri(uri)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(Bitmap icon, int label, String url) { return addLink(icon, label, Uri.parse(url)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(int icon, String label, View.OnClickListener onClickListener) { links.add(new ItemRes(icon, label, onClickListener)); return this; } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(int icon, int label, View.OnClickListener onClickListener) { return addLink(icon, context.getString(label), onClickListener); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(int icon, int label, Intent intent) { return addLink(icon, label, util.clickIntent(intent)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(int icon, int label, Uri uri) { return addLink(icon, label, util.clickUri(uri)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(int icon, int label, String url) { return addLink(icon, label, Uri.parse(url)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(int icon, String label, Intent intent) { return addLink(icon, label, util.clickIntent(intent)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(int icon, String label, Uri uri) { return addLink(icon, label, util.clickUri(uri)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(int icon, String label, String url) { return addLink(icon, label, Uri.parse(url)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(@NonNull BitmapDrawable icon, int label, View.OnClickListener onClickListener) { return addLink(IconUtil.getBitmap(icon), context.getString(label), onClickListener); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(@NonNull BitmapDrawable icon, int label, Intent intent) { return addLink(icon, label, util.clickIntent(intent)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(@NonNull BitmapDrawable icon, int label, Uri uri) { return addLink(icon, label, util.clickUri(uri)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(@NonNull BitmapDrawable icon, int label, String url) { return addLink(icon, label, Uri.parse(url)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(@NonNull BitmapDrawable icon, String label, View.OnClickListener onClickListener) { return addLink(IconUtil.getBitmap(icon), label, onClickListener); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(@NonNull BitmapDrawable icon, String label, Intent intent) { return addLink(icon, label, util.clickIntent(intent)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(@NonNull BitmapDrawable icon, String label, Uri uri) { return addLink(icon, label, util.clickUri(uri)); } /** * Adds an link on the links section. * * @param icon the action icon * @param label the action title * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLink(@NonNull BitmapDrawable icon, String label, String url) { return addLink(icon, label, Uri.parse(url)); } /** * Adds a GitHub profile link on the links section * * @param user a GitHub user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addGitHubLink(int user) { return addGitHubLink(context.getString(user)); } /** * Adds a GitHub profile link on the links section * * @param user a GitHub user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addGitHubLink(String user) { return addLink(R.mipmap.github, R.string.github, util.uri(R.string.url_github, user)); } /** * Adds a Bitbucket profile link on the links section * * @param user a Bitbucket user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addBitbucketLink(int user) { return addBitbucketLink(context.getString(user)); } /** * Adds a Bitbucket profile link on the links section * * @param user a Bitbucket user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addBitbucketLink(String user) { return addLink(R.mipmap.bitbucket, R.string.bitbucket, util.uri(R.string.url_bitbucket, user)); } /** * Adds a Facebook profile link on the links section * * @param user a Facebook user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFacebookLink(int user) { return addFacebookLink(context.getString(user)); } /** * Adds a Facebook profile link on the links section * * @param user a Facebook user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFacebookLink(String user) { return addLink(R.mipmap.facebook, R.string.facebook, util.openFacebook(user)); } /** * Adds a Instagram profile link on the links section * * @param user a Instagram user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addInstagramLink(int user) { return addInstagramLink(context.getString(user)); } /** * Adds a Instagram profile link on the links section * * @param user a Instagram user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addInstagramLink(String user) { return addLink(R.mipmap.instagram, R.string.instagram, util.openInstagram(user)); } /** * Adds a Twitter profile link on the links section * * @param user a Twitter user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addTwitterLink(int user) { return addTwitterLink(context.getString(user)); } /** * Adds a Twitter profile link on the links section * * @param user a Twitter user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addTwitterLink(String user) { return addLink(R.mipmap.twitter, R.string.twitter, util.openTwitter(user)); } /** * Adds a Google link on the links section * * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addGoogleLink(int url) { return addGoogleLink(context.getString(url)); } /** * Adds a Google link on the links section * * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addGoogleLink(String url) { return addLink(R.mipmap.google, R.string.google, url); } /** * Adds a Google Plus profile link on the links section * * @param user a Google Plus user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addGooglePlusLink(int user) { return addGooglePlusLink(context.getString(user)); } /** * Adds a Google Plus profile link on the links section * * @param user a Google Plus user name or id * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addGooglePlusLink(String user) { return addLink(R.mipmap.google_plus, R.string.google_plus, util.openGooglePlus(user)); } /** * Adds a Google Play Store profile link on the links section * * @param user a Google Play Store user name or id * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addGooglePlayStoreLink(int user) { return addGooglePlayStoreLink(context.getString(user)); } /** * Adds a Google Play Store profile link on the links section * * @param user a Google Play Store user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addGooglePlayStoreLink(String user) { return addLink(R.mipmap.google_play_store, R.string.google_play_store, util.openGooglePlayDev(user)); } /** * Adds a Google Games link on the links section * * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addGoogleGamesLink(int url) { return addGoogleGamesLink(context.getString(url)); } /** * Adds a Google Games link on the links section * * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addGoogleGamesLink(String url) { return addLink(R.mipmap.google_play_games, R.string.google_play_games, url); } /** * Adds a Youtube channel link on the links section * * @param user a Youtube channel name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addYoutubeChannelLink(int user) { return addYoutubeChannelLink(context.getString(user)); } /** * Adds a Youtube channel link on the links section * * @param user a Youtube channel name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addYoutubeChannelLink(String user) { return addLink(R.mipmap.youtube, R.string.youtube, util.openYoutubeChannel(user)); } /** * Adds a Youtube user link on the links section * * @param user a Youtube user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addYoutubeUserLink(int user) { return addYoutubeUserLink(context.getString(user)); } /** * Adds a Youtube user link on the links section * * @param user a Youtube user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addYoutubeUserLink(String user) { return addLink(R.mipmap.youtube, R.string.youtube, util.openYoutubeUser(user)); } /** * Adds a LinkedIn profile link on the links section * * @param user a LinkedIn user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLinkedInLink(int user) { return addLinkedInLink(context.getString(user)); } /** * Adds a LinkedIn profile link on the links section * * @param user a LinkedIn user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLinkedInLink(String user) { return addLink(R.mipmap.linkedin, R.string.linkedin, util.openLinkedIn(user)); } /** * Adds a Skype phone call on the links section * * @param phone a valid skype phone number * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addSkypeLink(int phone) { return addSkypeLink(context.getString(phone)); } /** * Adds a Skype phone call on the links section * * @param phone a valid skype phone number * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addSkypeLink(String phone) { return addLink(R.mipmap.skype, R.string.skype, util.openSkype(phone)); } /** * Adds a new contact button on the links section * * @param phone any phone number * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addWhatsappLink(int name, int phone) { return addWhatsappLink(context.getString(name), context.getString(phone)); } /** * Adds a new contact button on the links section * * @param phone any phone number * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addWhatsappLink(String name, String phone) { return addLink(R.mipmap.whatsapp, R.string.whastapp, util.openAddContact(name, phone)); } /** * Adds a Android link on the links section * * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAndroidLink(int url) { return addAndroidLink(context.getString(url)); } /** * Adds a Android link on the links section * * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAndroidLink(String url) { return addLink(R.mipmap.android, R.string.android, url); } /** * Adds a Dribbble link on the links section * * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addDribbbleLink(int url) { return addDribbbleLink(context.getString(url)); } /** * Adds a Dribbble link on the links section * * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addDribbbleLink(String url) { return addLink(R.mipmap.dribbble, R.string.dribbble, url); } /** * Adds a website link on the links section * * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addWebsiteLink(int url) { return addWebsiteLink(context.getString(url)); } /** * Adds a website link on the links section * * @param url any url * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addWebsiteLink(String url) { return addLink(R.mipmap.website, R.string.website, url); } /** * Adds a e-mail link on the links section * * @param email addressee e-mail * @param subject the subject of the e-mail * @param message the contect of the e-mail * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addEmailLink(int email, int subject, int message) { return addEmailLink(context.getString(email), context.getString(subject), context.getString(message)); } /** * Adds a e-mail link on the links section * * @param email addressee e-mail * @param subject the subject of the e-mail * @param message the contect of the e-mail * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addEmailLink(int email, String subject, String message) { return addEmailLink(context.getString(email), subject, message); } /** * Adds a e-mail link on the links section * * @param email addressee e-mail * @param subject the subject of the e-mail * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addEmailLink(int email, String subject) { return addEmailLink(context.getString(email), subject, null); } /** * Adds a e-mail link on the links section * * @param email addressee e-mail * @param subject the subject of the e-mail * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addEmailLink(int email, int subject) { return addEmailLink(context.getString(email), context.getString(subject), null); } /** * Adds a e-mail link on the links section * * @param email addressee e-mail * @param subject the subject of the e-mail * @param message the contect of the e-mail * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addEmailLink(String email, String subject, String message) { return addLink(R.mipmap.email, R.string.email, util.sendEmail(email, subject, message)); } /** * Adds a e-mail link on the links section without ant subject or contents * * @param email addressee e-mail * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addEmailLink(int email) { return addEmailLink(context.getString(email)); } /** * Adds a e-mail link on the links section without ant subject or contents * * @param email addressee e-mail * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addEmailLink(String email) { return addLink(R.mipmap.email, R.string.email, util.sendEmail(email, null, null)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(Bitmap icon, String label, View.OnClickListener onClickListener) { actions.add(new Item(icon, label, onClickListener)); return this; } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(Bitmap icon, String label, Intent intent) { return addAction(icon, label, util.clickIntent(intent)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(Bitmap icon, String label, Uri uri) { return addAction(icon, label, util.clickUri(uri)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param url any url to browse * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(Bitmap icon, String label, String url) { return addAction(icon, label, Uri.parse(url)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(Bitmap icon, int label, View.OnClickListener onClickListener) { return addAction(icon, context.getString(label), onClickListener); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(Bitmap icon, int label, Intent intent) { return addAction(icon, label, util.clickIntent(intent)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(Bitmap icon, int label, Uri uri) { return addAction(icon, label, util.clickUri(uri)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param url any url to browse * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(Bitmap icon, int label, String url) { return addAction(icon, label, Uri.parse(url)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(int icon, int label, View.OnClickListener onClickListener) { return addAction(IconUtil.getBitmap(context, icon), context.getString(label), onClickListener); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(int icon, int label, Intent intent) { return addAction(icon, label, util.clickIntent(intent)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(int icon, int label, Uri uri) { return addAction(icon, label, util.clickUri(uri)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param url any url to browse * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(int icon, int label, String url) { return addAction(icon, label, Uri.parse(url)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(int icon, String label, View.OnClickListener onClickListener) { return addAction(IconUtil.getBitmap(context, icon), label, onClickListener); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(int icon, String label, Intent intent) { return addAction(icon, label, util.clickIntent(intent)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(int icon, String label, Uri uri) { return addAction(icon, label, util.clickUri(uri)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param url any url to browse * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(int icon, String label, String url) { return addAction(icon, label, Uri.parse(url)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(@NonNull BitmapDrawable icon, int label, View.OnClickListener onClickListener) { return addAction(IconUtil.getBitmap(icon), context.getString(label), onClickListener); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(@NonNull BitmapDrawable icon, int label, Intent intent) { return addAction(icon, label, util.clickIntent(intent)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(@NonNull BitmapDrawable icon, int label, Uri uri) { return addAction(icon, label, util.clickUri(uri)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param url any url to browse * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(@NonNull BitmapDrawable icon, int label, String url) { return addAction(icon, label, Uri.parse(url)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(@NonNull BitmapDrawable icon, String label, View.OnClickListener onClickListener) { return addAction(IconUtil.getBitmap(icon), label, onClickListener); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(@NonNull BitmapDrawable icon, String label, Intent intent) { return addAction(icon, label, util.clickIntent(intent)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param uri the action uri * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(@NonNull BitmapDrawable icon, String label, Uri uri) { return addAction(icon, label, util.clickUri(uri)); } /** * Adds an action button on the actions section. * * @param icon the action icon * @param label the action title * @param url any url to browse * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addAction(@NonNull BitmapDrawable icon, String label, String url) { return addAction(icon, label, Uri.parse(url)); } /** * Adds an action button to rate the app on Google Play Store * * @param appId the application id * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFiveStarsAction(int appId) { return addFiveStarsAction(context.getString(appId)); } /** * Adds an action button to rate the app on Google Play Store * * @param appId the application id * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFiveStarsAction(String appId) { return addAction(R.mipmap.star, R.string.rate_five_stars, util.openPlayStoreAppPage(appId)); } /** * Adds an action button to rate the app on Google Play Store. * This method use the default application id from the context * * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFiveStarsAction() { return addFiveStarsAction(getApplicationID()); } /** * Adds an action button to update the app using Google Play Store * * @param appId the application id * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addUpdateAction(int appId) { return addUpdateAction(context.getString(appId)); } /** * Adds an action button to update the app using Google Play Store * * @param appId the application id * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addUpdateAction(String appId) { return addAction(R.mipmap.update, R.string.update_app, util.openPlayStoreAppPage(appId)); } /** * Adds an action button to update the app using Google Play Store * This method use the default application id from the context * * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addUpdateAction() { return addUpdateAction(getApplicationID()); } /** * Adds an action button to browse more apps from the developer * * @param userName the developer user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addMoreFromMeAction(int userName) { return addMoreFromMeAction(context.getString(userName)); } /** * Adds an action button to browse more apps from the developer * * @param userName the developer user name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addMoreFromMeAction(String userName) { return addAction(R.mipmap.google_play_store, R.string.more_apps, util.openPlayStoreAppsList(userName)); } /** * Adds a share action button * * @param subject the subject * @param message the content message * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addShareAction(int subject, int message) { return addShareAction(context.getString(subject), context.getString(message)); } /** * Adds a share action button * * @param subject the subject * @param message the content message * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addShareAction(String subject, String message) { return addAction(share, R.string.share_app, util.shareThisApp(subject, message)); } /** * Adds a share action button. No content message will be placed * * @param subject the subject * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addShareAction(String subject) { return addShareAction(subject, context.getString(R.string.uri_play_store_app_website, context.getPackageName())); } /** * Adds a share action button. No content message will be placed * * @param subject the subject * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addShareAction(int subject) { return addShareAction(context.getString(subject)); } /** * Adds a feedback action button * * @param email the developer e-mail * @param subject the subject * @param content the e-mail content * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFeedbackAction(int email, int subject, int content) { return addFeedbackAction(context.getString(email), context.getString(subject), context.getString(content)); } /** * Adds a feedback action button * * @param email the developer e-mail * @param subject the subject * @param content the e-mail content * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFeedbackAction(int email, String subject, String content) { return addAction(R.mipmap.feedback, R.string.feedback_app, util.sendEmail(context.getString(email), subject, content)); } /** * Adds a feedback action button * * @param email the developer e-mail * @param subject the subject * @param content the e-mail content * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFeedbackAction(String email, String subject, String content) { return addAction(R.mipmap.feedback, R.string.feedback_app, util.sendEmail(email, subject, content)); } /** * Adds a feedback action button. No content message will be placed * * @param email the developer e-mail * @param subject the subject * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFeedbackAction(int email, int subject) { return addFeedbackAction(context.getString(email), context.getString(subject)); } /** * Adds a feedback action button. No content message will be placed * * @param email the developer e-mail * @param subject the subject * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFeedbackAction(String email, String subject) { return addFeedbackAction(email, subject, null); } /** * Adds a feedback action button. No content message will be placed * * @param email the developer e-mail * @param subject the subject * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFeedbackAction(int email, String subject) { return addFeedbackAction(context.getString(email), subject, null); } /** * Adds a feedback action button. No subject or content message will be placed * * @param email the developer e-mail * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFeedbackAction(int email) { return addFeedbackAction(context.getString(email)); } /** * Adds a feedback action button. No subject or content message will be placed * * @param email the developer e-mail * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addFeedbackAction(String email) { return addFeedbackAction(email, null); } /** * Adds an introduce action button * * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addIntroduceAction(View.OnClickListener onClickListener) { return addAction(R.mipmap.intrduce, R.string.introduce_app, onClickListener); } /** * Adds an introduce action button * * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addIntroduceAction(Intent intent) { return addIntroduceAction(util.clickIntent(intent)); } /** * Adds an help action button * * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addHelpAction(View.OnClickListener onClickListener) { return addAction(R.mipmap.help, R.string.help, onClickListener); } /** * Adds an help action button * * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addHelpAction(Intent intent) { return addHelpAction(util.clickIntent(intent)); } /** * Adds an license action button * * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLicenseAction(View.OnClickListener onClickListener) { return addAction(R.mipmap.license, R.string.license, onClickListener); } /** * Adds an license action button * * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addLicenseAction(Intent intent) { return addLicenseAction(util.clickIntent(intent)); } /** * Adds an changelog action button * * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addChangeLogAction(View.OnClickListener onClickListener) { return addAction(R.mipmap.changelog, R.string.ma_changelog, onClickListener); } /** * Adds an changelog action button * * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addChangeLogAction(Intent intent) { return addChangeLogAction(util.clickIntent(intent)); } /** * Adds an remove ads action button * * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addRemoveAdsAction(View.OnClickListener onClickListener) { return addAction(R.mipmap.ads, R.string.remove_ads, onClickListener); } /** * Adds an remove ads action button * * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addRemoveAdsAction(Intent intent) { return addRemoveAdsAction(util.clickIntent(intent)); } /** * Adds an donate action button * * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addDonateAction(View.OnClickListener onClickListener) { return addAction(R.mipmap.donate, R.string.donate, onClickListener); } /** * Adds an donate action button * * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addDonateAction(Intent intent) { return addDonateAction(util.clickIntent(intent)); } /** * Adds a privacy policy action button * * @param url the url to privacy policy web page * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addPrivacyPolicyAction(String url) { return addAction(R.mipmap.privacy, R.string.privacy, util.intent(url)); } /** * Adds a privacy policy action button * * @param onClickListener the click callback * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addPrivacyPolicyAction(View.OnClickListener onClickListener) { return addAction(R.mipmap.privacy, R.string.privacy, onClickListener); } /** * Adds a privacy policy action button * * @param intent the action intent * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder addPrivacyPolicyAction(Intent intent) { return addAction(R.mipmap.privacy, R.string.privacy, util.clickIntent(intent)); } public boolean isShowAsCard() { return showAsCard; } /** * Wraps the content in a {@link CardView} * * @param showAsCard true if show in a CardView * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setShowAsCard(boolean showAsCard) { this.showAsCard = showAsCard; return this; } public String getName() { return name; } /** * Sets the developer name * * @param text the name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setName(String text) { this.name = text; return this; } /** * Sets the developer name * * @param text the name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setName(int text) { return setName(context.getString(text)); } public String getSubTitle() { return subTitle; } /** * Sets the sub title. It will be place below the developer name * * @param text the sub title * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setSubTitle(String text) { this.subTitle = text; return this; } /** * Sets the sub title. It will be place below the developer name * * @param text the sub title * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setSubTitle(int text) { return setSubTitle(context.getString(text)); } public String getBrief() { return brief; } /** * Sets a personal brief * * @param text the brief * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setBrief(String text) { this.brief = text; return this; } /** * Sets a personal brief * * @param text the brief * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setBrief(int text) { return setBrief(context.getString(text)); } public String getAppName() { return appName; } /** * Sets the app name * * @param text the app name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setAppName(String text) { this.appName = text; return this; } /** * Sets the app name * * @param text the app name * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setAppName(int text) { return setAppName(context.getString(text)); } public String getAppTitle() { return appTitle; } /** * Sets the app title * * @param text the title * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setAppTitle(String text) { this.appTitle = text; return this; } /** * Sets the app title * * @param text the title * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setAppTitle(int text) { return setAppTitle(context.getString(text)); } public Bitmap getPhoto() { return photo; } /** * Sets the developer photo * * @param photo the image * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setPhoto(Bitmap photo) { this.photo = photo; return this; } /** * Sets the developer photo * * @param photo the image * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setPhoto(int photo) { return setPhoto(IconUtil.getBitmap(context, photo)); } /** * Sets the developer photo * * @param photo the image * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setPhoto(@NonNull BitmapDrawable photo) { return setPhoto(IconUtil.getBitmap(photo)); } public Bitmap getCover() { return cover; } /** * Sets a about cover * * @param cover the image * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setCover(Bitmap cover) { this.cover = cover; return this; } /** * Sets a about cover * * @param cover the image * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setCover(int cover) { return setCover(IconUtil.getBitmap(context, cover)); } /** * Sets a about cover * * @param cover the image * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setCover(@NonNull BitmapDrawable cover) { return setCover(IconUtil.getBitmap(cover)); } public Bitmap getAppIcon() { return appIcon; } /** * Sets an icon to display as app icon * * @param icon the app icon * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setAppIcon(Bitmap icon) { this.appIcon = icon; return this; } /** * Sets an icon to display as app icon * * @param icon the app icon * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setAppIcon(int icon) { return setAppIcon(IconUtil.getBitmap(context, icon)); } /** * Sets an icon to display as app icon * * @param icon the app icon * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setAppIcon(@NonNull BitmapDrawable icon) { return setAppIcon(IconUtil.getBitmap(icon)); } public int getNameColor() { return nameColor; } /** * Sets the name text color * * @param color the color resource or the real color. * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setNameColor(int color) { this.nameColor = ColorUtil.get(context, color); return this; } public int getSubTitleColor() { return subTitleColor; } /** * Sets the sub title text color * * @param color the color resource or the real color. * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setSubTitleColor(int color) { this.subTitleColor = ColorUtil.get(context, color); return this; } public int getBriefColor() { return briefColor; } /** * Sets the brief text color * * @param color the color resource or the real color. * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setBriefColor(int color) { this.briefColor = ColorUtil.get(context, color); return this; } public int getDividerColor() { return dividerColor; } /** * Sets the divider color * * @param color the color resource or the real color. * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setDividerColor(int color) { this.dividerColor = ColorUtil.get(context, color); return this; } public int getIconColor() { return iconColor; } /** * Sets the icons color * * @param color the color resource or the real color. * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setIconColor(int color) { this.iconColor = ColorUtil.get(context, color); return this; } public int getBackgroundColor() { return backgroundColor; } /** * Sets the about view background color * * @param color the color resource or the real color. * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setBackgroundColor(int color) { this.backgroundColor = ColorUtil.get(context, color); return this; } public int getLinksColumnsCount() { return linksColumnsCount; } /** * Sets the maximum number of columns for the links section * * @param count number of columns * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setLinksColumnsCount(int count) { this.linksColumnsCount = count; return this; } public int getActionsColumnsCount() { return actionsColumnsCount; } /** * Sets the maximum number of columns for the actions section * * @param count number of columns * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setActionsColumnsCount(int count) { this.actionsColumnsCount = count; return this; } public boolean isShowDivider() { return showDivider; } /** * Displays a divider line between the about sections * * @param showDivider true if you want it * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setShowDivider(boolean showDivider) { this.showDivider = showDivider; return this; } public int getDividerHeight() { return dividerHeight; } /** * Sets the divider height * * @param dividerHeight size of the height * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setDividerHeight(int dividerHeight) { this.dividerHeight = dividerHeight; return this; } public int getDividerDashWidth() { return dividerDashWidth; } /** * Sets the divider dash width * * @param dividerDashWidth size of the width * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setDividerDashWidth(int dividerDashWidth) { this.dividerDashWidth = dividerDashWidth; return this; } public int getDividerDashGap() { return dividerDashGap; } /** * Sets the divider dash gap * * @param dividerDashGap size of the gap * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setDividerDashGap(int dividerDashGap) { this.dividerDashGap = dividerDashGap; return this; } public boolean isLinksAnimated() { return linksAnimated; } /** * Sets an animation when displaying the actions * * @param animate true if you want it * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setLinksAnimated(boolean animate) { this.linksAnimated = animate; return this; } public boolean isWrapScrollView() { return wrapScrollView; } /** * Places the about view inside a {@link android.widget.ScrollView} * * @param wrapScrollView true if you want to wrap * @return the same {@link AboutBuilder} instance */ @NonNull public AboutBuilder setWrapScrollView(boolean wrapScrollView) { this.wrapScrollView = wrapScrollView; return this; } @NonNull public LinkedList<Item> getLinks() { return links; } @NonNull public LinkedList<Item> getActions() { return actions; } @NonNull public AboutView build() { AboutView aboutView = new AboutView(context); aboutView.build(this); return aboutView; } }
package com.poc.pricing.auth.dto; import java.util.List; import com.poc.pricing.auth.model.Role; import io.swagger.annotations.ApiModelProperty; public class UserDataDTO { @ApiModelProperty(position = 0) private String username; @ApiModelProperty(position = 1) private String email; @ApiModelProperty(position = 2) private String password; @ApiModelProperty(position = 3) List<Role> roles; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } }
/** * Copyright Intellectual Reserve, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.familysearch.platform.ct; import com.fasterxml.jackson.annotation.JsonInclude; import org.gedcomx.rt.json.JsonElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * Information about a search. */ @XmlRootElement @JsonElementWrapper ( name = "searchInfo" ) @XmlType ( name = "SearchInfo" ) @JsonInclude ( JsonInclude.Include.NON_NULL ) public class SearchInfo { private Integer totalHits; private Integer closeHits; /** * The total number of hits. * * @return The total number of hits. */ public Integer getTotalHits() { return totalHits; } /** * The total number of hits. * * @param totalHits The total number of hits. */ public void setTotalHits(Integer totalHits) { this.totalHits = totalHits; } /** * The number of close hits. * * @return The number of close hits. */ public Integer getCloseHits() { return closeHits; } /** * The number of close hits. * * @param closeHits The number of close hits. */ public void setCloseHits(Integer closeHits) { this.closeHits = closeHits; } }
package org.mitre.policynet.policynet_layout; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class LayoutTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public LayoutTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( LayoutTest.class ); } /** * Rigorous Test :-) */ public void testApp() { assertTrue( true ); } }
/******************************************************************************* * Copyright (c) 1991, 2021 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ package com.ibm.j9ddr.vm29.structure; /** * Structure: J9VMExceptionDescribeEvent * * This stub class represents a class that can return in memory offsets * to VM C and C++ structures. * * This particular implementation exists only to allow StructurePointer code to * compile at development time. This is never loaded at run time. * * At runtime generated byte codes returning actual offset values from the core file * will be loaded by the StructureClassLoader. */ public final class J9VMExceptionDescribeEvent { // VM Constants public static final long SIZEOF; // Offsets public static final int _currentThreadOffset_; public static final int _exceptionOffset_; // Static Initializer private static final boolean RUNTIME = false; static { if (!RUNTIME) { throw new IllegalArgumentException("This stub class should not be on your classpath"); } SIZEOF = 0; _currentThreadOffset_ = 0; _exceptionOffset_ = 0; } }
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.accessservices.subjectarea.properties.enums; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonInclude; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * Defines the sequencing for a collection. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public enum OrderBy implements Serializable { /** * Order by name property. */ Name(0, "Order by name property.") , /** * Order by owner property. */ Owner(1, "Order by owner property.") , /** * Order by date added to the metadata collection. */ DateAdded(2, "Order by date added to the metadata collection.") , /** * Order by date that the asset was updated. */ DateUpdated(3, "Order by date that the asset was updated.") , /** * Order by date that the asset was created. */ DateCreated(4, "Order by date that the asset was created.") , /** * Order by another property. */ Other(99, "Order by another property.") ; private final int ordinal; private final String description ; /** * Default constructor sets up the specific values for an OrderBy enum instance. * * @param ordinal int enum value ordinal * @param description String description */ OrderBy(int ordinal, String description) { this.ordinal = ordinal; this.description = description; } /** * Return the numerical value for the enum. * * @return int enum value ordinal */ public int getOrdinal() { return this.ordinal; } /** * Return the description for the enum. * * @return String description */ public String getDescription() { return this.description; } /** * Return the descriptive name for the OrderBy enum instance * * @return String name */ public String getName() { return this.name(); } }
package com.maven.dao; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.maven.entity.EnterpriseAgength5Level; import com.maven.entity.EnterpriseEmployeeLevel; @Repository public interface EnterpriseAgength5LevelDao { /** * 调用获取员工级别数据方法 * @return Map<String, Object> */ public List<EnterpriseAgength5Level> getAllEmployeeLovel(); /** * 根据条件查询数据并且分页 * @param object * @return */ public List<EnterpriseAgength5Level> levelQuery(Map<String, Object> object); /** * 根据条件统计 * @param object * @return */ public int count(Map<String, Object> object); /** * 保存方法 * @param employeeLevel */ public void save(EnterpriseAgength5Level employeeLevel); /** * 批量删除 * @param array */ public void deleteBatch(String[] array); /** * 修改 * @param employeeLevel */ public void update(EnterpriseAgength5Level employeeLevel); /** * 删除 */ public void delete(String deleteCode); /** * 根据编码查询单个对象 * @param employeelevelCode * @return */ public EnterpriseAgength5Level getOneObject(String employeelevelcode); }
// Template Source: IBaseMethodBodyRequest.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.models.extensions.WorkbookFunctionResult; import com.microsoft.graph.requests.extensions.IWorkbookFunctionsNperRequest; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.http.BaseCollectionRequest; import com.microsoft.graph.http.BaseRequest; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.http.BaseCollectionRequest; import com.microsoft.graph.http.IHttpRequest; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The interface for the Workbook Functions Nper Request. */ public interface IWorkbookFunctionsNperRequest extends IHttpRequest { void post(final ICallback<? super WorkbookFunctionResult> callback); WorkbookFunctionResult post() throws ClientException; /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ IWorkbookFunctionsNperRequest select(final String value) ; /** * Sets the top value for the request * * @param value the max number of items to return * @return the updated request */ IWorkbookFunctionsNperRequest top(final int value); /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ IWorkbookFunctionsNperRequest expand(final String value); }
/* * 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. * * Contributions from 2013-2017 where performed either by US government * employees, or under US Veterans Health Administration contracts. * * US Veterans Health Administration contributions by government employees * are work of the U.S. Government and are not subject to copyright * protection in the United States. Portions contributed by government * employees are USGovWork (17USC §105). Not subject to copyright. * * Contribution by contractors to the US Veterans Health Administration * during this period are contractually contributed under the * Apache License, Version 2.0. * * See: https://www.usa.gov/government-works * * Contributions prior to 2013: * * Copyright (C) International Health Terminology Standards Development Organisation. * Licensed under the Apache License, Version 2.0. * */ package sh.isaac.api.index; //~--- non-JDK imports -------------------------------------------------------- import org.jvnet.hk2.annotations.Contract; //~--- interfaces ------------------------------------------------------------- /** * {@link IndexStatusListener} * * Any @Service annotated class which implements this interface will get the notifications below, when * index events happen. * * @author <a href="mailto:daniel.armbrust.list@gmail.com">Dan Armbrust</a> */ @Contract public interface IndexStatusListener { /** * Called when an index configuration change happens that listeners might be interested in. * @param indexConfigurationThatChanged - the indexer that had a change */ public void indexConfigurationChanged(IndexQueryService indexConfigurationThatChanged); /** * Called when a reindex sequence begins. * * @param index - the index being recreated */ public void reindexBegan(IndexQueryService index); /** * Called when a reindex sequence completes. * * @param index - the index that was recreated */ public void reindexCompleted(IndexQueryService index); }
package com.cinemafy.backend.repositories; /** * @author Mustafa Atmaca */ import com.cinemafy.backend.models.Cinema; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface CinemaRepository extends CrudRepository<Cinema, Long>, JpaRepository<Cinema, Long> { List<Cinema> findByNameContainingIgnoreCase(String filter); List<Cinema> findByCityContainingIgnoreCase(String filter); }
package com.mit.cloud; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.config.server.EnableConfigServer; /** * <p>Description:<p> * * @Author: Mr.Deng * @Date: 2018/11/8 11:58 * <p>Copyright: Copyright (c) 2018</p> * <p>Company: mitesofor </p> */ @SuppressWarnings("ALL") @EnableConfigServer @SpringBootApplication public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(WebApplicationType.SERVLET).run(args); } }
package com.example.application.customer.service; import com.example.application.customer.pojo.info.AdminCustomerInfoSaveRequestBody; import com.example.application.customer.pojo.info.AdminCustomerInfoUpdateRequestBody; import com.example.commons.db.mybatis.plus.pagehelper.module.pojo.query.CustomerInfoQuery; import com.example.commons.web.base.pojo.Result; import java.util.List; /** * @program: admin-demo-gradle * @description: * @author: yuane * @create: 2020-04-11 13:46 */ public interface AdminCustomerInfoService { Result data(CustomerInfoQuery query); Result list(CustomerInfoQuery query); Result get(Long id); Result save(AdminCustomerInfoSaveRequestBody requestBody); Result update(AdminCustomerInfoUpdateRequestBody requestBody); Result delete(Long id); Result delete(List<Long> ids); }
/* * 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.ignite.internal.processors.compute; import org.apache.ignite.IgniteException; import org.apache.ignite.Ignition; import org.apache.ignite.configuration.ExecutorConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; /** * Tests custom executor configuration. */ public class IgniteComputeCustomExecutorConfigurationSelfTest extends GridCommonAbstractTest { /** * @throws Exception If failed. */ @Test public void testConfigurations() throws Exception { try { checkStartWithInvalidConfiguration(getConfiguration("node0") .setExecutorConfiguration(new ExecutorConfiguration())); checkStartWithInvalidConfiguration(getConfiguration("node0") .setExecutorConfiguration(new ExecutorConfiguration(""))); checkStartWithInvalidConfiguration(getConfiguration("node0") .setExecutorConfiguration(new ExecutorConfiguration("exec").setSize(-1))); checkStartWithInvalidConfiguration(getConfiguration("node0") .setExecutorConfiguration(new ExecutorConfiguration("exec").setSize(0))); } finally { Ignition.stopAll(true); } } /** * @param cfg Ignite configuration. * @throws Exception If failed. */ private void checkStartWithInvalidConfiguration(IgniteConfiguration cfg) throws Exception { try { Ignition.start(cfg); fail("Node start must fail."); } catch (IgniteException e) { // No-op. } } }
// Copyright 2019 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.firebase.storage.network; import android.net.Uri; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.firebase.FirebaseApp; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; /** A network request that lists folder contents within gcs. */ public class ListNetworkRequest extends NetworkRequest { @Nullable private final Integer maxPageSize; @Nullable private final String nextPageToken; public ListNetworkRequest( @NonNull Uri gsUri, @NonNull FirebaseApp app, @Nullable Integer maxPageSize, @Nullable String nextPageToken) { super(gsUri, app); this.maxPageSize = maxPageSize; this.nextPageToken = nextPageToken; } @Override @NonNull protected String getAction() { return GET; } @Override @NonNull protected String getURL() { return sNetworkRequestUrl + "/b/" + mGsUri.getAuthority() + "/o"; } @Override @Nullable protected String getQueryParameters() throws UnsupportedEncodingException { List<String> keys = new ArrayList<>(); List<String> values = new ArrayList<>(); String prefix = getPathWithoutBucket(); if (!TextUtils.isEmpty(prefix)) { keys.add("prefix"); values.add(prefix + "/"); } // Firebase Storage uses file system semantics and treats slashes as separators. GCS's List API // does not prescribe a separator, and hence we need to provide a slash as the delimiter. keys.add("delimiter"); values.add("/"); // We don't set the `maxPageSize` for listAll() as this allows Firebase Storage to return // fewer items per page. This removes the need to backfill results if Firebase Storage filters // objects that are considered invalid (such as items with two consecutive slashes). if (maxPageSize != null) { keys.add("maxResults"); values.add(Integer.toString(maxPageSize)); } if (!TextUtils.isEmpty(nextPageToken)) { keys.add("pageToken"); values.add(nextPageToken); } return getPostDataString(keys, values, true); } }
package com.pj0730.demo.po; import java.sql.Date; public class AllInfo { private int dynamicID; private String hostAvatar; private String hostNick; private String createTime; private String mom_textField; private String mom_image; private int hasPraised; private int isCollected; private int isPraised; public AllInfo(int dynamicID, String hostAvatar, String hostNick, String createTime, String mom_textField, String mom_image, int hasPraised, int isCollected, int isPraised) { this.dynamicID = dynamicID; this.hostAvatar = hostAvatar; this.hostNick = hostNick; this.createTime = createTime; this.mom_textField = mom_textField; this.mom_image = mom_image; this.hasPraised = hasPraised; this.isCollected = isCollected; this.isPraised = isPraised; } public int getDynamicID() { return dynamicID; } public void setDynamicID(int dynamicID) { this.dynamicID = dynamicID; } public String getHostAvatar() { return hostAvatar; } public void setHostAvatar(String hostAvatar) { this.hostAvatar = hostAvatar; } public String getHostNick() { return hostNick; } public void setHostNick(String hostNick) { this.hostNick = hostNick; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getMom_textField() { return mom_textField; } public void setMom_textField(String mom_textField) { this.mom_textField = mom_textField; } public String getMom_image() { return mom_image; } public void setMom_image(String mom_image) { this.mom_image = mom_image; } public int getHasPraised() { return hasPraised; } public void setHasPraised(int hasPraised) { this.hasPraised = hasPraised; } public int getIsCollected() { return isCollected; } public void setIsCollected(int isCollected) { this.isCollected = isCollected; } public int getIsPraised() { return isPraised; } public void setIsPraised(int isPraised) { this.isPraised = isPraised; } }
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.setupwizardlib; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Shader.TileMode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; import android.widget.TextView; import com.android.setupwizardlib.template.HeaderMixin; import com.android.setupwizardlib.template.NavigationBarMixin; import com.android.setupwizardlib.template.ProgressBarMixin; import com.android.setupwizardlib.template.RequireScrollMixin; import com.android.setupwizardlib.template.ScrollViewScrollHandlingDelegate; import com.android.setupwizardlib.view.Illustration; import com.android.setupwizardlib.view.NavigationBar; public class SetupWizardLayout extends TemplateLayout { private static final String TAG = "SetupWizardLayout"; public SetupWizardLayout(Context context) { super(context, 0, 0); init(null, R.attr.suwLayoutTheme); } public SetupWizardLayout(Context context, int template) { this(context, template, 0); } public SetupWizardLayout(Context context, int template, int containerId) { super(context, template, containerId); init(null, R.attr.suwLayoutTheme); } public SetupWizardLayout(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, R.attr.suwLayoutTheme); } @TargetApi(VERSION_CODES.HONEYCOMB) public SetupWizardLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } // All the constructors delegate to this init method. The 3-argument constructor is not // available in LinearLayout before v11, so call super with the exact same arguments. private void init(AttributeSet attrs, int defStyleAttr) { registerMixin(HeaderMixin.class, new HeaderMixin(this, attrs, defStyleAttr)); registerMixin(ProgressBarMixin.class, new ProgressBarMixin(this)); registerMixin(NavigationBarMixin.class, new NavigationBarMixin(this)); final RequireScrollMixin requireScrollMixin = new RequireScrollMixin(this); registerMixin(RequireScrollMixin.class, requireScrollMixin); final ScrollView scrollView = getScrollView(); if (scrollView != null) { requireScrollMixin.setScrollHandlingDelegate( new ScrollViewScrollHandlingDelegate(requireScrollMixin, scrollView)); } final TypedArray a = getContext() .obtainStyledAttributes(attrs, R.styleable.SuwSetupWizardLayout, defStyleAttr, 0); // Set the background from XML, either directly or built from a bitmap tile final Drawable background = a.getDrawable(R.styleable.SuwSetupWizardLayout_suwBackground); if (background != null) { setLayoutBackground(background); } else { final Drawable backgroundTile = a.getDrawable(R.styleable.SuwSetupWizardLayout_suwBackgroundTile); if (backgroundTile != null) { setBackgroundTile(backgroundTile); } } // Set the illustration from XML, either directly or built from image + horizontal tile final Drawable illustration = a.getDrawable(R.styleable.SuwSetupWizardLayout_suwIllustration); if (illustration != null) { setIllustration(illustration); } else { final Drawable illustrationImage = a.getDrawable(R.styleable.SuwSetupWizardLayout_suwIllustrationImage); final Drawable horizontalTile = a.getDrawable(R.styleable.SuwSetupWizardLayout_suwIllustrationHorizontalTile); if (illustrationImage != null && horizontalTile != null) { setIllustration(illustrationImage, horizontalTile); } } // Set the top padding of the illustration int decorPaddingTop = a.getDimensionPixelSize(R.styleable.SuwSetupWizardLayout_suwDecorPaddingTop, -1); if (decorPaddingTop == -1) { decorPaddingTop = getResources().getDimensionPixelSize(R.dimen.suw_decor_padding_top); } setDecorPaddingTop(decorPaddingTop); // Set the illustration aspect ratio. See Illustration.setAspectRatio(float). This will // override suwDecorPaddingTop if its value is not 0. float illustrationAspectRatio = a.getFloat(R.styleable.SuwSetupWizardLayout_suwIllustrationAspectRatio, -1f); if (illustrationAspectRatio == -1f) { final TypedValue out = new TypedValue(); getResources().getValue(R.dimen.suw_illustration_aspect_ratio, out, true); illustrationAspectRatio = out.getFloat(); } setIllustrationAspectRatio(illustrationAspectRatio); a.recycle(); } @Override protected Parcelable onSaveInstanceState() { final Parcelable parcelable = super.onSaveInstanceState(); final SavedState ss = new SavedState(parcelable); ss.isProgressBarShown = isProgressBarShown(); return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { Log.w(TAG, "Ignoring restore instance state " + state); super.onRestoreInstanceState(state); return; } final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); final boolean isProgressBarShown = ss.isProgressBarShown; setProgressBarShown(isProgressBarShown); } @Override protected View onInflateTemplate(LayoutInflater inflater, int template) { if (template == 0) { template = R.layout.suw_template; } return inflateTemplate(inflater, R.style.SuwThemeMaterial_Light, template); } @Override protected ViewGroup findContainer(int containerId) { if (containerId == 0) { containerId = R.id.suw_layout_content; } return super.findContainer(containerId); } public NavigationBar getNavigationBar() { return getMixin(NavigationBarMixin.class).getNavigationBar(); } public ScrollView getScrollView() { final View view = findManagedViewById(R.id.suw_bottom_scroll_view); return view instanceof ScrollView ? (ScrollView) view : null; } public void requireScrollToBottom() { final RequireScrollMixin requireScrollMixin = getMixin(RequireScrollMixin.class); final NavigationBar navigationBar = getNavigationBar(); if (navigationBar != null) { requireScrollMixin.requireScrollWithNavigationBar(navigationBar); } else { Log.e(TAG, "Cannot require scroll. Navigation bar is null."); } } public void setHeaderText(int title) { getMixin(HeaderMixin.class).setText(title); } public void setHeaderText(CharSequence title) { getMixin(HeaderMixin.class).setText(title); } public CharSequence getHeaderText() { return getMixin(HeaderMixin.class).getText(); } public TextView getHeaderTextView() { return getMixin(HeaderMixin.class).getTextView(); } /** * Set the illustration of the layout. The drawable will be applied as is, and the bounds will be * set as implemented in {@link com.android.setupwizardlib.view.Illustration}. To create a * suitable drawable from an asset and a horizontal repeating tile, use {@link * #setIllustration(int, int)} instead. * * @param drawable The drawable specifying the illustration. */ public void setIllustration(Drawable drawable) { final View view = findManagedViewById(R.id.suw_layout_decor); if (view instanceof Illustration) { final Illustration illustration = (Illustration) view; illustration.setIllustration(drawable); } } /** * Set the illustration of the layout, which will be created asset and the horizontal tile as * suitable. On phone layouts (not sw600dp), the asset will be scaled, maintaining aspect ratio. * On tablets (sw600dp), the assets will always have 256dp height and the rest of the illustration * area that the asset doesn't fill will be covered by the horizontalTile. * * @param asset Resource ID of the illustration asset. * @param horizontalTile Resource ID of the horizontally repeating tile for tablet layout. */ public void setIllustration(int asset, int horizontalTile) { final View view = findManagedViewById(R.id.suw_layout_decor); if (view instanceof Illustration) { final Illustration illustration = (Illustration) view; final Drawable illustrationDrawable = getIllustration(asset, horizontalTile); illustration.setIllustration(illustrationDrawable); } } private void setIllustration(Drawable asset, Drawable horizontalTile) { final View view = findManagedViewById(R.id.suw_layout_decor); if (view instanceof Illustration) { final Illustration illustration = (Illustration) view; final Drawable illustrationDrawable = getIllustration(asset, horizontalTile); illustration.setIllustration(illustrationDrawable); } } /** * Sets the aspect ratio of the illustration. This will be the space (padding top) reserved above * the header text. This will override the padding top of the illustration. * * @param aspectRatio The aspect ratio * @see com.android.setupwizardlib.view.Illustration#setAspectRatio(float) */ public void setIllustrationAspectRatio(float aspectRatio) { final View view = findManagedViewById(R.id.suw_layout_decor); if (view instanceof Illustration) { final Illustration illustration = (Illustration) view; illustration.setAspectRatio(aspectRatio); } } /** * Set the top padding of the decor view. If the decor is an Illustration and the aspect ratio is * set, this value will be overridden. * * <p>Note: Currently the default top padding for tablet landscape is 128dp, which is the offset * of the card from the top. This is likely to change in future versions so this value aligns with * the height of the illustration instead. * * @param paddingTop The top padding in pixels. */ public void setDecorPaddingTop(int paddingTop) { final View view = findManagedViewById(R.id.suw_layout_decor); if (view != null) { view.setPadding( view.getPaddingLeft(), paddingTop, view.getPaddingRight(), view.getPaddingBottom()); } } /** * Set the background of the layout, which is expected to be able to extend infinitely. If it is a * bitmap tile and you want it to repeat, use {@link #setBackgroundTile(int)} instead. */ public void setLayoutBackground(Drawable background) { final View view = findManagedViewById(R.id.suw_layout_decor); if (view != null) { //noinspection deprecation view.setBackgroundDrawable(background); } } /** * Set the background of the layout to a repeating bitmap tile. To use a different kind of * drawable, use {@link #setLayoutBackground(android.graphics.drawable.Drawable)} instead. */ public void setBackgroundTile(int backgroundTile) { final Drawable backgroundTileDrawable = getContext().getResources().getDrawable(backgroundTile); setBackgroundTile(backgroundTileDrawable); } private void setBackgroundTile(Drawable backgroundTile) { if (backgroundTile instanceof BitmapDrawable) { ((BitmapDrawable) backgroundTile).setTileModeXY(TileMode.REPEAT, TileMode.REPEAT); } setLayoutBackground(backgroundTile); } private Drawable getIllustration(int asset, int horizontalTile) { final Context context = getContext(); final Drawable assetDrawable = context.getResources().getDrawable(asset); final Drawable tile = context.getResources().getDrawable(horizontalTile); return getIllustration(assetDrawable, tile); } @SuppressLint("RtlHardcoded") private Drawable getIllustration(Drawable asset, Drawable horizontalTile) { final Context context = getContext(); if (context.getResources().getBoolean(R.bool.suwUseTabletLayout)) { // If it is a "tablet" (sw600dp), create a LayerDrawable with the horizontal tile. if (horizontalTile instanceof BitmapDrawable) { ((BitmapDrawable) horizontalTile).setTileModeX(TileMode.REPEAT); ((BitmapDrawable) horizontalTile).setGravity(Gravity.TOP); } if (asset instanceof BitmapDrawable) { // Always specify TOP | LEFT, Illustration will flip the entire LayerDrawable. ((BitmapDrawable) asset).setGravity(Gravity.TOP | Gravity.LEFT); } final LayerDrawable layers = new LayerDrawable(new Drawable[] {horizontalTile, asset}); if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { layers.setAutoMirrored(true); } return layers; } else { // If it is a "phone" (not sw600dp), simply return the illustration if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { asset.setAutoMirrored(true); } return asset; } } public boolean isProgressBarShown() { return getMixin(ProgressBarMixin.class).isShown(); } /** * Sets whether the progress bar below the header text is shown or not. The progress bar is a * lazily inflated ViewStub, which means the progress bar will not actually be part of the view * hierarchy until the first time this is set to {@code true}. */ public void setProgressBarShown(boolean shown) { getMixin(ProgressBarMixin.class).setShown(shown); } /** @deprecated Use {@link #setProgressBarShown(boolean)} */ @Deprecated public void showProgressBar() { setProgressBarShown(true); } /** @deprecated Use {@link #setProgressBarShown(boolean)} */ @Deprecated public void hideProgressBar() { setProgressBarShown(false); } public void setProgressBarColor(ColorStateList color) { getMixin(ProgressBarMixin.class).setColor(color); } public ColorStateList getProgressBarColor() { return getMixin(ProgressBarMixin.class).getColor(); } /* Misc */ protected static class SavedState extends BaseSavedState { boolean isProgressBarShown = false; public SavedState(Parcelable parcelable) { super(parcelable); } public SavedState(Parcel source) { super(source); isProgressBarShown = source.readInt() != 0; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(isProgressBarShown ? 1 : 0); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel parcel) { return new SavedState(parcel); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
package algebra; public class BinaryExponentiation { public static long powerRecursive(long a, long b) { if (b == 0) return 1; if ((b & 1) == 1) return a * powerRecursive(a * a, (b - 1) / 2); return powerRecursive(a * a, b / 2); } public static long powerIterative(long a, long b) { long res = 1; while (b > 0) { if ((b & 1) == 1) res = res * a; a *= a; b >>= 1; } return res; } public static long powerMod(long a, long b, long m) { a %= m; long res = 1; while (b > 0) { if ((b & 1) == 1) res = a * a % m; a = a * a % m; b >>= 1; } return res; } public static void main(String[] args) { System.out.println(powerMod(2, 1000, ( ((long)1e9) + 7))); System.out.println(powerIterative(2, 8)); System.out.println(powerRecursive(2, 9)); System.out.println(powerRecursive(2, 10)); } }
package br.usp.each.saeg.baduino.xml; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import java.io.File; import java.net.URL; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class XMLFactoryTests { private static XMLProject project; @BeforeClass public static void setUpBeforeClass() throws Exception { final URL url = XMLFactoryTests.class.getResource("/xml/coverage_test.xml"); final File xml = new File(url.toURI()); project = XMLFactory.getInstance(xml); } @AfterClass public static void tearDownAfterClass() throws Exception { project = null; } @Test public final void testClasses() { final List<XMLClass> classes = project.getClasses(); assertThat(classes, is(notNullValue())); assertThat(classes, hasSize(7)); assertThat(classes, containsInAnyOrder( new XMLClass("br.usp.each.ach2026.AuthManager"), new XMLClass("br.usp.each.ach2026.HtmlGenerator"), new XMLClass("br.usp.each.ach2026.PropertiesManager"), new XMLClass("br.usp.each.ach2026.response.HttpResponse"), new XMLClass("br.usp.each.ach2026.response.HttpResponseFactory"), new XMLClass("br.usp.each.ach2026.response.HttpResponseOkFile"), new XMLClass("br.usp.each.ach2026.WebServer") )); } @Test public final void testMethods() { final List<XMLClass> classes = project.getClasses(); for (final XMLClass clazz : classes) { final List<XMLMethod> methods = clazz.getMethods(); assertThat(methods, is(notNullValue())); assertThat(methods, hasSize(greaterThan(0))); if (clazz.getName().equals("br.usp.each.ach2026.AuthManager")) { assertThat(methods, hasSize(1)); assertThat(methods.get(0).getName(), is("isLogged")); } else if (clazz.getName().equals("br.usp.each.ach2026.HtmlGenerator")) { assertThat(methods, hasSize(2)); for (final XMLMethod method : methods) { assertThat(method.getName(), isOneOf("readableFileSize", "lambda$0")); } } else if (clazz.getName().equals("br.usp.each.ach2026.PropertiesManager")) { assertThat(methods, hasSize(1)); assertThat(methods.get(0).getName(), is("<init>")); } else if (clazz.getName().equals("br.usp.each.ach2026.response.HttpResponse")) { assertThat(methods, hasSize(1)); assertThat(methods.get(0).getName(), is("contentType")); } else if (clazz.getName().equals("br.usp.each.ach2026.response.HttpResponseFactory")) { assertThat(methods, hasSize(2)); for (final XMLMethod method : methods) { assertThat(method.getName(), isOneOf("getResponse", "$SWITCH_TABLE$br$usp$each$ach2026$PropertiesManager$ListingDirectories")); } } else if (clazz.getName().equals("br.usp.each.ach2026.response.HttpResponseOkFile")) { assertThat(methods, hasSize(1)); assertThat(methods.get(0).getName(), is("writeBody")); } else if (clazz.getName().equals("br.usp.each.ach2026.WebServer")) { assertThat(methods, hasSize(1)); assertThat(methods.get(0).getName(), is("main")); } } } }
/* * 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.axis2.transport; import org.apache.axis2.AxisFault; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.SessionContext; import org.apache.axis2.description.TransportInDescription; /** * Class TransportListener */ public interface TransportListener { String PARAM_PORT = "port"; String HOST_ADDRESS = "hostname"; void init(ConfigurationContext axisConf, TransportInDescription transprtIn) throws AxisFault; void start() throws AxisFault; void stop() throws AxisFault; /** * @param serviceName * @param ip * @throws AxisFault * @deprecated Transport listener can expose more than EPRs. So this method should return an array of EPRs. * Deprecating this method for now and please use getEPRsForServices instead. */ EndpointReference getEPRForService(String serviceName, String ip) throws AxisFault; /** * Get the endpoint references for a given service. These are the addresses that a client * can use to send requests to the given service through this transport. * * @param serviceName TODO: this is actually not simply the service name! * @param ip The host name or IP address of the local host. The implementation should use * this information instead of {@link java.net.InetAddress#getLocalHost()}. * The value of this parameter may be <code>null</code>, in which case the * implementation should use {@link org.apache.axis2.util.Utils#getIpAddress( * org.apache.axis2.engine.AxisConfiguration)}. * @return an array of endpoint references for the given service * @throws AxisFault */ EndpointReference[] getEPRsForService(String serviceName, String ip) throws AxisFault; /** * To get the sessionContext transport dependent manner. So that transport listener * can return its own implementation of session managment * * @param messageContext : MessageContext which has all the relavent data * @return SessionContext */ SessionContext getSessionContext(MessageContext messageContext); void destroy(); }
package org.gwtproject.i18n.shared.cldr.impl; import java.lang.Override; import java.lang.String; import javax.annotation.Generated; import org.gwtproject.i18n.shared.cldr.DateTimeFormatInfo; import org.gwtproject.i18n.shared.cldr.LocaleInfoImpl; import org.gwtproject.i18n.shared.cldr.LocalizedNames; import org.gwtproject.i18n.shared.cldr.NumberConstants; @Generated("gwt-cldr-importer : org.gwtproject.tools.cldr.LocalesNativeNamesProcessor, CLDR version : release-34") public class LocaleInfoImpl_en_GB extends LocaleInfoImpl { @Override public String getLocaleName() { return "en_GB"; } @Override public LocalizedNames getLocalizedNames() { return new LocalizedNamesImpl_en_GB(); } @Override public DateTimeFormatInfo getDateTimeFormatInfo() { return new DateTimeFormatInfoImpl_en_GB(); } @Override public NumberConstants getNumberConstants() { return new NumberConstantsImpl_en_GB(); } @Override public boolean isRTL() { return false; } }
/* * Copyright 2019-present HiveMQ GmbH * * 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.hivemq.mqtt.message; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.Striped; import com.hivemq.extension.sdk.api.annotations.NotNull; import com.hivemq.extension.sdk.api.annotations.Nullable; import com.hivemq.configuration.service.InternalConfigurations; import com.hivemq.mqtt.message.pool.MessageIDPool; import com.hivemq.mqtt.message.pool.SequentialMessageIDPoolImpl; import javax.inject.Singleton; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; /** * @author Dominik Obermaier */ @Singleton public class MessageIDPools { private final @NotNull Striped<ReadWriteLock> lock; private final @NotNull ConcurrentHashMap<String, MessageIDPool> producers = new ConcurrentHashMap<>(); MessageIDPools() { //Do not instantiate manually lock = Striped.readWriteLock(InternalConfigurations.MESSAGE_ID_PRODUCER_LOCK_SIZE.get()); } /** * Returns the {@link MessageIDPool} for a client. If there is no message id pool available for the client, * it will create anew message id pool for that client. * * @param client the client to return the message id pool for * @return a {@link MessageIDPool} implementation */ @NotNull public MessageIDPool forClient(final @NotNull String client) { // A read lock is sufficient here, since we never override an entry with ConcurrentHashMap:putIfAbsent(). final Lock readLock = this.lock.get(client).readLock(); readLock.lock(); try { MessageIDPool idProducer = producers.get(client); //The following code is an optimization so we don't have to create //a new object everytime. In worst case we create unnecessary //objects only if we have a race condition if (idProducer == null) { producers.putIfAbsent(client, new SequentialMessageIDPoolImpl()); idProducer = producers.get(client); } return idProducer; } finally { readLock.unlock(); } } /** * Returns the {@link MessageIDPool} for a client or null, if there is no message id pool available for the client. * * @param client the client to return the message id pool for * @return a {@link MessageIDPool} implementation */ @Nullable public MessageIDPool forClientOrNull(final @NotNull String client) { // A read lock is sufficient here, since we never override an entry with ConcurrentHashMap:putIfAbsent(). final Lock readLock = this.lock.get(client).readLock(); readLock.lock(); try { return producers.get(client); } finally { readLock.unlock(); } } public void remove(final @NotNull String client) { final Lock writeLock = this.lock.get(client).writeLock(); writeLock.lock(); try { producers.remove(client); } finally { writeLock.unlock(); } } @VisibleForTesting int size() { return producers.size(); } }
/* 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.activiti.bpmn.model; /** * @author Tijs Rademakers */ public class MessageEventDefinition extends EventDefinition { protected String messageRef; public String getMessageRef() { return messageRef; } public void setMessageRef(String messageRef) { this.messageRef = messageRef; } }
package com.almis.awe.test.unit.hsql; import com.almis.awe.test.unit.database.DirectServiceCallTest; import com.almis.awe.test.unit.database.MaintainTest; import com.almis.awe.test.unit.database.QueryTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ MaintainTest.class, QueryTest.class, HsqlPerformanceTestsSuite.class, DirectServiceCallTest.class }) public class SpringHsqlTestsSuite { }
/* * Copyright 2016-2021 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.certificatemanager.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.certificatemanager.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * CertificateOptionsMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class CertificateOptionsMarshaller { private static final MarshallingInfo<String> CERTIFICATETRANSPARENCYLOGGINGPREFERENCE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CertificateTransparencyLoggingPreference").build(); private static final CertificateOptionsMarshaller instance = new CertificateOptionsMarshaller(); public static CertificateOptionsMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(CertificateOptions certificateOptions, ProtocolMarshaller protocolMarshaller) { if (certificateOptions == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(certificateOptions.getCertificateTransparencyLoggingPreference(), CERTIFICATETRANSPARENCYLOGGINGPREFERENCE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
/* * Copyright 2003 - 2010 The eFaps Team * * 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.esjp.sales.document; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; /** * This class must be replaced for customization, therefore it is left empty. * Functional description can be found in the related "<code>_base</code>" * class. * * @author The eFaps Team * */ @EFapsUUID("f3252401-2007-4ff3-997d-5e5d1a7ab863") @EFapsApplication("eFapsApp-Sales") public class UsageReport extends UsageReport_Base { }
package hud; public class SlopeLines { public float[] vertices; public int[] indices; public float[] normals; public SlopeLines() { } }
package pl.sdacademy.java16poz.testowanietdd.calculator; /** * Calculator * * @author: Jakub Olszewski [hintintp://github.com/jakub-olszewski] * @date: 16.06.2019 11:34 **/ public interface Calculator { /** * Metoda wprowadza znak z argumenintu na wyświeintlacz, ale nie wyświeintla * @param number */ void pressNumber(Object number); /** * Metoda wyświeintla zawarintość wyświeintlacza * @reinturn zawarintość wyświeintlacza */ String display(); /** * Metoda czyści wyświetlacz */ void clear(); /** * Metoda dodaje number1 do number2 * @param number1 liczba pierwsza * @param number2 liczba druga */ void add(int number1, int number2); /** * Metoda odejmuje number1 od number2 * @param number1 * @param number2 */ void sub(int number1, int number2); /** * Metoda dzieli number1 przez number2 * @param number1 * @param number2 */ void div(int number1, int number2); /** * Metoda mnoży number1 przez number2 * @param number1 * @param number2 */ void multi(int number1, int number2); }
/* * Copyright 2017 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.migration.eap6.to.eap7.tasks; import org.jboss.migration.core.jboss.JBossSubsystemNames; import org.jboss.migration.wfly11.task.subsystem.undertow.AddHttpInvoker; import org.jboss.migration.wfly10.config.task.management.subsystem.UpdateSubsystemResources; import org.jboss.migration.wfly10.config.task.subsystem.undertow.AddHttpsListener; import org.jboss.migration.wfly10.config.task.subsystem.undertow.AddWebsockets; import org.jboss.migration.wfly10.config.task.subsystem.undertow.EnableHttp2; import org.jboss.migration.wfly10.config.task.subsystem.undertow.SetDefaultHostResponseHeaderServer; import org.jboss.migration.wfly10.config.task.subsystem.undertow.SetDefaultHostResponseHeaderXPoweredBy; import org.jboss.migration.wfly10.config.task.subsystem.undertow.SetDefaultHttpListenerRedirectSocket; /** * @author emmartins */ public class EAP6_4ToEAP7_1UpdateUndertowSubsystem<S> extends UpdateSubsystemResources<S> { public EAP6_4ToEAP7_1UpdateUndertowSubsystem() { super(JBossSubsystemNames.UNDERTOW, new SetDefaultHttpListenerRedirectSocket<>("http"), new AddWebsockets<>(), new AddHttpsListener<>(), new EnableHttp2<>(), new SetDefaultHostResponseHeaderServer<>(), new SetDefaultHostResponseHeaderXPoweredBy<>(), new AddHttpInvoker<>()); } }
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.deeplearning4j.nn.modelimport.keras.layers.embeddings; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; import org.deeplearning4j.nn.modelimport.keras.KerasLayer; import org.deeplearning4j.nn.modelimport.keras.exceptions.InvalidKerasConfigurationException; import org.deeplearning4j.nn.modelimport.keras.exceptions.UnsupportedKerasConfigurationException; import org.deeplearning4j.nn.api.layers.LayerConstraint; import org.deeplearning4j.nn.conf.InputPreProcessor; import org.deeplearning4j.nn.conf.inputs.InputType; import org.deeplearning4j.nn.conf.layers.EmbeddingLayer; import org.deeplearning4j.nn.modelimport.keras.utils.KerasConstraintUtils; import org.deeplearning4j.nn.modelimport.keras.utils.KerasInitilizationUtils; import org.deeplearning4j.nn.modelimport.keras.utils.KerasLayerUtils; import org.deeplearning4j.nn.params.DefaultParamInitializer; import org.deeplearning4j.nn.weights.IWeightInit; import org.nd4j.linalg.activations.Activation; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Imports an Embedding layer from Keras. * * @author dave@skymind.io */ @Slf4j @Data @EqualsAndHashCode(callSuper = false) public class Keras2DEmbedding extends KerasLayer { private final int NUM_TRAINABLE_PARAMS = 1; private boolean zeroMasking; private int inputDim; private int inputLength; private boolean inferInputLength; /** * Pass through constructor for unit tests * * @throws UnsupportedKerasConfigurationException Unsupported Keras config */ public Keras2DEmbedding() throws UnsupportedKerasConfigurationException { } /** * Constructor from parsed Keras layer configuration dictionary. * * @param layerConfig dictionary containing Keras layer configuration * @throws InvalidKerasConfigurationException Invalid Keras config * @throws UnsupportedKerasConfigurationException Unsupported Keras config */ public Keras2DEmbedding(Map<String, Object> layerConfig) throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException { this(layerConfig, true); } /** * Constructor from parsed Keras layer configuration dictionary. * * @param layerConfig dictionary containing Keras layer configuration * @param enforceTrainingConfig whether to enforce training-related configuration options * @throws InvalidKerasConfigurationException Invalid Keras config * @throws UnsupportedKerasConfigurationException Unsupported Keras config */ public Keras2DEmbedding(Map<String, Object> layerConfig, boolean enforceTrainingConfig) throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException { super(layerConfig, enforceTrainingConfig); this.inputDim = getInputDimFromConfig(layerConfig); this.inputLength = getInputLengthFromConfig(layerConfig); this.inferInputLength = this.inputLength == 0; if (this.inferInputLength) this.inputLength = 1; // set dummy value, so shape inference works this.zeroMasking = KerasLayerUtils.getZeroMaskingFromConfig(layerConfig, conf); if (zeroMasking) log.warn("Masking in keras and DL4J work differently. We do not completely support mask_zero flag " + "on Embedding layers. Zero Masking for the Embedding layer only works with unidirectional LSTM for now." + " If you want to have this behaviour for your imported model " + "in DL4J, apply masking as a pre-processing step to your input." + "See https://deeplearning4j.konduit.ai/models/recurrent#masking-one-to-many-many-to-one-and-sequence-classification for more on this."); IWeightInit init = KerasInitilizationUtils.getWeightInitFromConfig(layerConfig, conf.getLAYER_FIELD_EMBEDDING_INIT(), enforceTrainingConfig, conf, kerasMajorVersion); LayerConstraint embeddingConstraint = KerasConstraintUtils.getConstraintsFromConfig( layerConfig, conf.getLAYER_FIELD_EMBEDDINGS_CONSTRAINT(), conf, kerasMajorVersion); int nOutFromConfig = KerasLayerUtils.getNOutFromConfig(layerConfig, conf); EmbeddingLayer.Builder builder = new EmbeddingLayer.Builder() .name(this.layerName) .nIn(inputDim) .nOut(nOutFromConfig) .dropOut(this.dropout).activation(Activation.IDENTITY) .weightInit(init) .biasInit(0.0) .l1(this.weightL1Regularization) .l2(this.weightL2Regularization) .hasBias(false); if (embeddingConstraint != null) builder.constrainWeights(embeddingConstraint); this.layer = builder.build(); this.inputShape = new int[]{inputDim,1}; } /** * Get DL4J Embedding Sequence layer. * * @return Embedding Sequence layer */ public EmbeddingLayer getEmbeddingLayer() { return (EmbeddingLayer) this.layer; } /** * Get layer output type. * * @param inputType Array of InputTypes * @return output type as InputType * @throws InvalidKerasConfigurationException Invalid Keras config */ @Override public InputType getOutputType(InputType... inputType) throws InvalidKerasConfigurationException { /* Check whether layer requires a preprocessor for this InputType. */ InputPreProcessor preprocessor = getInputPreprocessor(inputType[0]); if (preprocessor != null) { return this.getEmbeddingLayer().getOutputType(-1, preprocessor.getOutputType(inputType[0])); } return this.getEmbeddingLayer().getOutputType(-1, inputType[0]); } /** * Returns number of trainable parameters in layer. * * @return number of trainable parameters (1) */ @Override public int getNumParams() { return NUM_TRAINABLE_PARAMS; } /** * Set weights for layer. * * @param weights Embedding layer weights */ @Override public void setWeights(Map<String, INDArray> weights) throws InvalidKerasConfigurationException { this.weights = new HashMap<>(); // TODO: "embeddings" is incorrectly read as "s" for some applications if (weights.containsKey("s")) { INDArray kernel = weights.get("s"); weights.remove("s"); weights.put(conf.getLAYER_FIELD_EMBEDDING_WEIGHTS(), kernel); } if (!weights.containsKey(conf.getLAYER_FIELD_EMBEDDING_WEIGHTS())) throw new InvalidKerasConfigurationException( "Parameter " + conf.getLAYER_FIELD_EMBEDDING_WEIGHTS() + " does not exist in weights"); INDArray kernel = weights.get(conf.getLAYER_FIELD_EMBEDDING_WEIGHTS()); if (this.zeroMasking) { kernel.putRow(0, Nd4j.zeros(kernel.columns())); } this.weights.put(DefaultParamInitializer.WEIGHT_KEY, kernel); if (weights.size() > 2) { Set<String> paramNames = weights.keySet(); paramNames.remove(conf.getLAYER_FIELD_EMBEDDING_WEIGHTS()); String unknownParamNames = paramNames.toString(); log.warn("Attempting to set weights for unknown parameters: " + unknownParamNames.substring(1, unknownParamNames.length() - 1)); } } /** * Get Keras input length from Keras layer configuration. In Keras input_length, if present, denotes * the number of indices to embed per mini-batch, i.e. input will be of shape (mb, input_length) * and (mb, 1) else. * * @param layerConfig dictionary containing Keras layer configuration * @return input length as int */ private int getInputLengthFromConfig(Map<String, Object> layerConfig) throws InvalidKerasConfigurationException { Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf); if (!innerConfig.containsKey(conf.getLAYER_FIELD_INPUT_LENGTH())) throw new InvalidKerasConfigurationException( "Keras Embedding layer config missing " + conf.getLAYER_FIELD_INPUT_LENGTH() + " field"); if (innerConfig.get(conf.getLAYER_FIELD_INPUT_LENGTH()) == null) { return 0; } else { return (int) innerConfig.get(conf.getLAYER_FIELD_INPUT_LENGTH()); } } /** * Get Keras input dimension from Keras layer configuration. * * @param layerConfig dictionary containing Keras layer configuration * @return input dim as int */ private int getInputDimFromConfig(Map<String, Object> layerConfig) throws InvalidKerasConfigurationException { Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf); if (!innerConfig.containsKey(conf.getLAYER_FIELD_INPUT_DIM())) throw new InvalidKerasConfigurationException( "Keras Embedding layer config missing " + conf.getLAYER_FIELD_INPUT_DIM() + " field"); return (int) innerConfig.get(conf.getLAYER_FIELD_INPUT_DIM()); } }
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.frameworks.connectors.properties.beans; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * ValidValueSet defines a collection of valid value definitions. The members of the collection are * not nested directly in this object because there could be many hundreds of definition values in a set. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public class ValidValueSet extends ValidValue { private static final long serialVersionUID = 1L; /** * Constructor */ public ValidValueSet() { super(); } /** * Copy/clone constructor * * @param template object to copy */ public ValidValueSet(ValidValueSet template) { super(template); } /** * Generate a string containing the properties. * * @return string value */ @Override public String toString() { return "ValidValueSet{" + "displayName='" + displayName + '\'' + ", description='" + description + '\'' + ", usage='" + usage + '\'' + ", scope='" + scope + '\'' + ", preferredValue='" + preferredValue + '\'' + ", qualifiedName='" + qualifiedName + '\'' + ", additionalProperties=" + additionalProperties + ", meanings=" + meanings + ", type=" + type + ", guid='" + guid + '\'' + ", url='" + url + '\'' + ", classifications=" + classifications + ", extendedProperties=" + extendedProperties + '}'; } }
package com.tools20022.repogenerator.resulttypes; import javax.xml.bind.annotation.XmlElement; import org.jboss.forge.roaster.model.source.AnnotationSource; import org.jboss.forge.roaster.model.source.JavaClassSource; import com.tools20022.generators.StructuredName; import com.tools20022.metamodel.MMMessageConstruct; public class JaxbPropertyResult extends PropertyResult { JaxbPropertyResult(JaxbMainTypeResult containerGen, MMMessageConstruct mmBean) { super(containerGen, mmBean); } @Override public void flush() { super.flush(); MMMessageConstruct mmMsgConstruct = (MMMessageConstruct)mmBean; AnnotationSource<JavaClassSource> jaxbAnnot = beanFieldSrc.addAnnotation(XmlElement.class); jaxbAnnot.setStringValue("name", mmMsgConstruct.getXmlTag().get()); if( mmMsgConstruct.getMinOccurs().orElse(0) > 0 ) { jaxbAnnot.setLiteralValue("required", "true"); } ((JaxbMainTypeResult)containerGen).propOrder.add(beanFieldSrc.getName()); } }
package org.apache.solr.rest.schema; /* * 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. */ import org.apache.commons.io.FileUtils; import org.apache.solr.util.RestTestBase; import org.eclipse.jetty.servlet.ServletHolder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.restlet.ext.servlet.ServerServlet; import java.io.File; import java.util.SortedMap; import java.util.TreeMap; import java.util.regex.Pattern; public class TestManagedSchemaDynamicFieldResource extends RestTestBase { private static File tmpSolrHome; private static File tmpConfDir; private static final String collection = "collection1"; private static final String confDir = collection + "/conf"; @Before public void before() throws Exception { tmpSolrHome = createTempDir().toFile(); tmpConfDir = new File(tmpSolrHome, confDir); FileUtils.copyDirectory(new File(TEST_HOME()), tmpSolrHome.getAbsoluteFile()); final SortedMap<ServletHolder,String> extraServlets = new TreeMap<>(); final ServletHolder solrRestApi = new ServletHolder("SolrSchemaRestApi", ServerServlet.class); solrRestApi.setInitParameter("org.restlet.application", "org.apache.solr.rest.SolrSchemaRestApi"); extraServlets.put(solrRestApi, "/schema/*"); // '/schema/*' matches '/schema', '/schema/', and '/schema/whatever...' System.setProperty("managed.schema.mutable", "true"); System.setProperty("enable.update.log", "false"); createJettyAndHarness(tmpSolrHome.getAbsolutePath(), "solrconfig-managed-schema.xml", "schema-rest.xml", "/solr", true, extraServlets); } @After public void after() throws Exception { if (jetty != null) { jetty.stop(); jetty = null; } client = null; if (restTestHarness != null) { restTestHarness.close(); } restTestHarness = null; } @Test public void testAddDynamicFieldBadFieldType() throws Exception { assertJPut("/schema/dynamicfields/*_newdynamicfield", json( "{'type':'not_in_there_at_all','stored':false}" ), "/error/msg==\"Dynamic field \\'*_newdynamicfield\\': Field type \\'not_in_there_at_all\\' not found.\""); } @Test public void testAddDynamicFieldMismatchedName() throws Exception { assertJPut("/schema/dynamicfields/*_newdynamicfield", json( "{'name':'*_something_else','type':'text','stored':false}" ), "/error/msg=='///regex:\\\\*_newdynamicfield///'"); } @Test public void testAddDynamicFieldBadProperty() throws Exception { assertJPut("/schema/dynamicfields/*_newdynamicfield", json( "{'type':'text','no_property_with_this_name':false}" ), "/error/msg==\"java.lang.IllegalArgumentException: Invalid field property: no_property_with_this_name\""); } @Test public void testAddDynamicField() throws Exception { assertQ("/schema/dynamicfields/newdynamicfield_*?indent=on&wt=xml", "count(/response/lst[@name='newdynamicfield_*']) = 0", "/response/lst[@name='responseHeader']/int[@name='status'] = '404'", "/response/lst[@name='error']/int[@name='code'] = '404'"); assertJPut("/schema/dynamicfields/newdynamicfield_*", json("{'type':'text','stored':false}"), "/responseHeader/status==0"); assertQ("/schema/dynamicfields/newdynamicfield_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 1", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'"); assertU(adoc("newdynamicfield_A", "value1 value2", "id", "123")); assertU(commit()); assertQ("/select?q=newdynamicfield_A:value1", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'", "/response/result[@name='response'][@numFound='1']", "count(/response/result[@name='response']/doc/*) = 1", "/response/result[@name='response']/doc/str[@name='id'][.='123']"); } @Test public void testAddDynamicFieldWithMulipleOptions() throws Exception { assertQ("/schema/dynamicfields/newdynamicfield_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 0", "/response/lst[@name='responseHeader']/int[@name='status'] = '404'", "/response/lst[@name='error']/int[@name='code'] = '404'"); assertJPut("/schema/dynamicfields/newdynamicfield_*", json("{'type':'text_en','stored':true,'indexed':false}"), "/responseHeader/status==0"); File managedSchemaFile = new File(tmpConfDir, "managed-schema"); assertTrue(managedSchemaFile.exists()); String managedSchemaContents = FileUtils.readFileToString(managedSchemaFile, "UTF-8"); Pattern newdynamicfieldStoredTrueIndexedFalsePattern = Pattern.compile( "<dynamicField name=\"newdynamicfield_\\*\" type=\"text_en\"" + "(?=.*stored=\"true\")(?=.*indexed=\"false\").*/>"); assertTrue(newdynamicfieldStoredTrueIndexedFalsePattern.matcher(managedSchemaContents).find()); assertQ("/schema/dynamicfields/newdynamicfield_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 1", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'", "/response/lst[@name='dynamicField']/str[@name='name'] = 'newdynamicfield_*'", "/response/lst[@name='dynamicField']/str[@name='type'] = 'text_en'", "/response/lst[@name='dynamicField']/bool[@name='indexed'] = 'false'", "/response/lst[@name='dynamicField']/bool[@name='stored'] = 'true'"); assertU(adoc("newdynamicfield_A", "value1 value2", "id", "1234")); assertU(commit()); assertQ("/schema/dynamicfields/newdynamicfield2_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 0", "/response/lst[@name='responseHeader']/int[@name='status'] = '404'", "/response/lst[@name='error']/int[@name='code'] = '404'"); assertJPut("/schema/dynamicfields/newdynamicfield2_*", json("{'type':'text_en','stored':true,'indexed':true,'multiValued':true}"), "/responseHeader/status==0"); managedSchemaContents = FileUtils.readFileToString(managedSchemaFile, "UTF-8"); Pattern newdynamicfield2StoredTrueIndexedTrueMultiValuedTruePattern = Pattern.compile( "<dynamicField name=\"newdynamicfield2_\\*\" type=\"text_en\" " + "(?=.*stored=\"true\")(?=.*indexed=\"true\")(?=.*multiValued=\"true\").*/>"); assertTrue(newdynamicfield2StoredTrueIndexedTrueMultiValuedTruePattern.matcher(managedSchemaContents).find()); assertQ("/schema/dynamicfields/newdynamicfield2_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 1", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'", "/response/lst[@name='dynamicField']/str[@name='name'] = 'newdynamicfield2_*'", "/response/lst[@name='dynamicField']/str[@name='type'] = 'text_en'", "/response/lst[@name='dynamicField']/bool[@name='indexed'] = 'true'", "/response/lst[@name='dynamicField']/bool[@name='stored'] = 'true'", "/response/lst[@name='dynamicField']/bool[@name='multiValued'] = 'true'"); assertU(adoc("newdynamicfield2_A", "value1 value2", "newdynamicfield2_A", "value3 value4", "id", "5678")); assertU(commit()); assertQ("/select?q=newdynamicfield2_A:value3", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'", "/response/result[@name='response'][@numFound='1']", "count(/response/result[@name='response']/doc) = 1", "/response/result[@name='response']/doc/str[@name='id'][.='5678']"); } @Test public void testAddDynamicFieldCollectionWithMultipleOptions() throws Exception { assertQ("/schema/dynamicfields?indent=on&wt=xml", "count(/response/arr[@name='dynamicFields']/lst/str[@name]) > 0", // there are fields "count(/response/arr[@name='dynamicFields']/lst/str[starts-with(@name,'newfield')]) = 0"); // but none named newfield* assertJPost("/schema/dynamicfields", json("[{'name':'newdynamicfield_*','type':'text_en','stored':true,'indexed':false}]"), "/responseHeader/status==0"); File managedSchemaFile = new File(tmpConfDir, "managed-schema"); assertTrue(managedSchemaFile.exists()); String managedSchemaContents = FileUtils.readFileToString(managedSchemaFile, "UTF-8"); Pattern newfieldStoredTrueIndexedFalsePattern = Pattern.compile( "<dynamicField name=\"newdynamicfield_\\*\" type=\"text_en\"" + "(?=.*stored=\"true\")(?=.*indexed=\"false\").*/>"); assertTrue(newfieldStoredTrueIndexedFalsePattern.matcher(managedSchemaContents).find()); assertQ("/schema/dynamicfields?indent=on&wt=xml", "/response/arr[@name='dynamicFields']/lst" + "[str[@name='name']='newdynamicfield_*' and str[@name='type']='text_en'" + " and bool[@name='stored']='true' and bool[@name='indexed']='false']"); assertU(adoc("newdynamicfield_A", "value1 value2", "id", "789")); assertU(commit()); assertJPost("/schema/dynamicfields", json("[{'name':'newdynamicfield2_*','type':'text_en','stored':true,'indexed':true,'multiValued':true}]"), "/responseHeader/status==0"); managedSchemaContents = FileUtils.readFileToString(managedSchemaFile, "UTF-8"); Pattern newdynamicfield2StoredTrueIndexedTrueMultiValuedTruePattern = Pattern.compile( "<dynamicField name=\"newdynamicfield2_\\*\" type=\"text_en\" " + "(?=.*stored=\"true\")(?=.*indexed=\"true\")(?=.*multiValued=\"true\").*/>"); assertTrue(newdynamicfield2StoredTrueIndexedTrueMultiValuedTruePattern.matcher(managedSchemaContents).find()); assertQ("/schema/dynamicfields?indent=on&wt=xml", "/response/arr[@name='dynamicFields']/lst" + "[str[@name='name']='newdynamicfield2_*' and str[@name='type']='text_en'" + " and bool[@name='stored']='true' and bool[@name='indexed']='true' and bool[@name='multiValued']='true']"); assertU(adoc("newdynamicfield2_A", "value1 value2", "newdynamicfield2_A", "value3 value4", "id", "790")); assertU(commit()); assertQ("/select?q=newdynamicfield2_A:value3", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'", "/response/result[@name='response'][@numFound='1']", "count(/response/result[@name='response']/doc) = 1", "/response/result[@name='response']/doc/str[@name='id'][.='790']"); } @Test public void testAddCopyField() throws Exception { assertQ("/schema/dynamicfields/newdynamicfield2_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 0", "/response/lst[@name='responseHeader']/int[@name='status'] = '404'", "/response/lst[@name='error']/int[@name='code'] = '404'"); assertJPut("/schema/dynamicfields/dynamicfieldA_*", json("{'type':'text','stored':false}"), "/responseHeader/status==0"); assertJPut("/schema/dynamicfields/dynamicfieldB_*", json("{'type':'text','stored':false, 'copyFields':['dynamicfieldA_*']}"), "/responseHeader/status==0"); assertJPut("/schema/dynamicfields/dynamicfieldC_*", json("{'type':'text','stored':false, 'copyFields':'dynamicfieldA_*'}"), "/responseHeader/status==0"); assertQ("/schema/dynamicfields/dynamicfieldB_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 1", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'"); assertQ("/schema/copyfields/?indent=on&wt=xml&source.fl=dynamicfieldB_*", "count(/response/arr[@name='copyFields']/lst) = 1"); assertQ("/schema/copyfields/?indent=on&wt=xml&source.fl=dynamicfieldC_*", "count(/response/arr[@name='copyFields']/lst) = 1"); //fine to pass in empty list, just won't do anything assertJPut("/schema/dynamicfields/dynamicfieldD_*", json("{'type':'text','stored':false, 'copyFields':[]}"), "/responseHeader/status==0"); //some bad usages assertJPut("/schema/dynamicfields/dynamicfieldF_*", json("{'type':'text','stored':false, 'copyFields':['some_nonexistent_dynamicfield_ignore_exception_*']}"), "/error/msg==\"copyField dest :\\'some_nonexistent_dynamicfield_ignore_exception_*\\' is not an explicit field and doesn\\'t match a dynamicField.\""); } @Test public void testPostMultipleDynamicFields() throws Exception { assertQ("/schema/dynamicfields/newdynamicfield1_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 0", "/response/lst[@name='responseHeader']/int[@name='status'] = '404'", "/response/lst[@name='error']/int[@name='code'] = '404'"); assertQ("/schema/dynamicfields/newdynamicfield2_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 0", "/response/lst[@name='responseHeader']/int[@name='status'] = '404'", "/response/lst[@name='error']/int[@name='code'] = '404'"); assertJPost("/schema/dynamicfields", json( "[{'name':'newdynamicfield1_*','type':'text','stored':false}," + " {'name':'newdynamicfield2_*','type':'text','stored':false}]"), "/responseHeader/status==0"); assertQ("/schema/dynamicfields/newdynamicfield1_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 1", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'"); assertQ("/schema/dynamicfields/newdynamicfield2_*?indent=on&wt=xml", "count(/response/lst[@name='dynamicField']) = 1", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'"); assertU(adoc("newdynamicfield1_A", "value1 value2", "id", "123")); assertU(adoc("newdynamicfield2_A", "value3 value4", "id", "456")); assertU(commit()); assertQ("/select?q=newdynamicfield1_A:value1", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'", "/response/result[@name='response'][@numFound='1']", "count(/response/result[@name='response']/doc/*) = 1", "/response/result[@name='response']/doc/str[@name='id'][.='123']"); assertQ("/select?q=newdynamicfield2_A:value3", "/response/lst[@name='responseHeader']/int[@name='status'] = '0'", "/response/result[@name='response'][@numFound='1']", "count(/response/result[@name='response']/doc/*) = 1", "/response/result[@name='response']/doc/str[@name='id'][.='456']"); } @Test public void testPostCopy() throws Exception { assertJPost("/schema/dynamicfields", json( "[{'name':'dynamicfieldA_*','type':'text','stored':false}," + " {'name':'dynamicfieldB_*','type':'text','stored':false}," + " {'name':'dynamicfieldC_*','type':'text','stored':false, 'copyFields':['dynamicfieldB_*']}]"), "/responseHeader/status==0"); assertQ("/schema/copyfields/?indent=on&wt=xml&source.fl=dynamicfieldC_*", "count(/response/arr[@name='copyFields']/lst) = 1"); assertJPost("/schema/dynamicfields", json( "[{'name':'dynamicfieldD_*','type':'text','stored':false}," + " {'name':'dynamicfieldE_*','type':'text','stored':false}," + " {'name':'dynamicfieldF_*','type':'text','stored':false, 'copyFields':['dynamicfieldD_*','dynamicfieldE_*']}," + " {'name':'dynamicfieldG_*','type':'text','stored':false, 'copyFields':'dynamicfieldD_*'}]"),//single "/responseHeader/status==0"); assertQ("/schema/copyfields/?indent=on&wt=xml&source.fl=dynamicfieldF_*", "count(/response/arr[@name='copyFields']/lst) = 2"); //passing in an empty list is perfectly acceptable, it just won't do anything assertJPost("/schema/dynamicfields", json( "[{'name':'dynamicfieldX_*','type':'text','stored':false}," + " {'name':'dynamicfieldY_*','type':'text','stored':false}," + " {'name':'dynamicfieldZ_*','type':'text','stored':false, 'copyFields':[]}]"), "/responseHeader/status==0"); //some bad usages assertJPost("/schema/dynamicfields", json( "[{'name':'dynamicfieldH_*','type':'text','stored':false}," + " {'name':'dynamicfieldI_*','type':'text','stored':false}," + " {'name':'dynamicfieldJ_*','type':'text','stored':false, 'copyFields':['some_nonexistent_dynamicfield_ignore_exception_*']}]"), "/error/msg=='copyField dest :\\'some_nonexistent_dynamicfield_ignore_exception_*\\' is not an explicit field and doesn\\'t match a dynamicField.'"); } @Test public void testPostCopyFields() throws Exception { assertJPost("/schema/dynamicfields", json( "[{'name':'dynamicfieldA_*','type':'text','stored':false}," + " {'name':'dynamicfieldB_*','type':'text','stored':false}," + " {'name':'dynamicfieldC_*','type':'text','stored':false}," + " {'name':'dynamicfieldD_*','type':'text','stored':false}," + " {'name':'dynamicfieldE_*','type':'text','stored':false}]"), "/responseHeader/status==0"); assertJPost("/schema/copyfields", json( "[{'source':'dynamicfieldA_*', 'dest':'dynamicfieldB_*'}," + " {'source':'dynamicfieldD_*', 'dest':['dynamicfieldC_*', 'dynamicfieldE_*']}]"), "/responseHeader/status==0"); assertQ("/schema/copyfields/?indent=on&wt=xml&source.fl=dynamicfieldA_*", "count(/response/arr[@name='copyFields']/lst) = 1"); assertQ("/schema/copyfields/?indent=on&wt=xml&source.fl=dynamicfieldD_*", "count(/response/arr[@name='copyFields']/lst) = 2"); assertJPost("/schema/copyfields", // copyField glob sources are not required to match a dynamic field json("[{'source':'some_glob_not_necessarily_matching_any_dynamicfield_*', 'dest':['dynamicfieldA_*']}," +" {'source':'*', 'dest':['dynamicfieldD_*']}]"), "/responseHeader/status==0"); assertJPost("/schema/copyfields", json("[{'source':'dynamicfieldD_*', 'dest':['some_nonexistent_dynamicfield_ignore_exception_*']}]"), "/error/msg=='copyField dest :\\'some_nonexistent_dynamicfield_ignore_exception_*\\' is not an explicit field and doesn\\'t match a dynamicField.'"); } }
/******************************************************************************* * Copyright (c) 1991, 2021 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ /** * WARNING!!! GENERATED FILE * * This class is generated. * Do not use the Eclipse "Organize Imports" feature on this class. * * It can contain user content, but that content must be delimited with the * the tags * [BEGIN USER IMPORTS] * [END USER IMPORTS] * * or * * [BEGIN USER CODE] * [END USER CODE] * * These tags are entered as comments. Characters before [ and after ] are ignored. * Lines between the tags are inserted into the newly generated file. * * IMPORTS are combined and inserted above newly generated imports. CODE is combined * and inserted immediately after the class declaration * * All lines outside these tags are lost and replaced with newly generated code. */ package com.ibm.j9ddr.vm29.pointer.generated; /*[BEGIN USER IMPORTS]*/ /*[END USER IMPORTS]*/ import com.ibm.j9ddr.vm29.pointer.*; import com.ibm.j9ddr.vm29.structure.*; import com.ibm.j9ddr.vm29.types.*; /** * Structure: J9VMRuntimeFlagsPointer * * A generated implementation of a VM structure * * This class contains generated code and MAY contain hand written user code. * * Hand written user code must be contained at the top of * the class file, specifically above * the comment line containing WARNING!!! GENERATED CODE * * ALL code below the GENERATED warning will be replaced with new generated code * each time the PointerGenerator utility is run. * * The generated code will provide getters for all elements in the J9VMRuntimeFlagsPointer * structure. Where possible, meaningful return types are inferred. * * The user may add methods to provide meaningful return types where only pointers * could be automatically inferred. */ @com.ibm.j9ddr.GeneratedPointerClass(structureClass=J9VMRuntimeFlags.class) public class J9VMRuntimeFlagsPointer extends StructurePointer { // NULL public static final J9VMRuntimeFlagsPointer NULL = new J9VMRuntimeFlagsPointer(0); /*[BEGIN USER CODE]*/ /*[END USER CODE]*/ // Do not call this constructor. Use static method cast instead. protected J9VMRuntimeFlagsPointer(long address) { super(address); } public static J9VMRuntimeFlagsPointer cast(AbstractPointer structure) { return cast(structure.getAddress()); } public static J9VMRuntimeFlagsPointer cast(UDATA udata) { return cast(udata.longValue()); } public static J9VMRuntimeFlagsPointer cast(long address) { if (address == 0) { return NULL; } return new J9VMRuntimeFlagsPointer(address); } public J9VMRuntimeFlagsPointer add(long count) { return J9VMRuntimeFlagsPointer.cast(address + (J9VMRuntimeFlags.SIZEOF * count)); } public J9VMRuntimeFlagsPointer add(Scalar count) { return add(count.longValue()); } public J9VMRuntimeFlagsPointer addOffset(long offset) { return J9VMRuntimeFlagsPointer.cast(address + offset); } public J9VMRuntimeFlagsPointer addOffset(Scalar offset) { return addOffset(offset.longValue()); } public J9VMRuntimeFlagsPointer sub(long count) { return J9VMRuntimeFlagsPointer.cast(address - (J9VMRuntimeFlags.SIZEOF * count)); } public J9VMRuntimeFlagsPointer sub(Scalar count) { return sub(count.longValue()); } public J9VMRuntimeFlagsPointer subOffset(long offset) { return J9VMRuntimeFlagsPointer.cast(address - offset); } public J9VMRuntimeFlagsPointer subOffset(Scalar offset) { return subOffset(offset.longValue()); } public J9VMRuntimeFlagsPointer untag(long mask) { return J9VMRuntimeFlagsPointer.cast(address & ~mask); } public J9VMRuntimeFlagsPointer untag() { return untag(UDATA.SIZEOF - 1); } protected long sizeOfBaseType() { return J9VMRuntimeFlags.SIZEOF; } // Implementation methods }
package com.flowci.core.config.service; import com.flowci.core.common.config.AppProperties; import com.flowci.core.common.domain.Mongoable; import com.flowci.core.common.manager.SpringEventManager; import com.flowci.core.config.dao.ConfigDao; import com.flowci.core.config.domain.*; import com.flowci.core.config.event.GetConfigEvent; import com.flowci.core.secret.domain.Secret; import com.flowci.core.secret.event.GetSecretEvent; import com.flowci.domain.SimpleAuthPair; import com.flowci.exception.ArgumentException; import com.flowci.exception.DuplicateException; import com.flowci.exception.NotFoundException; import com.flowci.exception.StatusException; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.event.EventListener; import org.springframework.core.io.Resource; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.List; import java.util.Optional; @Log4j2 @Service public class ConfigServiceImpl implements ConfigService { @Value("classpath:default/smtp-demo-config.yml") private Resource defaultSmtpConfigYml; @Autowired private AppProperties appProperties; @Autowired private ConfigDao configDao; @Autowired private SpringEventManager eventManager; @PostConstruct public void onInit() { try { Config config = ConfigParser.parse(defaultSmtpConfigYml.getInputStream()); Optional<Config> optional = configDao.findByName(config.getName()); // delete if default smtp config is disabled if (!appProperties.isDefaultSmtpConfig()) { optional.ifPresent(value -> configDao.delete(value)); return; } if (optional.isPresent()) { return; } configDao.save(config); log.info("Config {} has been created", config.getName()); } catch (IOException e) { log.warn(e); } } @EventListener public void onGetConfigEvent(GetConfigEvent event) { try { Config config = get(event.getName()); event.setFetched(config); } catch (NotFoundException e) { event.setError(e); } } @Override public Config get(String name) { Optional<Config> optional = configDao.findByName(name); if (!optional.isPresent()) { throw new NotFoundException("Configuration name {0} is not found", name); } return optional.get(); } @Override public List<Config> list() { return configDao.findAll(Mongoable.SortByCreatedAtASC); } @Override public List<Config> list(Config.Category category) { return configDao.findAllByCategoryOrderByCreatedAtAsc(category); } @Override public Config save(String name, SmtpOption option) { try { SmtpConfig config = load(name, SmtpConfig.class); config.setServer(option.getServer()); config.setPort(option.getPort()); config.setSecure(option.getSecure()); config.setAuth(option.getAuth()); if (option.hasSecret()) { config.setAuth(getAuthPairFromSecret(option)); } return save(config); } catch (ReflectiveOperationException e) { throw new StatusException(e.getMessage()); } } @Override public Config save(String name, String text) { try { TextConfig config = load(name, TextConfig.class); config.setText(text); return save(config); } catch (ReflectiveOperationException e) { throw new StatusException(e.getMessage()); } } private <T extends Config> T load(String name, Class<T> tClass) throws ReflectiveOperationException { Optional<Config> optional = configDao.findByName(name); T config; if (optional.isPresent()) { config = (T) optional.get(); } else { config = tClass.newInstance(); config.setName(name); } return config; } private <T extends Config> T save(T config) { try { return configDao.save(config); } catch (DuplicateKeyException e) { throw new DuplicateException("Config name {0} is already defined", config.getName()); } } private SimpleAuthPair getAuthPairFromSecret(SmtpOption option) { GetSecretEvent event = eventManager.publish(new GetSecretEvent(this, option.getSecret())); if (event.hasError()) { throw event.getError(); } Secret secret = event.getFetched(); if (secret.getCategory() != Secret.Category.AUTH) { throw new ArgumentException("Invalid secret type"); } return (SimpleAuthPair) secret.toSimpleSecret(); } @Override public Config delete(String name) { Config config = get(name); configDao.deleteById(config.getId()); return config; } }
package voss.discovery.agent.alaxala.mib; import net.snmp.*; import voss.discovery.iolib.snmp.SnmpEntry; import java.io.IOException; public abstract class AlaxalaAbstractMibImpl { protected final String qosFlowEntryKey; public AlaxalaAbstractMibImpl(String qosFlowEntryKey) { checkKey(qosFlowEntryKey); this.qosFlowEntryKey = qosFlowEntryKey; } public AlaxalaAbstractMibImpl() { this.qosFlowEntryKey = null; } protected void assertNotNull(Object target) { if (target == null) { throw new IllegalArgumentException(); } } protected String getStringValue(SnmpClient client, String oid) { assertNotNull(client); assertNotNull(oid); try { VarBind varbind = client.snmpGet(OidTLV.getInstance(oid)); if (varbind == null) { throw new IllegalStateException("No such Mib."); } String value = varbind.getValueAsString(); return value; } catch (SnmpResponseException sre) { sre.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } protected abstract void checkKey(String key); protected long getCounterValue(SnmpClient client, String oid) throws SnmpResponseException, IOException { assertNotNull(client); assertNotNull(oid); OidTLV targetOid = OidTLV.getInstance(oid); SnmpResponse.Get responses = client.snmpGet(new OidTLV[]{targetOid}); VarBind varbind = responses.getResponseVarBind(targetOid); if (varbind == null) { throw new IllegalStateException("No such mib: " + oid); } return new TypeCounter64(oid, varbind).getValueAsLong(); } @SuppressWarnings("serial") public class TypeCounter64 extends SnmpEntry { public TypeCounter64(String baseOid, VarBind varbind) { super(baseOid, varbind); } public long getValueAsLong() { return getValueAsBigInteger().longValue(); } } }
package kendzi.josm.kendzi3d.data; import kendzi.kendzi3d.josm.model.perspective.Perspective; import org.openstreetmap.josm.data.osm.OsmPrimitive; /** * Allows to reuse existing world object when related osm primitive or * perspective was changed. * * @author Tomasz Kedziora (Kendzi) * */ public interface RebuildableWorldObject { /** * Rebuild world object from changed initial data. * * @param primitive * osm primitive * @param perspective * perspective */ void rebuildWorldObject(OsmPrimitive primitive, Perspective perspective); }
package com.dennis.nio; import java.nio.ByteBuffer; /** * 只读buffer,我们可以随时将一个普通Buffer调用asReadOnlyBuffer方法返回一个只读Buffer * 但不能将一个只读Buffer转换为读写Buffer */ public class NioTest07 { public static void main(String[] args) { ByteBuffer buffer = ByteBuffer.allocate(10); System.out.println(buffer.getClass()); for (int i = 0; i < buffer.capacity(); ++i) { buffer.put((byte) i); } ByteBuffer readonlyBuffer = buffer.asReadOnlyBuffer(); System.out.println(readonlyBuffer.getClass()); readonlyBuffer.position(0); // readonlyBuffer.put((byte)2); } }
package fi.com.sukapura.MainMenu.Activity.Utils; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.util.Log; import java.util.ArrayList; import fi.com.sukapura.MainMenu.Activity.Konsinyasi; import fi.com.sukapura.Model.GsonInterface.ResponseHandler; import fi.com.sukapura.Services.ApiClient; import fi.com.sukapura.Services.ApiInterface; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by _fi on 11/9/2017. */ public class SendMsisdnKonsinyasi extends AsyncTask<Void, Void, Void> { Context context; ProgressDialog progressDialog; AlertDialog alertDialog; String type, outlet_id, device_id; ApiInterface apiInterface; ArrayList<String> msisdns = new ArrayList<>(); Dialog dialog; public SendMsisdnKonsinyasi(String type, ArrayList<String> msisdns, String outlet_id, String device_id, Context context) { this.type = type; this.msisdns = msisdns; this.outlet_id = outlet_id; this.device_id = device_id; this.context = context; } public SendMsisdnKonsinyasi(String type, ArrayList<String> msisdns, String outlet_id, String device_id, Context context, Dialog dialog) { this.type = type; this.msisdns = msisdns; this.outlet_id = outlet_id; this.device_id = device_id; this.context = context; this.dialog = dialog; } @Override protected void onPreExecute() { super.onPreExecute(); if(type.equals("2")){ dialog.dismiss(); } apiInterface = ApiClient.getClient().create(ApiInterface.class); progressDialog = new ProgressDialog(context); progressDialog.setMessage("Mengirim Nomor..."); progressDialog.show(); } @Override protected Void doInBackground(Void... voids) { for (int i = 0; i < msisdns.size(); i++) { Log.e("sendMsisdn", "msisdn: " + msisdns.get(i).toString() + " outlet_id: " + outlet_id + " type: " + type + " device_id: " + device_id); Call<ResponseHandler> call = apiInterface.msisdn_konsinyasi(msisdns.get(i).toString(), outlet_id, type, device_id); call.enqueue(new Callback<ResponseHandler>() { @Override public void onResponse(Call<ResponseHandler> call, Response<ResponseHandler> response) { } @Override public void onFailure(Call<ResponseHandler> call, Throwable t) { } }); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); progressDialog.dismiss(); alertDialog = new AlertDialog.Builder(context).create(); alertDialog.setMessage("Selesai"); alertDialog.setButton(android.support.v7.app.AlertDialog.BUTTON_NEUTRAL, "Oke", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Konsinyasi konsinyasi = (Konsinyasi) context; konsinyasi.loadMsisdn(); } }); alertDialog.show(); } }
/* * Copyright 2018 The RoboZonky 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.github.robozonky.common.state; import java.util.function.Consumer; /** * Represents state data specific to a given tenant and a given {@link Class}. * @param <T> Class for which the state is kept. */ public interface InstanceState<T> extends StateReader { /** * Perform updates to state using a given modifier. Not guaranteed to happen immediately, {@link #getValue(String)} * may still reflect the state at instantiation. * @param modifier Modifier to use. */ void update(Consumer<StateModifier<T>> modifier); /** * Perform updates to state using a given setter, deleting all pre-existing state information. Not guaranteed to * happen immediately, {@link #getValue(String)} may still reflect the state at instantiation. * @param setter Modifier to use. */ void reset(Consumer<StateModifier<T>> setter); /** * Delete all pre-existing information kept here. Not guaranteed to happen immediately, {@link #getValue(String)} * may still reflect the state at instantiation. */ default void reset() { reset(b -> { // do not add any content }); } default boolean isInitialized() { return getLastUpdated().isPresent(); } }
package br.com.casadocodigo.loja.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericToStringSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.session.data.redis.config.ConfigureRedisAction; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; import redis.clients.jedis.JedisPoolConfig; @EnableRedisHttpSession @Configuration public class RedisConfiguration extends AbstractHttpSessionApplicationInitializer { @Bean public JedisConnectionFactory jedisConnectionFactory() { JedisPoolConfig pool = new JedisPoolConfig(); JedisConnectionFactory factory = new JedisConnectionFactory(pool); factory.setHostName("[SEU ENDPOINT]"); factory.setPort(6379); return factory; } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(jedisConnectionFactory()); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class)); return template; } @Bean public ConfigureRedisAction configureRedisAction() { return ConfigureRedisAction.NO_OP; } }
package com.roby.android.robcket_rocketlaunchschedule.utils; import com.google.android.material.appbar.AppBarLayout; /** * This class used to hide horizontal linear layout * that contain items on the collapsing toolbar * in the launch detail activity */ public abstract class AppBarStateChangeListener implements AppBarLayout.OnOffsetChangedListener { public enum State { EXPANDED, COLLAPSED, IDLE } private State mCurrentState = State.IDLE; @Override public final void onOffsetChanged(AppBarLayout appBarLayout, int i) { if (i == 0) { if (mCurrentState != State.EXPANDED) { onStateChanged(appBarLayout, State.EXPANDED); } mCurrentState = State.EXPANDED; } else if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) { if (mCurrentState != State.COLLAPSED) { onStateChanged(appBarLayout, State.COLLAPSED); } mCurrentState = State.COLLAPSED; } else { if (mCurrentState != State.IDLE) { onStateChanged(appBarLayout, State.IDLE); } mCurrentState = State.IDLE; } } public abstract void onStateChanged(AppBarLayout appBarLayout, State state); }
package org.jeecg.modules.access.controller; import org.jeecg.common.api.vo.Result; import org.jeecg.modules.access.feign.IAccessFeignController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; @RestController @RequestMapping("access") public class AccessController { @Autowired private IAccessFeignController accessFeignController; /** * 获取测试项和其测试用例子项的分页列表方法 * @param likeFullName 模糊查询全称 * @param pageNo 分页Index * @param pageSize 单分页大小 * @return 测试项和其测试用例子项的分页列表 */ @RequestMapping("list/task2case") public Result<?> listTask2Case( @RequestParam("likeFullName")String likeFullName, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){ return accessFeignController.listTask2Case(likeFullName, pageNo, pageSize); } /** * 从Access数据源同步数据到MySQL数据源 * @param map JSON对象Map, 其中含有 * key: [ids], value: [测试用例ID列表字符串 ","分割 String] * key: [projectId], value: [项目ID, String] * key: [turnId], value: [轮次ID String] * key: [turnVerId], value: [轮次版本ID String] * * @return 成功同步的测试用例ID列表 */ @PostMapping("sync") public Result<?> syncData2MySQL(@RequestBody(required = false) Map<String, ?> map){ return accessFeignController.syncData2MySQL(map); } /** * 更新数据源文件路径 * @param map JSON对象Map, 其中含 * key: [path], value: [文件路径 String] * @return */ @PostMapping("update/data-source/path") public Result<?> updateAccessDataSource(@RequestBody(required = false) Map<String, ?> map){ return accessFeignController.updateAccessDataSource(map); } /** * 获取存储的Access数据源文件路径 * @return Access数据源文件路径 */ @GetMapping("get/data-source/path") public Result<?> getAccessDataSource(){ return getAccessDataSource(); } /** * 检查该Access数据源文件是否存在 * @param path Access数据源文件路径(eg. D:\0.mdb) * @return 是否存在 */ @GetMapping("check/data-source/path") public Result<?> checkAccessDateSource(@RequestParam("path")String path) { return checkAccessDateSource(path); } }
/* * Copyright 2016 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.gradle.nativeplatform.tasks; import javax.inject.Inject; import org.gradle.api.DefaultTask; import org.gradle.api.Incubating; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.FileCollection; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.model.ObjectFactory; import org.gradle.api.provider.ListProperty; import org.gradle.api.provider.Property; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.Nested; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.SkipWhenEmpty; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.WorkResult; import org.gradle.internal.Cast; import org.gradle.internal.operations.logging.BuildOperationLogger; import org.gradle.internal.operations.logging.BuildOperationLoggerFactory; import org.gradle.language.base.internal.compile.Compiler; import org.gradle.nativeplatform.internal.BuildOperationLoggingCompilerDecorator; import org.gradle.nativeplatform.internal.DefaultSemiStaticLibraryArchiverSpec; import org.gradle.nativeplatform.internal.SemiStaticLibraryArchiverSpec; import org.gradle.nativeplatform.platform.NativePlatform; import org.gradle.nativeplatform.platform.internal.NativePlatformInternal; import org.gradle.nativeplatform.toolchain.NativeToolChain; import org.gradle.nativeplatform.toolchain.internal.NativeToolChainInternal; import org.gradle.nativeplatform.toolchain.internal.PlatformToolProvider; /** * Assembles a static library from object files. */ @Incubating public class CreateSemiStaticLibrary extends DefaultTask implements ObjectFilesToBinary { private final ConfigurableFileCollection source; private final RegularFileProperty outputFile; private final ListProperty<String> staticLibArgs; private final Property<NativePlatform> targetPlatform; private final Property<NativeToolChain> toolChain; public CreateSemiStaticLibrary() { ObjectFactory objectFactory = getProject().getObjects(); this.source = getProject().files(); this.outputFile = newOutputFile(); this.staticLibArgs = getProject().getObjects().listProperty(String.class); this.targetPlatform = objectFactory.property(NativePlatform.class); this.toolChain = objectFactory.property(NativeToolChain.class); } /** * The source object files to be passed to the archiver. */ @InputFiles @SkipWhenEmpty public FileCollection getSource() { return source; } /** * Adds a set of object files to be linked. <p> The provided source object is evaluated as per {@link org.gradle.api.Project#files(Object...)}. */ public void source(Object source) { this.source.from(source); } @Inject public BuildOperationLoggerFactory getOperationLoggerFactory() { throw new UnsupportedOperationException(); } // TODO: Need to track version/implementation of ar tool. @TaskAction public void link() { SemiStaticLibraryArchiverSpec spec = new DefaultSemiStaticLibraryArchiverSpec(); spec.setTempDir(getTemporaryDir()); spec.setOutputFile(getOutputFile().get().getAsFile()); spec.objectFiles(getSource()); spec.args(getStaticLibArgs().get()); BuildOperationLogger operationLogger = getOperationLoggerFactory().newOperationLogger(getName(), getTemporaryDir()); spec.setOperationLogger(operationLogger); Compiler<SemiStaticLibraryArchiverSpec> compiler = createCompiler(); WorkResult result = BuildOperationLoggingCompilerDecorator.wrap(compiler).execute(spec); setDidWork(result.getDidWork()); } private Compiler<SemiStaticLibraryArchiverSpec> createCompiler() { NativePlatformInternal targetPlatform = Cast.cast(NativePlatformInternal.class, this.targetPlatform.get()); NativeToolChainInternal toolChain = Cast.cast(NativeToolChainInternal.class, getToolChain().get()); PlatformToolProvider toolProvider = toolChain.select(targetPlatform); return toolProvider.newCompiler(SemiStaticLibraryArchiverSpec.class); } /** * The tool chain used for linking. * * @since 4.7 */ @Internal public Property<NativeToolChain> getToolChain() { return toolChain; } /** * The platform being linked for. * * @since 4.7 */ @Nested public Property<NativePlatform> getTargetPlatform() { return targetPlatform; } /** * The file where the output binary will be located. */ @OutputFile public RegularFileProperty getOutputFile() { return outputFile; } /** * The file where the linked binary will be located. * * @since 4.5 */ @Internal public RegularFileProperty getBinaryFile() { return this.outputFile; } /** * <em>Additional</em> arguments passed to the archiver. * * @since 4.7 */ @Input public ListProperty<String> getStaticLibArgs() { return staticLibArgs; } }
/* * 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.hudi.table.action.commit; import org.apache.hudi.client.WriteStatus; import org.apache.hudi.common.engine.HoodieEngineContext; import org.apache.hudi.common.model.HoodieKey; import org.apache.hudi.common.model.HoodieRecord; import org.apache.hudi.common.model.HoodieRecordPayload; import org.apache.hudi.common.util.collection.Pair; import org.apache.hudi.exception.HoodieUpsertException; import org.apache.hudi.index.HoodieIndex; import org.apache.hudi.table.HoodieTable; import org.apache.hudi.table.action.HoodieWriteMetadata; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; /** * Overrides the {@link #write} method to not look up index and partition the records, because * with {@code org.apache.hudi.operator.partitioner.BucketAssigner}, each hoodie record * is tagged with a bucket ID (partition path + fileID) in streaming way. The FlinkWriteHelper only hands over * the records to the action executor {@link BaseCommitActionExecutor} to execute. * * <p>Computing the records batch locations all at a time is a pressure to the engine, * we should avoid that in streaming system. */ public class FlinkWriteHelper<T extends HoodieRecordPayload,R> extends AbstractWriteHelper<T, List<HoodieRecord<T>>, List<HoodieKey>, List<WriteStatus>, R> { private FlinkWriteHelper() { } private static class WriteHelperHolder { private static final FlinkWriteHelper FLINK_WRITE_HELPER = new FlinkWriteHelper(); } public static FlinkWriteHelper newInstance() { return WriteHelperHolder.FLINK_WRITE_HELPER; } @Override public HoodieWriteMetadata<List<WriteStatus>> write(String instantTime, List<HoodieRecord<T>> inputRecords, HoodieEngineContext context, HoodieTable<T, List<HoodieRecord<T>>, List<HoodieKey>, List<WriteStatus>> table, boolean shouldCombine, int shuffleParallelism, BaseCommitActionExecutor<T, List<HoodieRecord<T>>, List<HoodieKey>, List<WriteStatus>, R> executor, boolean performTagging) { try { Instant lookupBegin = Instant.now(); Duration indexLookupDuration = Duration.between(lookupBegin, Instant.now()); HoodieWriteMetadata<List<WriteStatus>> result = executor.execute(inputRecords); result.setIndexLookupDuration(indexLookupDuration); return result; } catch (Throwable e) { if (e instanceof HoodieUpsertException) { throw (HoodieUpsertException) e; } throw new HoodieUpsertException("Failed to upsert for commit time " + instantTime, e); } } @Override public List<HoodieRecord<T>> deduplicateRecords(List<HoodieRecord<T>> records, HoodieIndex<T, List<HoodieRecord<T>>, List<HoodieKey>, List<WriteStatus>> index, int parallelism) { Map<Object, List<Pair<Object, HoodieRecord<T>>>> keyedRecords = records.stream().map(record -> { // If index used is global, then records are expected to differ in their partitionPath final Object key = record.getKey().getRecordKey(); return Pair.of(key, record); }).collect(Collectors.groupingBy(Pair::getLeft)); return keyedRecords.values().stream().map(x -> x.stream().map(Pair::getRight).reduce((rec1, rec2) -> { @SuppressWarnings("unchecked") T reducedData = (T) rec1.getData().preCombine(rec2.getData()); // we cannot allow the user to change the key or partitionPath, since that will affect // everything // so pick it from one of the records. HoodieKey reducedKey = rec1.getData().equals(reducedData) ? rec1.getKey() : rec2.getKey(); HoodieRecord<T> hoodieRecord = new HoodieRecord<>(reducedKey, reducedData); // reuse the location from the first record. hoodieRecord.setCurrentLocation(rec1.getCurrentLocation()); return hoodieRecord; }).orElse(null)).filter(Objects::nonNull).collect(Collectors.toList()); } }
package frc.robot.utils.sensors; import edu.wpi.first.wpilibj.ADXRS450_Gyro; public class Gyro { private final ADXRS450_Gyro gyro; public Gyro() { this.gyro = new ADXRS450_Gyro(); } public double getAngle(){ return gyro.getAngle(); } public void calibrate(){ gyro.calibrate(); } public void zero(){ gyro.reset(); } }
package com.fluxtream.api; import java.io.IOException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.fluxtream.aspects.FlxLogger; /** * Created with IntelliJ IDEA. * User: candide * Date: 05/03/13 * Time: 11:50 * To change this template use File | Settings | File Templates. */ @Path("/ping") public class PingController { FlxLogger logger = FlxLogger.getLogger(PingController.class); @GET @Produces({MediaType.TEXT_PLAIN}) public String ping() throws IOException { return "pong"; } }
package org.myrobotlab.service; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.slf4j.Logger; public class Intro extends Service { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(Intro.class); public Intro(String n, String id) { super(n, id); } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(Intro.class); meta.addDescription("Introduction to MyRobotlab"); meta.setAvailable(true); meta.addCategory("general"); return meta; } public static void main(String[] args) { try { LoggingFactory.init(Level.INFO); Runtime.start("intro", "Intro"); Runtime.start("servo", "Servo"); Runtime.start("gui", "SwingGui"); } catch (Exception e) { log.error("main threw", e); } } }
package net.dankito.jpa.apt.test_entities.relationship_annotations; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class OneToOne_Bidirectional_OwningSide { @Id private String id; @OneToOne private OneToOne_Bidirectional_InverseSide inverseSide; }
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2011, 2012, 2013, 2014, 2016 Synacor, Inc. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software Foundation, * version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. * ***** END LICENSE BLOCK ***** */ package com.zimbra.soap.mail.type; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import com.google.common.base.MoreObjects; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.zimbra.common.gql.GqlConstants; import com.zimbra.common.soap.MailConstants; import com.zimbra.soap.base.CalOrganizerInterface; import com.zimbra.soap.base.XParamInterface; import io.leangen.graphql.annotations.GraphQLIgnore; import io.leangen.graphql.annotations.GraphQLInputField; import io.leangen.graphql.annotations.GraphQLQuery; import io.leangen.graphql.annotations.types.GraphQLType; @XmlAccessorType(XmlAccessType.NONE) @GraphQLType(name=GqlConstants.CLASS_CALENDAR_ORGANIZER, description="Calendar organizer") public class CalOrganizer implements CalOrganizerInterface { /** * @zm-api-field-tag email-address * @zm-api-field-description Email address (without "MAILTO:") */ @XmlAttribute(name=MailConstants.A_ADDRESS /* a */, required=false) private String address; /** * @zm-api-field-tag url * @zm-api-field-description URL - has same value as <b>{email-address}</b>. * <br /> * Maintained for backwards compatibility with ZCS 4.5 */ @XmlAttribute(name=MailConstants.A_URL /* url */, required=false) private String url; /** * @zm-api-field-tag friendly-name * @zm-api-field-description Friendly name - "CN" in iCalendar */ @XmlAttribute(name=MailConstants.A_DISPLAY /* d */, required=false) private String displayName; /** * @zm-api-field-tag sent-by * @zm-api-field-description iCalendar SENT-BY */ @XmlAttribute(name=MailConstants.A_CAL_SENTBY /* sentBy */, required=false) private String sentBy; /** * @zm-api-field-tag dir * @zm-api-field-description iCalendar DIR - Reference to a directory entry associated with the calendar user. */ @XmlAttribute(name=MailConstants.A_CAL_DIR /* dir */, required=false) private String dir; /** * @zm-api-field-tag language * @zm-api-field-description iCalendar LANGUAGE - As defined in RFC5646 * (e.g. "en-US") */ @XmlAttribute(name=MailConstants.A_CAL_LANGUAGE /* lang */, required=false) private String language; /** * @zm-api-field-description Non-standard parameters (XPARAMs) */ @XmlElement(name=MailConstants.E_CAL_XPARAM /* xparam */, required=false) @GraphQLQuery(name=GqlConstants.XPARAMS, description="Non-standard parameters") private final List<XParam> xParams = Lists.newArrayList(); public CalOrganizer() { } public static CalOrganizer createForAddress(String addr) { CalOrganizer co = new CalOrganizer(); co.setAddress(addr); return co; } @Override @GraphQLInputField(name=GqlConstants.ADDRESS, description="Email address (without MAILTO:)") public void setAddress(String address) { this.address = address; } @Override @GraphQLInputField(name=GqlConstants.URL, description="URL - has same value as emailAddress") public void setUrl(String url) { this.url = url; } @Override @GraphQLInputField(name=GqlConstants.DISPLAY_NAME, description="Friendly name - CN in iCalendar") public void setDisplayName(String displayName) { this.displayName = displayName; } @Override @GraphQLInputField(name=GqlConstants.SENT_BY, description="iCalendar SENT_BY") public void setSentBy(String sentBy) { this.sentBy = sentBy; } @Override @GraphQLInputField(name=GqlConstants.DIRECTORY, description="iCalendar DIR - Reference to a directory entry associated with the calendar user") public void setDir(String dir) { this.dir = dir; } @Override @GraphQLInputField(name=GqlConstants.LANGUAGE, description="iCalendar LANGUAGE - As defined in RFC5646 * (e.g. \"en-US\")") public void setLanguage(String language) { this.language = language; } @GraphQLInputField(name=GqlConstants.XPARAMS, description="Non-standard parameters") public void setXParams(Iterable <XParam> xParams) { this.xParams.clear(); if (xParams != null) { Iterables.addAll(this.xParams,xParams); } } @GraphQLIgnore public CalOrganizer addXParam(XParam xParam) { this.xParams.add(xParam); return this; } @Override @GraphQLQuery(name=GqlConstants.ADDRESS, description="Email address (without MAILTO:)") public String getAddress() { return address; } @Override @GraphQLQuery(name=GqlConstants.URL, description="URL - has same value as emailAddress") public String getUrl() { return url; } @Override @GraphQLQuery(name=GqlConstants.DISPLAY_NAME, description="Friendly name - CN in iCalendar") public String getDisplayName() { return displayName; } @Override @GraphQLQuery(name=GqlConstants.SENT_BY, description="iCalendar SENT_BY") public String getSentBy() { return sentBy; } @Override @GraphQLQuery(name=GqlConstants.DIRECTORY, description="iCalendar DIR - Reference to a directory entry associated with the calendar user") public String getDir() { return dir; } @Override @GraphQLQuery(name=GqlConstants.LANGUAGE, description="iCalendar LANGUAGE - As defined in RFC5646 * (e.g. \"en-US\")") public String getLanguage() { return language; } @GraphQLQuery(name=GqlConstants.XPARAMS, description="Non-standard parameters") public List<XParam> getXParams() { return Collections.unmodifiableList(xParams); } @Override @GraphQLIgnore public void setXParamInterfaces(Iterable<XParamInterface> xParams) { setXParams(XParam.fromInterfaces(xParams)); } @Override @GraphQLIgnore public void addXParamInterface(XParamInterface xParam) { addXParam((XParam) xParam); } @Override @GraphQLIgnore public List<XParamInterface> getXParamInterfaces() { return XParam.toInterfaces(xParams); } public MoreObjects.ToStringHelper addToStringInfo( MoreObjects.ToStringHelper helper) { return helper .add("address", address) .add("url", url) .add("displayName", displayName) .add("sentBy", sentBy) .add("dir", dir) .add("language", language) .add("xParams", xParams); } @Override public String toString() { return addToStringInfo(MoreObjects.toStringHelper(this)) .toString(); } }
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.trade.repaybill.order.createandpay response. * * @author auto create * @since 1.0, 2020-10-09 11:27:13 */ public class AlipayTradeRepaybillOrderCreateandpayResponse extends AlipayResponse { private static final long serialVersionUID = 2561846146764736521L; /** * 支付宝账单编号 */ @ApiField("bill_no") private String billNo; /** * 还款金额,单位为元,精确到小数点后两位,取值范围[0.01,100000000] */ @ApiField("repay_amount") private String repayAmount; /** * 还款的资金单号,后续用该单号去调用支付宝收银台sdk进行支付 */ @ApiField("repay_fund_order_no") private String repayFundOrderNo; /** * 订单还款状态,INIT:初始状态;PARTIAL_SUCCESS:部分还款成功;SUCCESS:全部还款成功;CLOSE:订单已经关闭 */ @ApiField("repay_status") private String repayStatus; public void setBillNo(String billNo) { this.billNo = billNo; } public String getBillNo() { return this.billNo; } public void setRepayAmount(String repayAmount) { this.repayAmount = repayAmount; } public String getRepayAmount() { return this.repayAmount; } public void setRepayFundOrderNo(String repayFundOrderNo) { this.repayFundOrderNo = repayFundOrderNo; } public String getRepayFundOrderNo() { return this.repayFundOrderNo; } public void setRepayStatus(String repayStatus) { this.repayStatus = repayStatus; } public String getRepayStatus() { return this.repayStatus; } }
/* * 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.calcite.adapter.druid; import org.apache.calcite.sql.type.SqlTypeName; /** Druid type. */ public enum DruidType { LONG(SqlTypeName.BIGINT), // SQL DOUBLE and FLOAT types are both 64 bit, but we use DOUBLE because // people find FLOAT confusing. FLOAT(SqlTypeName.DOUBLE), STRING(SqlTypeName.VARCHAR), HYPER_UNIQUE(SqlTypeName.VARBINARY), THETA_SKETCH(SqlTypeName.VARBINARY); /** The corresponding SQL type. */ public final SqlTypeName sqlType; DruidType(SqlTypeName sqlType) { this.sqlType = sqlType; } /** * Returns true if and only if this enum should be used inside of a {@link ComplexMetric} * */ public boolean isComplex() { return this == THETA_SKETCH || this == HYPER_UNIQUE; } /** * Returns a DruidType matching the given String type from a Druid metric * */ public static DruidType getTypeFromMetric(String type) { assert type != null; if (type.equals("hyperUnique")) { return HYPER_UNIQUE; } else if (type.equals("thetaSketch")) { return THETA_SKETCH; } else if (type.startsWith("long") || type.equals("count")) { return LONG; } else if (type.startsWith("double")) { return FLOAT; } throw new AssertionError("Unknown type: " + type); } /** * Returns a DruidType matching the String from a meta data query * */ public static DruidType getTypeFromMetaData(String type) { assert type != null; switch (type) { case "LONG": return LONG; case "FLOAT": return FLOAT; case "STRING": return STRING; default: // Likely a sketch, or a type String from the aggregations field. return getTypeFromMetric(type); } } } // End DruidType.java
package com.arcao.trackables.ui.fragment.detail; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.arcao.trackables.internal.di.HasComponent; import com.arcao.trackables.internal.di.component.DetailActivityComponent; import com.arcao.trackables.ui.DetailActivity; import butterknife.ButterKnife; public abstract class AbstractTrackableFragment extends Fragment implements HasComponent<DetailActivityComponent> { private static final String ARG_TRACKABLE_CODE = "TRACKABLE_CODE"; protected void setTrackableCode(String trackableCode) { if (getArguments() == null) { setArguments(new Bundle()); } getArguments().putString(ARG_TRACKABLE_CODE, trackableCode); } protected String getTrackableCode() { return getArguments().getString(ARG_TRACKABLE_CODE); } @LayoutRes protected abstract int getLayout(); @Override public DetailActivityComponent component() { return ((DetailActivity) getActivity()).component(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); component().inject(this); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(getLayout(), container, false); ButterKnife.inject(this, view); return view; } }
package com.kang.mall.controller.admin; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.kang.mall.common.Result; import com.kang.mall.entity.User; import com.kang.mall.param.admin.UserParam; import com.kang.mall.service.admin.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * @author kang * ClassName: UserController * Create Date: 2021/3/14 18:15 */ @RestController("User_AdminController") @RequestMapping("/admin") public class UserController { @Autowired private UserService userService; @GetMapping("/user") public Result<Page<User>> list( @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size ) { Page<User> list = userService.list(page, size); return Result.ok(list); } @GetMapping("/user/{id}") public Result get(@PathVariable Long id) { return null; } @PostMapping("/user") public Result create() { return null; } @RequestMapping(value = "/user/{id}/password", method = RequestMethod.PUT) public Result resetPassword(@PathVariable Long id) { return userService.resetPassword(id) ? Result.ok("重置密码成功,密码重置为 123456") : Result.error("重置密码失败"); } @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT) public Result update(@PathVariable Long id, @RequestBody @Valid UserParam userParam) { return userService.update(id, userParam) ? Result.ok("更新成功") : Result.error("更新失败"); } @RequestMapping(value = "/user{id}", method = RequestMethod.DELETE) public Result remove(@PathVariable Long id) { return null; } }
/** * 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.hadoop.hive.serde2.lazybinary; import org.apache.hadoop.hive.serde2.lazy.ByteArrayRef; import org.apache.hadoop.hive.serde2.lazybinary.LazyBinaryUtils.VLong; import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableLongObjectInspector; import org.apache.hadoop.io.LongWritable; public class LazyBinaryLong extends LazyBinaryPrimitive<WritableLongObjectInspector, LongWritable> { LazyBinaryLong(WritableLongObjectInspector oi) { super(oi); data = new LongWritable(); } LazyBinaryLong(LazyBinaryLong copy) { super(copy); data = new LongWritable(copy.data.get()); } VLong vLong = new LazyBinaryUtils.VLong(); @Override public void init(ByteArrayRef bytes, int start, int length) { LazyBinaryUtils.readVLong(bytes.getData(), start, vLong); assert (length == vLong.length); data.set(vLong.value); } }
/* * Copyright 2019 Arcus 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.iris.driver.event; import com.iris.messages.model.DriverId; import com.iris.model.Version; /** * */ public class DriverUpgradedEvent extends DriverEvent { DriverId oldDriverId; DriverUpgradedEvent(DriverId oldVersion) { this.oldDriverId = oldVersion; } public DriverId getOldDriverId() { return oldDriverId; } public Version getOldVersion() { return oldDriverId.getVersion(); } public String getOldName() { return oldDriverId.getName(); } @Override public String toString() { return "DriverUpgradedEvent [oldVersion=" + oldDriverId + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((oldDriverId == null) ? 0 : oldDriverId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DriverUpgradedEvent other = (DriverUpgradedEvent) obj; if (oldDriverId == null) { if (other.oldDriverId != null) return false; } else if (!oldDriverId.equals(other.oldDriverId)) return false; return true; } @Override public ActionAfterHandled getActionAfterHandled() { return ActionAfterHandled.NONE; } }
package gov.va.isaac.gui.enhancedsearchview.resulthandler; import gov.va.isaac.AppContext; import gov.va.isaac.gui.enhancedsearchview.SearchTypeEnums.ResultsType; import gov.va.isaac.gui.enhancedsearchview.model.SearchModel; import gov.va.isaac.interfaces.utility.DialogResponse; import gov.va.isaac.interfaces.workflow.ComponentWorkflowServiceI; import gov.va.isaac.interfaces.workflow.ProcessInstanceCreationRequestI; import gov.va.isaac.interfaces.workflow.WorkflowProcess; import gov.va.isaac.search.CompositeSearchResult; import java.util.HashMap; import java.util.Map; import org.ihtsdo.otf.tcc.api.chronicle.ComponentVersionBI; import org.ihtsdo.otf.tcc.api.concept.ConceptVersionBI; import org.ihtsdo.otf.tcc.api.description.DescriptionVersionBI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResultsToWorkflow { private static final Logger LOG = LoggerFactory.getLogger(ResultsToWorkflow.class); private static ComponentWorkflowServiceI conceptWorkflowService; private static SearchModel searchModel = new SearchModel(); // TODO (artf23141) This doesn't make sense here. Should be exported to listView, then Workflow public static void multipleResultsToWorkflow() { initializeWorkflowServices(); // Use HashSet to ensure that only one workflow is created for each concept Map<Integer, ComponentVersionBI> conceptsOrComponents = new HashMap<>(); if (searchModel.getResultsTypeComboBox().getSelectionModel().getSelectedItem() == ResultsType.CONCEPT) { for (CompositeSearchResult result : searchModel.getSearchResultsTable().getResults().getItems()) { ConceptVersionBI conceptVersion = result.getContainingConcept(); int nid = conceptVersion.getNid(); if (! conceptsOrComponents.containsKey(nid)) { conceptsOrComponents.put(nid, conceptVersion); } } } else if (searchModel.getResultsTypeComboBox().getSelectionModel().getSelectedItem() == ResultsType.DESCRIPTION) { for (CompositeSearchResult result : searchModel.getSearchResultsTable().getResults().getItems()) { ComponentVersionBI componentVersion = result.getMatchingComponents().iterator().next(); int nid = componentVersion.getNid(); if (! conceptsOrComponents.containsKey(nid)) { conceptsOrComponents.put(nid, componentVersion); } } } else { String title = "Failed exporting search results to workflow"; String msg = "Unsupported AggregationType " + searchModel.getResultsTypeComboBox().getSelectionModel().getSelectedItem(); LOG.error(title + ". " + msg); AppContext.getCommonDialogs().showErrorDialog(title, msg, title + ". " + msg, AppContext.getMainApplicationWindow().getPrimaryStage()); } if (conceptsOrComponents.size() > 0) { DialogResponse response = AppContext.getCommonDialogs().showYesNoDialog("Bulk Workflow Export Confirmation", "Are you sure that you want to generate " + conceptsOrComponents.size() + " new Workflow instance(s)?"); if (response == DialogResponse.YES) { for (ComponentVersionBI conceptOrComponent : conceptsOrComponents.values()) { singleResultToWorkflow(conceptOrComponent); } conceptWorkflowService.synchronizeWithRemote(); } } } private static void singleResultToWorkflow(ComponentVersionBI componentOrConceptVersion) { initializeWorkflowServices(); final WorkflowProcess process = WorkflowProcess.REVIEW3; String preferredDescription = null; try { if (componentOrConceptVersion instanceof ConceptVersionBI) { DescriptionVersionBI<?> desc = ((ConceptVersionBI)componentOrConceptVersion).getPreferredDescription(); preferredDescription = desc.getText(); } else { preferredDescription = componentOrConceptVersion.toUserString(); } LOG.debug("Invoking createNewConceptWorkflowRequest(preferredDescription=\"" + preferredDescription + "\", conceptUuid=\"" + componentOrConceptVersion.getPrimordialUuid().toString() + "\", processName=\"" + process.getText() + "\")"); ProcessInstanceCreationRequestI createdRequest = conceptWorkflowService.createNewComponentWorkflowRequest(preferredDescription, componentOrConceptVersion.getPrimordialUuid(), process.getText(), new HashMap<String,String>()); LOG.debug("Created ProcessInstanceCreationRequestI: " + createdRequest); } catch (Exception e1) { String title = "Error sending component to workflow"; String msg = title + ". Unexpected error while sending the component (nid=" + componentOrConceptVersion.getNid() + ", uuid=" + componentOrConceptVersion.getPrimordialUuid().toString() + "): caught " + e1.getClass().getName() + " " + e1.getLocalizedMessage(); LOG.error(msg, e1); AppContext.getCommonDialogs().showErrorDialog(title, msg, e1.getMessage(), AppContext.getMainApplicationWindow().getPrimaryStage()); return; } } private static void initializeWorkflowServices() { if (conceptWorkflowService == null) { conceptWorkflowService = AppContext.getService(ComponentWorkflowServiceI.class); } assert conceptWorkflowService != null; } }
/** * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.dns.model; /** * A DNS resource record. For more information about records, see [RFC 1034](https://tools.ietf.org/html/rfc1034#section-3.6). * <br/> * Note: Objects should always be created or deserialized using the {@link Builder}. This model distinguishes fields * that are {@code null} because they are unset from fields that are explicitly set to {@code null}. This is done in * the setter methods of the {@link Builder}, which maintain a set of all explicitly set fields called * {@link #__explicitlySet__}. The {@link #hashCode()} and {@link #equals(Object)} methods are implemented to take * {@link #__explicitlySet__} into account. The constructor, on the other hand, does not set {@link #__explicitlySet__} * (since the constructor cannot distinguish explicit {@code null} from unset {@code null}). **/ @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20180115") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize(builder = RecordDetails.Builder.class) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) public class RecordDetails { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("domain") private String domain; public Builder domain(String domain) { this.domain = domain; this.__explicitlySet__.add("domain"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("recordHash") private String recordHash; public Builder recordHash(String recordHash) { this.recordHash = recordHash; this.__explicitlySet__.add("recordHash"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("isProtected") private Boolean isProtected; public Builder isProtected(Boolean isProtected) { this.isProtected = isProtected; this.__explicitlySet__.add("isProtected"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("rdata") private String rdata; public Builder rdata(String rdata) { this.rdata = rdata; this.__explicitlySet__.add("rdata"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("rrsetVersion") private String rrsetVersion; public Builder rrsetVersion(String rrsetVersion) { this.rrsetVersion = rrsetVersion; this.__explicitlySet__.add("rrsetVersion"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("rtype") private String rtype; public Builder rtype(String rtype) { this.rtype = rtype; this.__explicitlySet__.add("rtype"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("ttl") private Integer ttl; public Builder ttl(Integer ttl) { this.ttl = ttl; this.__explicitlySet__.add("ttl"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>(); public RecordDetails build() { RecordDetails __instance__ = new RecordDetails( domain, recordHash, isProtected, rdata, rrsetVersion, rtype, ttl); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(RecordDetails o) { Builder copiedBuilder = domain(o.getDomain()) .recordHash(o.getRecordHash()) .isProtected(o.getIsProtected()) .rdata(o.getRdata()) .rrsetVersion(o.getRrsetVersion()) .rtype(o.getRtype()) .ttl(o.getTtl()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * The fully qualified domain name where the record can be located. * **/ @com.fasterxml.jackson.annotation.JsonProperty("domain") String domain; /** * A unique identifier for the record within its zone. * **/ @com.fasterxml.jackson.annotation.JsonProperty("recordHash") String recordHash; /** * A Boolean flag indicating whether or not parts of the record * are unable to be explicitly managed. * **/ @com.fasterxml.jackson.annotation.JsonProperty("isProtected") Boolean isProtected; /** * The record's data, as whitespace-delimited tokens in * type-specific presentation format. All RDATA is normalized and the * returned presentation of your RDATA may differ from its initial input. * For more information about RDATA, see [Supported DNS Resource Record Types](https://docs.cloud.oracle.com/iaas/Content/DNS/Reference/supporteddnsresource.htm) * **/ @com.fasterxml.jackson.annotation.JsonProperty("rdata") String rdata; /** * The latest version of the record's zone in which its RRSet differs * from the preceding version. * **/ @com.fasterxml.jackson.annotation.JsonProperty("rrsetVersion") String rrsetVersion; /** * The canonical name for the record's type, such as A or CNAME. For more * information, see [Resource Record (RR) TYPEs](https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4). * **/ @com.fasterxml.jackson.annotation.JsonProperty("rtype") String rtype; /** * The Time To Live for the record, in seconds. **/ @com.fasterxml.jackson.annotation.JsonProperty("ttl") Integer ttl; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>(); }
/* * Copyright 2017-2021 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 * * 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 io.spring.javaformat.eclipse.projectsettings; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import io.spring.javaformat.config.JavaFormatConfig; /** * Locates project settings files to be applied to projects. * * @author Phillip Webb */ public class ProjectSettingsFilesLocator { private static final String JDT_CORE_PREFS = "org.eclipse.jdt.core.prefs"; private static final String[] SOURCE_FOLDERS = { "eclipse", ".eclipse" }; private static final String[] DEFAULT_FILES = { JDT_CORE_PREFS, "org.eclipse.jdt.ui.prefs" }; private final File[] searchFolders; public ProjectSettingsFilesLocator(File... searchFolders) { this.searchFolders = searchFolders; } public ProjectSettingsFilesLocator(Collection<File> searchFolders) { this.searchFolders = searchFolders.toArray(new File[0]); } public ProjectSettingsFiles locateSettingsFiles() throws IOException { ProjectProperties projectProperties = new ProjectProperties(); Map<String, ProjectSettingsFile> files = new LinkedHashMap<>(); for (File searchFolder : this.searchFolders) { for (String sourceFolder : SOURCE_FOLDERS) { add(projectProperties, files, new File(searchFolder, sourceFolder)); } } for (String file : DEFAULT_FILES) { putIfAbsent(files, getDefaultSettingsFile(file)); } return new ProjectSettingsFiles(files.values(), projectProperties); } private ProjectSettingsFile getDefaultSettingsFile(String file) { ProjectSettingsFile settingsFile = ProjectSettingsFile.fromClasspath(getClass(), file); if (settingsFile.getName().equals(JDT_CORE_PREFS)) { settingsFile = settingsFile.withUpdatedContent(this::updateFormatter); } return settingsFile; } private String updateFormatter(JavaFormatConfig javaFormatConfig, String content) { String formatterId = getFormatterId(javaFormatConfig); if (formatterId != null) { return content.replace( "org.eclipse.jdt.core.javaFormatter=io.spring.javaformat.eclipse.formatter.jdk11.tabs", "org.eclipse.jdt.core.javaFormatter=" + formatterId); } return content; } private String getFormatterId(JavaFormatConfig config) { String jdk = config.getJavaBaseline().name().substring(1); String indentation = config.getIndentationStyle().name().toLowerCase(); return "io.spring.javaformat.eclipse.formatter.jdk" + jdk + "." + indentation; } private void add(ProjectProperties projectProperties, Map<String, ProjectSettingsFile> files, File folder) throws IOException { if (folder.exists() && folder.isDirectory()) { for (File file : folder.listFiles(this::isPrefsFile)) { putIfAbsent(files, ProjectSettingsFile.fromFile(file)); } projectProperties.addFromFolder(folder); } } private boolean isPrefsFile(File file) { return file.getName().toLowerCase().endsWith(".prefs"); } private void putIfAbsent(Map<String, ProjectSettingsFile> files, ProjectSettingsFile candidate) { files.putIfAbsent(candidate.getName(), candidate); } }
package com.kroraina.easyreader.modules.community.detail; import com.kroraina.easyreader.model.bean.AuthorBean; public class HelpsDetailBean { /** * _id : 579df15f8eaf3ec231d8bc2b * type : help * author : {"_id":"54ec360d77bace32513eabc1","avatar":"/avatar/f1/ca/f1cad586d81253f48b360738b1b90780","nickname":"万剑一","activityAvatar":"/activities/20170120/4.jpg","type":"doyen","lv":10,"gender":"male","rank":null,"created":"2015-02-24T08:27:57.000Z","id":"54ec360d77bace32513eabc1"} * title : 16-8养肥书单 * content : 有些评论不是我写的,但是我尽量挑公允一点的。 * <p> * 《皇帝直播间》 * UP主魂穿高武位面的小国纨绔庶皇子,金手指系统+千千万万直播网友,创意满分,文笔平均偏下水准,文中皇帝设定正值壮年+性格多疑,争夺封王位比立功,五皇子散财赈灾,男主拉出一个前世制图专业的设定靠画地图强行当功劳,你了解本国国情吗?知道你爹喜文喜武吗?如果你爹怀疑你借机卖人情给武将或是私下里和武将来往怎么办?与其如此倒不如以五年内成为封圣强者为比试内容(五皇子方也可以选择拉拢一位封圣强者对皇帝效忠)更为妥当,首先这任务你办不到得死,硬条件,第二这个比试不涉及朝堂权力斗争,一个封圣强者拥有灭国级别的核弹实力,成不了男主死五皇子上位,成了自然而然就有自己的势力,夺嫡登基更有竞争力。 * <p> * 《重生之抠脚大汉变男神》 * 我想评价这本书的时候我必须要再一次抬出这句话了:“一本书的主角其实是作者本身特质的折射”,所以我猜测作者应该是一位拥有少女心的抠脚大汉,在闲暇午睡时来了一场如同成人童话一般的梦中重生之旅。然后,就有了这本书。虽然脱胎于某种逗比小白文的文字风格很有趣,但这类文总有一个后劲不强容易腻的通病,所以后续如何要看作者的功力。哦对了,为什么我说这书脱胎逗比小白文,因为有一些情节实在是太幼稚了,忽略那些毒点是可看的。 * <p> * 《气吞寰宇》 * 教主的新书,先养着 * <p> * 《百年家书》 * 作者文笔很好,实体风,也表现出民国的波澜壮阔。但是文风看的很累,加上写的是那个残酷的年代就更累了。 按我的说法,不会刻意去找这本书,但如果在书店碰到会买下来。但是平常在网上不会选择阅读这类书。原因不管是爽文还是虐文,看着不会累,毕竟看网络小说就是为了消遣娱乐。但是你会在休息时间在网上看悲惨世界,围城之类的名著吗?这种书还是适合实体 * <p> * 《红龙》 * 异世-异类,量大管饱,更新较慢,著名异类文兼气管炎老司机接口卡的老坑,讲述主角死后重生为一条与众不同的红龙睡觉或破坏的日常,从用牙齿种出管钱的女儿到体内长出核反应堆。目前已变成为眼里只剩母蜥蜴的淫龙,果断上了亲妹。 * <p> * 《韩警官》 * 很有味道的一本官场刑侦小说,主角重生怀疑自己做梦,家庭和睦,仕途顺利,主角慢慢向警察发展,很喜欢里面的风格,九十年代的气息扑面而来,那时候的精气神,基层人民的生活,都很好的展示出来了。作者安排的金手指大多是主角的个人道德修养吧,谦虚周到理智精明,剧情上的硬伤倒是没怎么发现。单看前几章作者对主角的安排——整顿夜市、参加律师考试,就能看出作者的精心经营,慢慢雕琢的主角谁不喜欢呢?现实中读者大多没有目的性,那么网文中行事有条理有强烈目的性的主角自然会得到众人的欢心了。另,提醒:这本几乎没有明显的装逼打脸情节,不要拿一般官场文度之,恩,比余罪严肃很多。 * <p> * 《特拉福买家俱乐部》 * 首先主角三观较正,并非见钱眼开,交易了就什么都不管的主,甚至遇到了那种穷凶极恶的交易者,还会体现出些许另类的「侠者之气」,看了不难受。 第二,文笔不错,行文流畅,顺带一提对于人偶妹子的描写让我这个轻度人偶控相当的受用。 第三,这本小说好像有那啥的倾向....不说太多,给你们四个字「圣母降临」,也是坛子里作者的作品,老司机们自然就明白了。 * <p> * 《柯南世界里的巫师》 * 作为柯南同人居然敢穿插奇门异术的力量体系,暗世界的设定可见作者魄力,这么一写俨然是鹤立鸡群,新意突显啊。文笔虽谈不上上上之选但也是流畅无阻,可以说是柯南同人中鲜有的佳作。不足之处在于感情描写颇是仓促缺乏点睛之笔,人物形象略显单一苍白。 * <p> * 《大明1630》 * 总体来说还是有干粮水平的,主角国姓爷身份的切入点也挺特别,里面几段主角立论也写得挺好。主要问题在于部分对话用语太现代,会冒出有些可能没有的词汇,还有一个攀科技树的小说一般都会出现不太切合实际这个问题。 * <p> * 《重生之出人头地》 * 沧海的马甲,真正的智斗流,写的比本尊那本兵锋无双好,沧海还是最适合写香港。各种细节信手拈來,现实和电影糅合在一起,那不是香港又是香港,那就是我们心目中的香港江湖。 * <p> * 《放开那个女巫》 * 很多人都说好的书,的确很好。仙草-。主角来到个类似中世纪(冰与火?)的时代,拯救了一群女巫,利用女巫的超能力快速发展工业,用钢铁枪炮与兄弟姐妹争夺王位的故事。好吧,虽然是中世纪发展工业,不过看点完全不在这!最大的看点是,在最黑暗的年代,主角王子扮演救世主的角色,拯救了一群被残酷迫害的女巫妹子的故事。这是多么伟大和圣母啊!!哈哈,不完全是开玩笑,工业什么的看看就行了,最好看的还是主角和妹子的互动。 * <p> * 《我的魔法时代》 * 穿越玄幻类小说,从5岁写起,整体氛围很好,没那么多戾气,文笔好。但是相应的主角的心态上感觉有些弱鸡。慢热 好看就是更的慢 又的养了。 * <p> * 《暗影圣贤》 * 作者这么爱吐槽为什么不干脆写一本逗逼文呢?上本这样,这本也是,不说写出史诗感至少也应该严肃点,插进去的各种明显是作者的无厘头吐槽配上救世题材…… * <p> * 《绝顶枪王》 * 本文选择的游戏是枪战类。之后主角做游戏通关任务,妙趣横生,又很能体现主角的实力。作者这样把竞技和游戏任务结合在一起写,很赞,至少节奏把握的很好。生活情节虽然满满热血漫的既视感,但作者把握住了风格,青春热血,激情奋斗的味道写出来了,这也就够了。对比作者的上一本书,感觉这次进步很大,作者比较擅长写这方面的故事,期待作者能保持水平,继续进步。 * <p> * 《这锅我不背》 * 晋江位面的特产——搞基文,不喜勿入。 脑洞巨大,创意独特,非常有意思的小说,作者的脑回路有异于常人,看这本书看看创意还是蛮爽的,搞基部分自动屏蔽就好了 * <p> * 《从酋长到球长》 * 看着就能感觉作者的写作水平又提高了,额,或者说这个作者本来的文字水平就是顶尖一系列的,写这本书的过程中逐渐熟悉了网文读者的好恶,努力的去写成一本网文。这么说或者有点乱,不过大概可以理解为用平铺直叙的方式来讲一个故事的情况下让你感觉到文字的美感。并且情节的把控上水平也有所提高。而且作者没有范文青病,最近的文字在超好的文笔与文青之间,非常好的把握住了那个度,让人看起来非常舒服。好书不容错过。 * <p> * 《[综]天生反派》 * 这根本就是个男版林黛玉,既不能做到有恩报恩,又不能做到有仇报仇,每次都是病殃殃的让别人可怜,最后英年早逝把所有关心他的人伤害个遍,真是个废物。 * <p> * 《远东王庭》 * 颇为有趣的DND作品,金手指虽然巴拉巴拉解释了一连串,但是和系统流差别其实不是很大。 作者应该是老作者,很明白怎么在爽的同时调整主角的进步速度。 * <p> * 《魔神乐园》 * 主流小白文的模板,准一流的打斗描写。为了配合小白文写法,反派的魅力被削弱很多。 支线加入同伴的描写,比前两本进步,有亮点。 总体来说:可以一看,有毒点,跳着看还不错。 * <p> * 这次书不多,主要这半年也没什么好书,说实话 * state : distillate * updated : 2017-04-22T18:47:16.745Z * created : 2016-07-31T12:38:55.286Z * commentCount : 339 * shareLink : http://share.zhuishushenqi.com/post/579df15f8eaf3ec231d8bc2b * id : 579df15f8eaf3ec231d8bc2b */ private String _id; private String type; private AuthorBean author; private String title; private String content; private String state; private String updated; private String created; private int commentCount; public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public AuthorBean getAuthor() { return author; } public void setAuthor(AuthorBean author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getUpdated() { return updated; } public void setUpdated(String updated) { this.updated = updated; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public int getCommentCount() { return commentCount; } public void setCommentCount(int commentCount) { this.commentCount = commentCount; } }
package code.kafka.interceptor; import org.apache.kafka.clients.producer.ProducerInterceptor; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @describe: kafka 拦截器,生产者拦截器 * 需求:业务消息从被生产出来到最后被消费的平均总时长是多少,统计端到端的平均延时 * @author: 彭爽 pross.peng * @date: 2020/05/07 */ public class AvgLatencyProducerInterceptor implements ProducerInterceptor<String,String> { // private Jedis jedis; // 省略Jedis初始化, 用map代替统计,需要保证线程安全(producerIntercepter和consumerInterceptor是不同的线程) static ConcurrentHashMap<String,Object> messageMap; static { messageMap.put("totalSentMessage",0); messageMap.put("totalLatency",0); messageMap.put("avgLatency",0); } /** * onsend方法,会在消息发送之前被调用,需要考虑消息发送失败的情况 * @param producerRecord * @return */ @Override public ProducerRecord<String, String> onSend(ProducerRecord<String, String> producerRecord) { // jedis.incr("totalSentMessage); // 在发送消息前更新总的已发送消息数 Long totalSentMessage = Long.parseLong(messageMap.get("totalSentMessage").toString()); totalSentMessage += 1 ; messageMap.put("totalSentMessage",totalSentMessage); return producerRecord; } /** * onAcknowledgement方法,在消息被确定提交后被调用(无论消息提交失败还是成功) * @param recordMetadata * @param e */ @Override public void onAcknowledgement(RecordMetadata recordMetadata, Exception e) { } @Override public void close() { } @Override public void configure(Map<String, ?> map) { } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package automata; /** * * @author Samer2 */ public class SymbolNotInAlphabetException extends Exception{ @Override public String getMessage() { return "A Symbol is not in alphabet!"; } }
package org.openqa.selenium.server; import static org.junit.Assert.*; import org.junit.After; import org.junit.Test; /** * Unit tests for SeleniumServer. * * @author Matthew Purland */ public class SeleniumServerUnitTest { // Number of jetty threads to positively test for private int positiveJettyThreads = SeleniumServer.DEFAULT_JETTY_THREADS; private SeleniumServer server; @Test public void constructor_setsThisAsSeleniumServerInRemoteControlConfiguration() throws Exception { RemoteControlConfiguration remoteConfiguration = new RemoteControlConfiguration(); server = new SeleniumServer(remoteConfiguration); assertEquals(server, remoteConfiguration.getSeleniumServer()); } @After public void tearDown() { if (server != null) { server.stop(); } } /** * Test happy path that if an "okay" number of threads is given then it will * start up correctly. * * @throws Exception */ @Test public void testJettyThreadsPositive() throws Exception { RemoteControlConfiguration configuration = new RemoteControlConfiguration(); configuration.setJettyThreads(positiveJettyThreads); server = new SeleniumServer(configuration); server.start(); assertEquals("Jetty threads given is not correct.", positiveJettyThreads, server.getJettyThreads()); } // /** // * Test for a positive result when passing a positive argument for // * -jettyThreads. // * // * @throws Exception // */ // public void testJettyServerArgumentPositive() throws Exception { // String[] args = new String[] { "-jettyThreads", // String.valueOf(positiveJettyThreads) }; // SeleniumServer.main(args); // // assertEquals("Server did not start up correctly from arguments.", // positiveJettyThreads, SeleniumServer.getJettyThreads()); // } // // /** // * Test for a negative result when passing a max argument for -jettyThreads. // * // * @throws Exception // */ // public void testJettyServerArgumentNegativeMaximum() throws Exception { // int expectedJettyThreads = SeleniumServer.getJettyThreads(); // // String[] args = new String[] { "-jettyThreads", // String.valueOf(negativeJettyThreadsMaximum) }; // try { // SeleniumServer.main(args); // // Fail if an exception wasn't thrown // fail("Server should not be able to start when given an illegal amount of jettyThreads (" // + negativeJettyThreadsMaximum + ")"); // } catch (IllegalArgumentException ex) { // /* // * Empty catch block // */ // } // assertEquals("Server did not start up correctly from arguments.", // expectedJettyThreads, SeleniumServer.getJettyThreads()); // } // // /** // * Test for a negative result when passing a zero argument for // * -jettyThreads. // * // * @throws Exception // */ // public void testJettyServerArgumentNegativeZero() throws Exception { // int expectedJettyThreads = SeleniumServer.getJettyThreads(); // // String[] args = new String[] { "-jettyThreads", // String.valueOf(negativeJettyThreadsMinimum) }; // try { // SeleniumServer.main(args); // // Fail if an exception wasn't thrown // fail("Server should not be able to start when given an illegal amount of jettyThreads (" // + negativeJettyThreadsMinimum + ")"); // } catch (IllegalArgumentException ex) { // /* // * Empty catch block // */ // } // assertEquals("Server did not start up correctly from arguments.", // expectedJettyThreads, SeleniumServer.getJettyThreads()); // } }
/* * Copyright (c) 2011-2013 The original author or authors * ------------------------------------------------------ * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.core.dns; import java.util.Objects; /** * Exception which is used to notify the {@link io.vertx.core.AsyncResult} * if the DNS query returns a {@link DnsResponseCode} which indicates and error. * * @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a> */ public final class DnsException extends Exception { private DnsResponseCode code; public DnsException(DnsResponseCode code) { Objects.requireNonNull(code, "code"); this.code = code; } /** * The {@link DnsResponseCode} which caused this {@link DnsException} to be created. */ public DnsResponseCode code() { return code; } }
/** * Copyright (c) 2009-2016, Data Geekery GmbH (http://www.datageekery.com) * 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. * * Other licenses: * ----------------------------------------------------------------------------- * Commercial licenses for this work are available. These replace the above * ASL 2.0 and offer limited warranties, support, maintenance, and commercial * database integrations. * * For more information, please visit: http://www.jooq.org/licenses * * * * * * * * * * * * * * * * */ package org.jooq.impl; import static java.util.Arrays.asList; import static org.jooq.Clause.ALTER_TABLE; import static org.jooq.Clause.ALTER_TABLE_ADD; import static org.jooq.Clause.ALTER_TABLE_ALTER; import static org.jooq.Clause.ALTER_TABLE_ALTER_DEFAULT; import static org.jooq.Clause.ALTER_TABLE_DROP; import static org.jooq.Clause.ALTER_TABLE_RENAME; import static org.jooq.Clause.ALTER_TABLE_RENAME_COLUMN; import static org.jooq.Clause.ALTER_TABLE_RENAME_CONSTRAINT; import static org.jooq.Clause.ALTER_TABLE_TABLE; import static org.jooq.SQLDialect.DERBY; import static org.jooq.SQLDialect.FIREBIRD; // ... import static org.jooq.SQLDialect.HSQLDB; // ... import static org.jooq.impl.DSL.constraint; import static org.jooq.impl.DSL.field; import static org.jooq.impl.DSL.inline; import static org.jooq.impl.DSL.name; import static org.jooq.impl.DSL.sql; import static org.jooq.impl.Tools.toSQLDDLTypeDeclaration; import static org.jooq.impl.Tools.DataKey.DATA_CONSTRAINT_REFERENCE; import org.jooq.AlterTableAlterStep; import org.jooq.AlterTableDropStep; import org.jooq.AlterTableFinalStep; import org.jooq.AlterTableRenameColumnToStep; import org.jooq.AlterTableRenameConstraintToStep; import org.jooq.AlterTableStep; import org.jooq.Clause; import org.jooq.Configuration; import org.jooq.Constraint; import org.jooq.Context; import org.jooq.DSLContext; import org.jooq.DataType; import org.jooq.Field; import org.jooq.Name; import org.jooq.SQLDialect; import org.jooq.Table; /** * @author Lukas Eder */ @SuppressWarnings({ "rawtypes", "unchecked" }) final class AlterTableImpl extends AbstractQuery implements // Cascading interface implementations for ALTER TABLE behaviour AlterTableStep, AlterTableDropStep, AlterTableAlterStep, AlterTableRenameColumnToStep, AlterTableRenameConstraintToStep { /** * Generated UID */ private static final long serialVersionUID = 8904572826501186329L; private static final Clause[] CLAUSES = { ALTER_TABLE }; private final Table<?> table; private final boolean ifExists; private Table<?> renameTo; private Field<?> renameColumn; private Field<?> renameColumnTo; private Constraint renameConstraint; private Constraint renameConstraintTo; private Field<?> addColumn; private DataType<?> addColumnType; private Constraint addConstraint; private Field<?> alterColumn; private DataType<?> alterColumnType; private Field<?> alterColumnDefault; private Field<?> dropColumn; private boolean dropColumnCascade; private Constraint dropConstraint; AlterTableImpl(Configuration configuration, Table<?> table) { this(configuration, table, false); } AlterTableImpl(Configuration configuration, Table<?> table, boolean ifExists) { super(configuration); this.table = table; this.ifExists = ifExists; } // ------------------------------------------------------------------------ // XXX: DSL API // ------------------------------------------------------------------------ @Override public final AlterTableImpl renameTo(Table<?> newName) { this.renameTo = newName; return this; } @Override public final AlterTableImpl renameTo(Name newName) { return renameTo(DSL.table(newName)); } @Override public final AlterTableImpl renameTo(String newName) { return renameTo(name(newName)); } @Override public final AlterTableImpl renameColumn(Field<?> oldName) { renameColumn = oldName; return this; } @Override public final AlterTableImpl renameColumn(Name oldName) { return renameColumn(field(oldName)); } @Override public final AlterTableImpl renameColumn(String oldName) { return renameColumn(name(oldName)); } @Override public final AlterTableImpl renameConstraint(Constraint oldName) { renameConstraint = oldName; return this; } @Override public final AlterTableImpl renameConstraint(Name oldName) { return renameConstraint(constraint(oldName)); } @Override public final AlterTableImpl renameConstraint(String oldName) { return renameConstraint(name(oldName)); } @Override public final AlterTableImpl to(Field<?> newName) { if (renameColumn != null) renameColumnTo = newName; else throw new IllegalStateException(); return this; } @Override public final AlterTableImpl to(Constraint newName) { if (renameConstraint != null) renameConstraintTo = newName; else throw new IllegalStateException(); return this; } @Override public final AlterTableImpl to(Name newName) { if (renameColumn != null) return to(field(newName)); else if (renameConstraint != null) return to(constraint(newName)); else throw new IllegalStateException(); } @Override public final AlterTableImpl to(String newName) { return to(name(newName)); } @Override public final <T> AlterTableImpl add(Field<T> field, DataType<T> type) { return addColumn(field, type); } @Override public final AlterTableImpl add(Name field, DataType<?> type) { return addColumn(field, type); } @Override public final AlterTableImpl add(String field, DataType<?> type) { return addColumn(field, type); } @Override public final AlterTableImpl addColumn(String field, DataType<?> type) { return addColumn(name(field), type); } @Override public final AlterTableImpl addColumn(Name field, DataType<?> type) { return addColumn((Field) field(field, type), type); } @Override public final <T> AlterTableImpl addColumn(Field<T> field, DataType<T> type) { addColumn = field; addColumnType = type; return this; } @Override public final AlterTableImpl add(Constraint constraint) { addConstraint = constraint; return this; } @Override public final <T> AlterTableImpl alter(Field<T> field) { return alterColumn(field); } @Override public final AlterTableImpl alter(Name field) { return alterColumn(field); } @Override public final AlterTableImpl alter(String field) { return alterColumn(field); } @Override public final AlterTableImpl alterColumn(Name field) { return alterColumn(field(field)); } @Override public final AlterTableImpl alterColumn(String field) { return alterColumn(name(field)); } @Override public final <T> AlterTableImpl alterColumn(Field<T> field) { alterColumn = field; return this; } @Override public final AlterTableImpl set(DataType type) { alterColumnType = type; return this; } @Override public final AlterTableImpl defaultValue(Object literal) { return defaultValue(Tools.field(literal)); } @Override public final AlterTableImpl defaultValue(Field expression) { alterColumnDefault = expression; return this; } @Override public final AlterTableImpl drop(Field<?> field) { return dropColumn(field); } @Override public final AlterTableImpl drop(Name field) { return dropColumn(field); } @Override public final AlterTableImpl drop(String field) { return dropColumn(field); } @Override public final AlterTableImpl dropColumn(Name field) { return dropColumn(field(field)); } @Override public final AlterTableImpl dropColumn(String field) { return dropColumn(name(field)); } @Override public final AlterTableImpl dropColumn(Field<?> field) { dropColumn = field; return this; } @Override public final AlterTableImpl drop(Constraint constraint) { dropConstraint = constraint; return this; } @Override public final AlterTableImpl dropConstraint(Name constraint) { return drop(DSL.constraint(constraint)); } @Override public final AlterTableImpl dropConstraint(String constraint) { return drop(DSL.constraint(constraint)); } @Override public final AlterTableFinalStep cascade() { dropColumnCascade = true; return this; } @Override public final AlterTableFinalStep restrict() { dropColumnCascade = false; return this; } // ------------------------------------------------------------------------ // XXX: QueryPart API // ------------------------------------------------------------------------ @Override public final void accept(Context<?> ctx) { SQLDialect family = ctx.configuration().dialect().family(); accept0(ctx); } private final void accept0(Context<?> ctx) { SQLDialect family = ctx.family(); boolean omitAlterTable = family == HSQLDB && renameConstraint != null; if (!omitAlterTable) { ctx.start(ALTER_TABLE_TABLE) .keyword("alter table"); if (ifExists) ctx.sql(' ').keyword("if exists"); ctx.sql(' ').visit(table) .end(ALTER_TABLE_TABLE) .formatIndentStart() .formatSeparator(); } if (renameTo != null) { boolean qualify = ctx.qualify(); ctx.start(ALTER_TABLE_RENAME) .qualify(false) .keyword("rename to").sql(' ') .visit(renameTo) .qualify(qualify) .end(ALTER_TABLE_RENAME); } else if (renameColumn != null) { boolean qualify = ctx.qualify(); ctx.start(ALTER_TABLE_RENAME_COLUMN) .qualify(false); switch (ctx.family()) { case H2: case HSQLDB: ctx.keyword("alter column").sql(' ') .visit(renameColumn) .formatSeparator() .keyword("rename to").sql(' ') .visit(renameColumnTo); break; default: ctx.keyword("rename column").sql(' ') .visit(renameColumn) .formatSeparator() .keyword("to").sql(' ') .visit(renameColumnTo); break; } ctx.qualify(qualify) .end(ALTER_TABLE_RENAME_COLUMN); } else if (renameConstraint != null) { boolean qualify = ctx.qualify(); ctx.start(ALTER_TABLE_RENAME_CONSTRAINT); ctx.data(DATA_CONSTRAINT_REFERENCE, true); if (family == HSQLDB) { ctx.qualify(false) .keyword("alter constraint").sql(' ') .visit(renameConstraint) .formatSeparator() .keyword("rename to").sql(' ') .visit(renameConstraintTo) .qualify(qualify); } else { ctx.qualify(false) .keyword("rename constraint").sql(' ') .visit(renameConstraint) .formatSeparator() .keyword("to").sql(' ') .visit(renameConstraintTo) .qualify(qualify); } ctx.data().remove(DATA_CONSTRAINT_REFERENCE); ctx.end(ALTER_TABLE_RENAME_CONSTRAINT); } else if (addColumn != null) { boolean qualify = ctx.qualify(); ctx.start(ALTER_TABLE_ADD) .keyword("add").sql(' '); ctx.qualify(false) .visit(addColumn).sql(' ') .qualify(qualify); toSQLDDLTypeDeclaration(ctx, addColumnType); if (!addColumnType.nullable()) { ctx.sql(' ').keyword("not null"); } // Some databases default to NOT NULL, so explicitly setting columns to NULL is mostly required here // [#3400] [#4321] ... but not in Derby, Firebird else if (!asList(DERBY, FIREBIRD).contains(family)) { ctx.sql(' ').keyword("null"); } ctx.end(ALTER_TABLE_ADD); } else if (addConstraint != null) { boolean qualify = ctx.qualify(); ctx.start(ALTER_TABLE_ADD); ctx.keyword("add") .sql(' ') .qualify(false) .visit(addConstraint) .qualify(qualify); ctx.end(ALTER_TABLE_ADD); } else if (alterColumn != null) { ctx.start(ALTER_TABLE_ALTER); switch (family) { case CUBRID: case MARIADB: case MYSQL: { if (alterColumnDefault == null) { // MySQL's CHANGE COLUMN clause has a mandatory RENAMING syntax... ctx.keyword("change column") .sql(' ').qualify(false).visit(alterColumn).qualify(true); } else { ctx.keyword("alter column"); } break; } default: ctx.keyword("alter"); break; } ctx.sql(' ') .qualify(false) .visit(alterColumn) .qualify(true); if (alterColumnType != null) { switch (family) { case DERBY: ctx.sql(' ').keyword("set data type"); break; case POSTGRES: ctx.sql(' ').keyword("type"); break; } ctx.sql(' '); toSQLDDLTypeDeclaration(ctx, alterColumnType); if (!alterColumnType.nullable()) { ctx.sql(' ').keyword("not null"); } } else if (alterColumnDefault != null) { ctx.start(ALTER_TABLE_ALTER_DEFAULT); switch (family) { default: ctx.keyword("set default"); break; } ctx.sql(' ').visit(alterColumnDefault) .end(ALTER_TABLE_ALTER_DEFAULT); } ctx.end(ALTER_TABLE_ALTER); } else if (dropColumn != null) { ctx.start(ALTER_TABLE_DROP); switch (family) { default: ctx.keyword("drop"); break; } ctx.sql(' ') .qualify(false) .visit(dropColumn) .qualify(true); switch (family) { default: break; } if (dropColumnCascade) { ctx.sql(' ').keyword("cascade"); } ctx.end(ALTER_TABLE_DROP); } else if (dropConstraint != null) { ctx.start(ALTER_TABLE_DROP); ctx.data(DATA_CONSTRAINT_REFERENCE, true); ctx.keyword("drop constraint") .sql(' ') .visit(dropConstraint); ctx.data().remove(DATA_CONSTRAINT_REFERENCE); ctx.end(ALTER_TABLE_DROP); } if (!omitAlterTable) ctx.formatIndentEnd(); } @Override public final Clause[] clauses(Context<?> ctx) { return CLAUSES; } }
/** * Copyright 2019 Yanzheng (https://github.com/micyo202). All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lion.common.lock.locker; import lombok.extern.slf4j.Slf4j; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /** * RedissonDistributedLocker * 分布式锁方法实现 * * @author Yanzheng (https://github.com/micyo202) * @date 2019/05/08 */ @Component @Slf4j public class RedissonDistributedLocker implements DistributedLocker { /** * 锁key值前缀 */ private final static String KEY_PREFIX = "LOCK:"; /** * 默认秒数单位,毫秒 */ private final static TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS; /** * RedissonClient已经由配置类生成,这里自动装配即可 */ @Autowired private RedissonClient redissonClient; /** * 强制加锁 * * 拿不到lock就不罢休,不然线程就一直block * * @param lockKey 锁的key值 * @return 锁信息 */ @Override public RLock lock(String lockKey) { RLock lock = redissonClient.getLock(KEY_PREFIX + lockKey); lock.lock(); return lock; } /** * 强制加锁 * * @param lockKey 锁的key值 * @param leaseTime 加锁时间(默认单位毫秒) * @return 锁信息 */ @Override public RLock lock(String lockKey, long leaseTime) { RLock lock = redissonClient.getLock(KEY_PREFIX + lockKey); lock.lock(leaseTime, TIME_UNIT); return lock; } /** * 强制加锁 * * @param lockKey 锁的key值 * @param unit 时间单位 * @param leaseTime 加锁时间 * @return 锁信息 */ @Override public RLock lock(String lockKey, TimeUnit unit, long leaseTime) { RLock lock = redissonClient.getLock(KEY_PREFIX + lockKey); lock.lock(leaseTime, unit); return lock; } /** * 尝试加锁 * * 马上返回,拿到lock就返回true,不然返回false * 带时间限制的tryLock(),拿不到lock,就等一段时间,超时返回false * * @param lockKey 锁的key值 * @return 是否拿到 */ @Override public boolean tryLock(String lockKey) { RLock lock = redissonClient.getLock(KEY_PREFIX + lockKey); return lock.tryLock(); } /** * 尝试加锁 * * @param lockKey 锁的key值 * @param waitTime 等待时间 * @param leaseTime 加锁时间 * @return 是否拿到标志 */ @Override public boolean tryLock(String lockKey, long waitTime, long leaseTime) { RLock lock = redissonClient.getLock(KEY_PREFIX + lockKey); try { return lock.tryLock(waitTime, leaseTime, TIME_UNIT); } catch (InterruptedException e) { return false; } } /** * 尝试加锁 * * @param lockKey 锁的key值 * @param unit 时间单位 * @param waitTime 等待时间 * @param leaseTime 加锁时间 * @return 是否拿到标志 */ @Override public boolean tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime) { RLock lock = redissonClient.getLock(KEY_PREFIX + lockKey); try { return lock.tryLock(waitTime, leaseTime, unit); } catch (InterruptedException e) { log.error(e.getMessage(), e); return false; } } /** * 解锁 * * @param lockKey 锁的key值 */ @Override public void unlock(String lockKey) { RLock lock = redissonClient.getLock(KEY_PREFIX + lockKey); lock.unlock(); } /** * 解锁 * * @param lock 锁信息 */ @Override public void unlock(RLock lock) { lock.unlock(); } }
package santa.simulator.genomes; import java.util.SortedSet; /** * @author Andrew Rambaut */ public class SimpleGenome extends BaseGenome { public SimpleGenome() { } public void duplicate(SimpleGenome source) { this.sequence = new SimpleSequence(source.sequence); this.fitnessCache = source.fitnessCache.clone(); this.descriptor = source.descriptor; setLogFitness(source.getLogFitness()); assert(this.descriptor.getGenomeLength() == this.sequence.getLength()); } public int getLength() { return sequence.getLength(); } public byte getNucleotide(int site) { return sequence.getNucleotide(site); } public void setSequence(Sequence sequence) { this.sequence = new SimpleSequence(sequence); } /** * Gets a byte array representing the entire sequence. If the genome stores * differences rather than a complete sequence, then this may be an inefficient * way of accessing each state. * * @return a byte array containing sequence states */ public Sequence getSequence() { return sequence; } /** * Apply an array of mutations to the genome. The new mutation array may not have the mutations * in positional order. The mutation array for the genome (mutations from the master sequence) * must be in positional order. * @param newMutations the array of new mutations in positional order */ public void applyMutations(SortedSet<Mutation> newMutations) { GenomeDescription gd = null; assert(this.descriptor.getGenomeLength() == getLength()); for (Mutation m : newMutations) { int l = getLength(); if (m.apply(this)) { // If the genome length changes, a new, updated GenomeDescription object must be created. The // genome description objects are linked together in a tree so we can trace the evolutionary history of // indel events for a genome. int nl = getLength(); if (l != nl) { if (gd == null) { gd = GenomeDescription.applyIndel(this.descriptor, m.position, m.length()); this.descriptor = gd; this.fitnessCache = null; assert(descriptor.getGenomeLength() == getLength()); } } assert(descriptor.getGenomeLength() == getLength()); incrementTotalMutationCount(); } } assert(this.descriptor.getGenomeLength() == sequence.getLength()); } /** * Substitution mutation effector function. Substitute one * nucleotide at a single site for another. * * @param position integer position relative to beginning of genome where the substitution should be made. * @param state new nucleotide at site. Coded as integer 0-3 = {A,C,G,T} * @return boolean indication whether state was changed at designated site. **/ public boolean substitute(int position, byte state) { assert(state >= 0 && state <= 3); assert(position >=0 && position < sequence.getLength()); byte oldState = sequence.getNucleotide(position); if (state != oldState) sequence.setNucleotide(position, state); return(state != oldState); } /** * Deletion mutation effector function. Deletes nucleotides at * designated position relative to start of genome. If there are * fewer than `count` elements available, do not change anything * and return `false` * Note-to-future: If there are fewer elements available than * requested, it is important to NOT just delete what is * available. Doing so might throw the feature out-of-frame. * * @param position non-negative integer position of first nucletide to be deleted. * @param count number of nucleotides to be deleted. * @return boolean indication of success **/ public boolean delete(int position, int count) { assert(count >= 0); assert(position >=0 && position < sequence.getLength()); int avail = Math.min(count, sequence.getLength()-position); if (count != avail) return false; return sequence.deleteSubSequence(position, count); } /** * Insertion mutation effector function. Inserts nucleotides at * designated position relative to start of genome. * * @param position non-negative integer position at which insertion begins. * @param seq nucleotides to be inserted. * @return boolean indication of success **/ public boolean insert(int position, SimpleSequence seq) { return sequence.insertSequence(position, seq); } public Genome copy() { SimpleGenome g = new SimpleGenome(); g.duplicate(this); return g; } // private members /** * The sequence of nucleotides making up this genome. * This sequence is continually maintained in the face of substitutions, insertions, and deletions. */ private SimpleSequence sequence = null; }
package com.dexesttp.hkxpack.resources.byteutils; import static org.junit.Assert.*; import org.junit.Test; /** * Tests the {@link ULongByteUtils} class */ public class ULongByteUtilsTest { @Test /** * Test */ public void getUIntSize2ShouldWorkFor0() { assertArrayEquals("Long(2) : 0 => 0", new byte[]{0, 0}, ULongByteUtils.fromLong(0, 2)); } @Test /** * Test */ public void getUIntSize2ShouldWorkFor1() { assertArrayEquals("Long(2) : 1 => 1", new byte[]{1, 0}, ULongByteUtils.fromLong(1, 2)); } @Test /** * Test */ public void getUIntSize2ShouldWorkForMaxValue() { assertArrayEquals("Long(2) : 65535 => 65535", new byte[]{-1, -1}, ULongByteUtils.fromLong(65535, 2)); } @Test /** * Test */ public void getUIntSize2ShouldWorkFor30() { assertArrayEquals("Long(2) : 30 => 30", new byte[]{30, 0}, ULongByteUtils.fromLong(30, 2)); } }
/* * 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.kafka.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.kafka.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ClusterInfo JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ClusterInfoJsonUnmarshaller implements Unmarshaller<ClusterInfo, JsonUnmarshallerContext> { public ClusterInfo unmarshall(JsonUnmarshallerContext context) throws Exception { ClusterInfo clusterInfo = new ClusterInfo(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("activeOperationArn", targetDepth)) { context.nextToken(); clusterInfo.setActiveOperationArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("brokerNodeGroupInfo", targetDepth)) { context.nextToken(); clusterInfo.setBrokerNodeGroupInfo(BrokerNodeGroupInfoJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("clientAuthentication", targetDepth)) { context.nextToken(); clusterInfo.setClientAuthentication(ClientAuthenticationJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("clusterArn", targetDepth)) { context.nextToken(); clusterInfo.setClusterArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("clusterName", targetDepth)) { context.nextToken(); clusterInfo.setClusterName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("creationTime", targetDepth)) { context.nextToken(); clusterInfo.setCreationTime(DateJsonUnmarshallerFactory.getInstance("iso8601").unmarshall(context)); } if (context.testExpression("currentBrokerSoftwareInfo", targetDepth)) { context.nextToken(); clusterInfo.setCurrentBrokerSoftwareInfo(BrokerSoftwareInfoJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("currentVersion", targetDepth)) { context.nextToken(); clusterInfo.setCurrentVersion(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("encryptionInfo", targetDepth)) { context.nextToken(); clusterInfo.setEncryptionInfo(EncryptionInfoJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("enhancedMonitoring", targetDepth)) { context.nextToken(); clusterInfo.setEnhancedMonitoring(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("openMonitoring", targetDepth)) { context.nextToken(); clusterInfo.setOpenMonitoring(OpenMonitoringJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("loggingInfo", targetDepth)) { context.nextToken(); clusterInfo.setLoggingInfo(LoggingInfoJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("numberOfBrokerNodes", targetDepth)) { context.nextToken(); clusterInfo.setNumberOfBrokerNodes(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("state", targetDepth)) { context.nextToken(); clusterInfo.setState(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("stateInfo", targetDepth)) { context.nextToken(); clusterInfo.setStateInfo(StateInfoJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("tags", targetDepth)) { context.nextToken(); clusterInfo.setTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context.getUnmarshaller(String.class)) .unmarshall(context)); } if (context.testExpression("zookeeperConnectString", targetDepth)) { context.nextToken(); clusterInfo.setZookeeperConnectString(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("zookeeperConnectStringTls", targetDepth)) { context.nextToken(); clusterInfo.setZookeeperConnectStringTls(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return clusterInfo; } private static ClusterInfoJsonUnmarshaller instance; public static ClusterInfoJsonUnmarshaller getInstance() { if (instance == null) instance = new ClusterInfoJsonUnmarshaller(); return instance; } }
package contagionJVM.Repository; @SuppressWarnings("UnusedDeclaration") public class DMRoleRepository { }
/* * 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.hop.pipeline.transforms.rowstoresult; import org.apache.hop.core.CheckResult; import org.apache.hop.core.ICheckResult; import org.apache.hop.core.annotations.Transform; import org.apache.hop.core.exception.HopTransformException; import org.apache.hop.core.exception.HopXmlException; import org.apache.hop.core.row.IRowMeta; import org.apache.hop.core.variables.IVariables; import org.apache.hop.i18n.BaseMessages; import org.apache.hop.metadata.api.IHopMetadataProvider; import org.apache.hop.pipeline.Pipeline; import org.apache.hop.pipeline.PipelineMeta; import org.apache.hop.pipeline.transform.BaseTransformMeta; import org.apache.hop.pipeline.transform.ITransform; import org.apache.hop.pipeline.transform.ITransformMeta; import org.apache.hop.pipeline.transform.TransformMeta; import org.w3c.dom.Node; import java.util.List; @Transform( id = "RowsToResult", image = "rowstoresult.svg", name = "i18n::BaseTransform.TypeLongDesc.RowsToResult", description = "i18n::BaseTransform.TypeTooltipDesc.RowsToResult", categoryDescription = "i18n:org.apache.hop.pipeline.transform:BaseTransform.Category.Workflow", documentationUrl = "https://hop.apache.org/manual/latest/pipeline/transforms/copyrowstoresult.html") public class RowsToResultMeta extends BaseTransformMeta implements ITransformMeta<RowsToResult, RowsToResultData> { private static final Class<?> PKG = RowsToResult.class; // For Translator public RowsToResultMeta() { super(); // allocate BaseTransformMeta } @Override public void loadXml(Node transformNode, IHopMetadataProvider metadataProvider) throws HopXmlException { readData(transformNode); } @Override public Object clone() { Object retval = super.clone(); return retval; } @Override public ITransform createTransform( TransformMeta transformMeta, RowsToResultData data, int copyNr, PipelineMeta pipelineMeta, Pipeline pipeline) { return new RowsToResult(transformMeta, this, data, copyNr, pipelineMeta, pipeline); } private void readData(Node transformNode) {} @Override public void setDefault() {} @Override public void getFields( IRowMeta rowMeta, String origin, IRowMeta[] info, TransformMeta nextTransform, IVariables variables, IHopMetadataProvider metadataProvider) throws HopTransformException { // Default: nothing changes to rowMeta } @Override public void check( List<ICheckResult> remarks, PipelineMeta pipelineMeta, TransformMeta transformMeta, IRowMeta prev, String[] input, String[] output, IRowMeta info, IVariables variables, IHopMetadataProvider metadataProvider) { // See if we have input streams leading to this transform! if (input.length > 0) { CheckResult cr = new CheckResult( ICheckResult.TYPE_RESULT_OK, BaseMessages.getString( PKG, "RowsToResultMeta.CheckResult.TransformReceivingInfoFromOtherTransforms"), transformMeta); remarks.add(cr); } else { CheckResult cr = new CheckResult( ICheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(PKG, "RowsToResultMeta.CheckResult.NoInputReceivedError"), transformMeta); remarks.add(cr); } } @Override public RowsToResultData getTransformData() { return new RowsToResultData(); } }
package jp.gr.java_conf.ke.foca.internal.injector; import java.lang.annotation.Annotation; import jp.gr.java_conf.ke.foca.DIContents; import jp.gr.java_conf.ke.foca.annotation.exit.View; import jp.gr.java_conf.ke.foca.DefinitionNotFound; import jp.gr.java_conf.ke.foca.FocaException; import jp.gr.java_conf.ke.foca.annotation.entrance.InterfaceAdapter; import jp.gr.java_conf.ke.foca.internal.adapter.AdapterFactory; import jp.gr.java_conf.ke.namespace.foca.Aspect; import jp.gr.java_conf.ke.namespace.foca.Converter; import jp.gr.java_conf.ke.namespace.foca.Presenter; /** * Created by YT on 2017/03/26. */ class PresenterInjector extends Injector { PresenterInjector(DIContents containts, String adapterName, AdapterFactory factory) { super(containts, adapterName, factory); } @Override InterfaceAdapter<?, ?> getAdapter(DIContents contents, String presenterName) throws FocaException { Presenter presenter = contents.selectPresenter(presenterName).rawValue(); Class<? extends Annotation> inputPortClass = View.class; if (presenter == null) { throw new DefinitionNotFound(getFieldName(), presenterName, inputPortClass); } Converter cnv = presenter.getConverter(); Iterable<Aspect> aspects = contents.aspecters(); return factory().createAdapter( cnv, inputPortClass, presenter.getView(), aspects); } }
package deltix.qsrv.hf.tickdb.comm.server; import deltix.gflog.Log; import deltix.gflog.LogLevel; import deltix.util.time.TimeKeeper; import java.io.*; import java.security.Principal; import java.util.Date; import java.util.logging.LogRecord; import java.util.logging.SimpleFormatter; public class UserLogger { public static final String CONNECT_PATTERN = "CONNECT"; public static final String CONNECTED_PATTERN = "CONNECTED"; public static final String DISCONNECT_PATTERN = "DISCONNECT"; public static final String CREATE_STREAM_PATTERN = "CREATE STREAM (%s)"; public static final String DELETE_STREAM_PATTERN = "DELETE STREAM (%s)"; public static final String RENAME_STREAM_PATTERN = "RENAME STREAM (%s)"; public static final String CREATE_CURSOR_PATTERN = "CREATE CURSOR %s"; public static final String CREATE_LOADER_PATTERN = "CREATE LOADER (%s)"; public static final String CLOSE_CURSOR_PATTERN = "CLOSE CURSOR %s: [%s]"; public static final String CLOSE_LOADER_PATTERN = "CLOSE LOADER (%s)"; public static final String SUBSCRIBE_PATTERN = "SUBSCRIBE %s: %s"; public static final String UNSUBSCRIBE_PATTERN = "UNSUBSCRIBE %s: %s"; private static final String PATTERN = "[user=%s, ip=%s, app=%s] %s"; private static Log logger = deltix.gflog.LogFactory.getLog("deltix.user.logger"); // public static boolean isEnabled(Principal user) { // return user != null && logger != null; // } public static boolean canTrace(Principal user) { return logger.isEnabled(LogLevel.DEBUG); } public static void trace (Principal user, String address, String appId, String pattern, Object ... args) { log(LogLevel.DEBUG, user, address, appId, pattern, args); } private static String getUserName(Principal user) { return user != null ? user.getName() : "<none>"; } public static void log (LogLevel level, Principal user, String address, String appId, String pattern, Object ... args) { if (logger.isEnabled(level)) logger.log(level).append(String.format(PATTERN, getUserName(user), address, appId, String.format(pattern, args))).commit(); } public static void log (LogLevel level, Principal user, String address, String appId, String message) { if (logger.isEnabled(level)) logger.log(level).append(String.format(PATTERN, getUserName(user), address, appId, message)).commit(); } public static void warn (Principal user, String address, String appId, String message, Throwable error) { log(LogLevel.WARN, user, address, appId, message, error); } public static void severe (Principal user, String address, String appId, String message, Throwable error) { log(LogLevel.FATAL, user, address, appId, message, error); } public static void log (LogLevel level, Principal user, String address, String appId, String message, Throwable error) { if (logger.isEnabled(level)) logger.log(level).append(String.format(PATTERN, getUserName(user), address, appId, message)).append(error).commit(); } private static class Formatter extends SimpleFormatter { private final Date time = new Date(); @Override public synchronized String format(LogRecord record) { String message = formatMessage(record); String throwable = ""; time.setTime(TimeKeeper.currentTime); Throwable thrown = record.getThrown(); if (thrown != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(); thrown.printStackTrace(pw); pw.close(); throwable = sw.toString(); return String.format("%1$tm-%1$te-%1$tY %1$tH:%1$tM:%1$tS, %2$s %3$s%n", time, message, throwable); } return String.format("%1$tm-%1$te-%1$tY %1$tH:%1$tM:%1$tS, %2$s%n", time, message); } } }
package org.iota.ict.model.transfer; import org.iota.ict.model.bc.BalanceChange; import org.iota.ict.model.bc.BalanceChangeBuilder; import org.iota.ict.model.transaction.Transaction; import org.iota.ict.model.transaction.TransactionBuilder; import org.iota.ict.utils.crypto.SignatureSchemeImplementation; import java.math.BigInteger; public class InputBuilder extends BalanceChangeBuilder { private final SignatureSchemeImplementation.PrivateKey privateKey; public InputBuilder(SignatureSchemeImplementation.PrivateKey privateKey, BigInteger value) { super(privateKey.deriveAddress(), value, privateKey.length() / Transaction.Field.SIGNATURE_FRAGMENTS.tryteLength); this.privateKey = privateKey; if(value.compareTo(BigInteger.ZERO) >= 0) throw new IllegalArgumentException("Value must be negative in input."); } public BalanceChange build(String bundleHash) { SignatureSchemeImplementation.Signature signature = privateKey.sign(bundleHash); if(signature.fragments() != buildersFromTailToHead.length) throw new IllegalStateException("BalanceChange has reserved " + buildersFromTailToHead.length + " transactions but signature length is " + signature.length() + " trytes."); for(int i = 0; i < buildersFromTailToHead.length; i++) { SignatureSchemeImplementation.Signature signatureFragment = signature.getFragment(i); buildersFromTailToHead[i].signatureFragments = signatureFragment.toString(); } return new BalanceChange(getAddress(), getValue(), signature.toString()); } @Override public String getEssence() { StringBuilder essence = new StringBuilder(); for (TransactionBuilder builder : buildersFromTailToHead) { essence.insert(0, builder.getEssence()); } return essence.toString(); } }
/* *AVISO LEGAL © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.inventario.presentation.web.jsf.sessionbean; import java.util.Set; import java.util.HashSet; import java.util.ArrayList; import java.util.Date; import java.io.Serializable; import com.bydan.framework.erp.util.Constantes; import com.bydan.erp.inventario.business.entity.*; @SuppressWarnings("unused") public class NivelLineaSessionBean extends NivelLineaSessionBeanAdditional { private static final long serialVersionUID = 1L; protected Boolean isPermiteNavegacionHaciaForeignKeyDesdeNivelLinea; protected Boolean isPermiteRecargarInformacion; protected String sNombrePaginaNavegacionHaciaForeignKeyDesdeNivelLinea; protected Boolean isBusquedaDesdeForeignKeySesionForeignKeyNivelLinea; protected Long lIdNivelLineaActualForeignKey; protected Long lIdNivelLineaActualForeignKeyParaPosibleAtras; protected Boolean isBusquedaDesdeForeignKeySesionForeignKeyNivelLineaParaPosibleAtras; protected String sUltimaBusquedaNivelLinea; protected String sServletGenerarHtmlReporte; protected Integer iNumeroPaginacion; protected Integer iNumeroPaginacionPagina; protected String sPathNavegacionActual=""; protected Boolean isPaginaPopup=false; protected String sStyleDivArbol=""; protected String sStyleDivContent=""; protected String sStyleDivOpcionesBanner=""; protected String sStyleDivExpandirColapsar=""; protected String sFuncionBusquedaRapida=""; private Long id; private String nombre; protected Boolean conGuardarRelaciones=false; protected Boolean estaModoGuardarRelaciones=false; protected Boolean esGuardarRelacionado=false; protected Boolean estaModoBusqueda=false; protected Boolean noMantenimiento=false; protected NivelLineaSessionBeanAdditional nivellineaSessionBeanAdditional=null; public NivelLineaSessionBeanAdditional getNivelLineaSessionBeanAdditional() { return this.nivellineaSessionBeanAdditional; } public void setNivelLineaSessionBeanAdditional(NivelLineaSessionBeanAdditional nivellineaSessionBeanAdditional) { try { this.nivellineaSessionBeanAdditional=nivellineaSessionBeanAdditional; } catch(Exception e) { ; } } public NivelLineaSessionBean () { this.inicializarNivelLineaSessionBean(); } public void inicializarNivelLineaSessionBean () { this.isPermiteNavegacionHaciaForeignKeyDesdeNivelLinea=false; this.isPermiteRecargarInformacion=false; this.sNombrePaginaNavegacionHaciaForeignKeyDesdeNivelLinea=""; this.isBusquedaDesdeForeignKeySesionForeignKeyNivelLinea=false; this.lIdNivelLineaActualForeignKey=0L; this.lIdNivelLineaActualForeignKeyParaPosibleAtras=0L; this.isBusquedaDesdeForeignKeySesionForeignKeyNivelLineaParaPosibleAtras=false; this.sUltimaBusquedaNivelLinea =""; this.sServletGenerarHtmlReporte=""; this.iNumeroPaginacion=10; this.iNumeroPaginacionPagina=0; this.sPathNavegacionActual=""; this.sFuncionBusquedaRapida=""; this.sStyleDivArbol="display:table-row;width:20%;height:800px;visibility:visible"; this.sStyleDivContent="height:600px;width:80%"; this.sStyleDivOpcionesBanner="display:table-row"; this.sStyleDivExpandirColapsar="display:table-row"; this.isPaginaPopup=false; this.estaModoGuardarRelaciones=true; this.conGuardarRelaciones=false; this.esGuardarRelacionado=false; this.estaModoBusqueda=false; this.noMantenimiento=false; this.nombre=""; } public void setPaginaPopupVariables(Boolean isPopupVariables) { if(isPopupVariables) { if(!this.isPaginaPopup) { this.sStyleDivArbol="display:none;width:0px;height:0px;visibility:hidden"; this.sStyleDivContent="height:800px;width:100%";; this.sStyleDivOpcionesBanner="display:none"; this.sStyleDivExpandirColapsar="display:none"; this.isPaginaPopup=true; } } else { if(this.isPaginaPopup) { this.sStyleDivArbol="display:table-row;width:15%;height:600px;visibility:visible;overflow:auto;"; this.sStyleDivContent="height:600px;width:80%"; this.sStyleDivOpcionesBanner="display:table-row"; this.sStyleDivExpandirColapsar="display:table-row"; this.isPaginaPopup=false; } } } public Boolean getisPermiteNavegacionHaciaForeignKeyDesdeNivelLinea() { return this.isPermiteNavegacionHaciaForeignKeyDesdeNivelLinea; } public void setisPermiteNavegacionHaciaForeignKeyDesdeNivelLinea( Boolean isPermiteNavegacionHaciaForeignKeyDesdeNivelLinea) { this.isPermiteNavegacionHaciaForeignKeyDesdeNivelLinea= isPermiteNavegacionHaciaForeignKeyDesdeNivelLinea; } public Boolean getisPermiteRecargarInformacion() { return this.isPermiteRecargarInformacion; } public void setisPermiteRecargarInformacion( Boolean isPermiteRecargarInformacion) { this.isPermiteRecargarInformacion=isPermiteRecargarInformacion; } public String getsNombrePaginaNavegacionHaciaForeignKeyDesdeNivelLinea() { return this.sNombrePaginaNavegacionHaciaForeignKeyDesdeNivelLinea; } public void setsNombrePaginaNavegacionHaciaForeignKeyDesdeNivelLinea(String sNombrePaginaNavegacionHaciaForeignKeyDesdeNivelLinea) { this.sNombrePaginaNavegacionHaciaForeignKeyDesdeNivelLinea = sNombrePaginaNavegacionHaciaForeignKeyDesdeNivelLinea; } public Boolean getisBusquedaDesdeForeignKeySesionForeignKeyNivelLinea() { return isBusquedaDesdeForeignKeySesionForeignKeyNivelLinea; } public void setisBusquedaDesdeForeignKeySesionForeignKeyNivelLinea( Boolean isBusquedaDesdeForeignKeySesionForeignKeyNivelLinea) { this.isBusquedaDesdeForeignKeySesionForeignKeyNivelLinea= isBusquedaDesdeForeignKeySesionForeignKeyNivelLinea; } public Long getlIdNivelLineaActualForeignKey() { return lIdNivelLineaActualForeignKey; } public void setlIdNivelLineaActualForeignKey( Long lIdNivelLineaActualForeignKey) { this.lIdNivelLineaActualForeignKey = lIdNivelLineaActualForeignKey; } public Long getlIdNivelLineaActualForeignKeyParaPosibleAtras() { return lIdNivelLineaActualForeignKeyParaPosibleAtras; } public void setlIdNivelLineaActualForeignKeyParaPosibleAtras( Long lIdNivelLineaActualForeignKeyParaPosibleAtras) { this.lIdNivelLineaActualForeignKeyParaPosibleAtras = lIdNivelLineaActualForeignKeyParaPosibleAtras; } public Boolean getisBusquedaDesdeForeignKeySesionForeignKeyNivelLineaParaPosibleAtras() { return isBusquedaDesdeForeignKeySesionForeignKeyNivelLineaParaPosibleAtras; } public void setisBusquedaDesdeForeignKeySesionForeignKeyNivelLineaParaPosibleAtras( Boolean isBusquedaDesdeForeignKeySesionForeignKeyNivelLineaParaPosibleAtras) { this.isBusquedaDesdeForeignKeySesionForeignKeyNivelLineaParaPosibleAtras = isBusquedaDesdeForeignKeySesionForeignKeyNivelLineaParaPosibleAtras; } public String getsUltimaBusquedaNivelLinea() { return sUltimaBusquedaNivelLinea; } public void setsUltimaBusquedaNivelLinea(String sUltimaBusquedaNivelLinea) { this.sUltimaBusquedaNivelLinea = sUltimaBusquedaNivelLinea; } public String getsServletGenerarHtmlReporte() { return sServletGenerarHtmlReporte; } public void setsServletGenerarHtmlReporte(String sServletGenerarHtmlReporte) { this.sServletGenerarHtmlReporte = sServletGenerarHtmlReporte; } public Integer getiNumeroPaginacion() { return iNumeroPaginacion; } public void setiNumeroPaginacion(Integer iNumeroPaginacion) { this.iNumeroPaginacion= iNumeroPaginacion; } public Integer getiNumeroPaginacionPagina() { return iNumeroPaginacionPagina; } public void setiNumeroPaginacionPagina(Integer iNumeroPaginacionPagina) { this.iNumeroPaginacionPagina= iNumeroPaginacionPagina; } public String getsPathNavegacionActual() { return this.sPathNavegacionActual; } public void setsPathNavegacionActual(String sPathNavegacionActual) { this.sPathNavegacionActual = sPathNavegacionActual; } public Boolean getisPaginaPopup() { return this.isPaginaPopup; } public void setisPaginaPopup(Boolean isPaginaPopup) { this.isPaginaPopup = isPaginaPopup; } public String getsStyleDivArbol() { return this.sStyleDivArbol; } public void setsStyleDivArbol(String sStyleDivArbol) { this.sStyleDivArbol = sStyleDivArbol; } public String getsStyleDivContent() { return this.sStyleDivContent; } public void setsStyleDivContent(String sStyleDivContent) { this.sStyleDivContent = sStyleDivContent; } public String getsStyleDivOpcionesBanner() { return this.sStyleDivOpcionesBanner; } public void setsStyleDivOpcionesBanner(String sStyleDivOpcionesBanner) { this.sStyleDivOpcionesBanner = sStyleDivOpcionesBanner; } public String getsStyleDivExpandirColapsar() { return this.sStyleDivExpandirColapsar; } public void setsStyleDivExpandirColapsar(String sStyleDivExpandirColapsar) { this.sStyleDivExpandirColapsar = sStyleDivExpandirColapsar; } public String getsFuncionBusquedaRapida() { return this.sFuncionBusquedaRapida; } public void setsFuncionBusquedaRapida(String sFuncionBusquedaRapida) { this.sFuncionBusquedaRapida = sFuncionBusquedaRapida; } public Boolean getConGuardarRelaciones() { return this.conGuardarRelaciones; } public void setConGuardarRelaciones(Boolean conGuardarRelaciones) { this.conGuardarRelaciones = conGuardarRelaciones; } public Boolean getEstaModoGuardarRelaciones() { return this.estaModoGuardarRelaciones; } public void setEstaModoGuardarRelaciones(Boolean estaModoGuardarRelaciones) { this.estaModoGuardarRelaciones = estaModoGuardarRelaciones; } public Boolean getEsGuardarRelacionado() { return this.esGuardarRelacionado; } public void setEsGuardarRelacionado(Boolean esGuardarRelacionado) { this.esGuardarRelacionado = esGuardarRelacionado; } public Boolean getEstaModoBusqueda() { return this.estaModoBusqueda; } public void setEstaModoBusqueda(Boolean estaModoBusqueda) { this.estaModoBusqueda = estaModoBusqueda; } public Boolean getNoMantenimiento() { return this.noMantenimiento; } public void setNoMantenimiento(Boolean noMantenimiento) { this.noMantenimiento = noMantenimiento; } public Long getid() { return this.id; } public String getnombre() { return this.nombre; } public void setid(Long newid)throws Exception { try { if(this.id!=newid) { if(newid==null) { //newid=0L; if(Constantes.ISDEVELOPING) { System.out.println("NivelLinea:Valor nulo no permitido en columna id"); } } this.id=newid; } } catch(Exception e) { throw e; } } public void setnombre(String newnombre)throws Exception { try { if(this.nombre!=newnombre) { if(newnombre==null) { //newnombre=""; if(Constantes.ISDEVELOPING) { System.out.println("NivelLinea:Valor nulo no permitido en columna nombre"); } } if(newnombre!=null&&newnombre.length()>150) { newnombre=newnombre.substring(0,148); System.out.println("NivelLinea:Ha sobrepasado el numero maximo de caracteres permitidos,Maximo=150 en columna nombre"); } this.nombre=newnombre; } } catch(Exception e) { throw e; } } }
// Write a program to input an integer T and // then T lines each containing two integers A & B from user and print T lines // conatining HCF of two given 2 numbers A and B. import java.lang.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int n= sc.nextInt(); int [][] a = new int[n][2]; for (int i=0; i<n; i++){ for (int j=0; j<2; j++){ a[i][j]= sc.nextInt(); } } for (int i=0; i<n; i++){ int hcf=1; int x = 2; while ( x<= a[i][1] && x <= a[i][0]){ if (a[i][1]%x==0 && a[i][0]%x==0){ a[i][0]= a[i][0]/x; a[i][1]= a[i][1]/x; hcf = hcf*x; } else { x++; } } System.out.println(hcf); } } }
/* * Copyright 2013 NGDATA nv * * 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.ngdata.hbaseindexer.indexer; import static com.ngdata.hbaseindexer.metrics.IndexerMetricsUtil.metricName; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Meter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.SolrInputDocument; /** * Writes updates (new documents and deletes) directly to a SolrServer. * <p> * There are two main pieces of functionality that this class provides, both related to error handling in Solr: * <h3>Selective swallowing of errors</h3> * If a write to Solr throws an exception signifying that the underlying problem is related to Solr, then the exception * will be thrown up the stack. The intention of this behaviour is to allow the write to be re-tried indefinitely until * the Solr issue is resolved. * <p> * If a write to Solr throws an exception signifying that the underlying problem lies with the document being written, * then the exception will be logged, but otherwise ignored. The intention of this behaviour is to stop a single bad * document from holding up the whole indexing process for other documents. * * <h3>Individual retry of documents</h3> * If a single document in a batch causes an exception to be thrown that is related to the document itself, then each * update will be retried individually. */ public class DirectSolrInputDocumentWriter implements SolrInputDocumentWriter { private Log log = LogFactory.getLog(getClass()); private SolrServer solrServer; private Meter indexAddMeter; private Meter indexDeleteMeter; private Meter solrAddErrorMeter; private Meter solrDeleteErrorMeter; private Meter documentAddErrorMeter; private Meter documentDeleteErrorMeter; public DirectSolrInputDocumentWriter(String indexName, SolrServer solrServer) { this.solrServer = solrServer; indexAddMeter = Metrics.newMeter(metricName(getClass(), "Index adds", indexName), "Documents added to Solr index", TimeUnit.SECONDS); indexDeleteMeter = Metrics.newMeter(metricName(getClass(), "Index deletes", indexName), "Documents deleted from Solr index", TimeUnit.SECONDS); solrAddErrorMeter = Metrics.newMeter(metricName(getClass(), "Solr add errors", indexName), "Documents not added to Solr due to Solr errors", TimeUnit.SECONDS); solrDeleteErrorMeter = Metrics.newMeter(metricName(getClass(), "Solr delete errors", indexName), "Documents not deleted from Solr due to Solr errors", TimeUnit.SECONDS); documentAddErrorMeter = Metrics.newMeter(metricName(getClass(), "Document add errors", indexName), "Documents not added to Solr due to document errors", TimeUnit.SECONDS); documentDeleteErrorMeter = Metrics.newMeter(metricName(getClass(), "Document delete errors", indexName), "Documents not deleted from Solr due to document errors", TimeUnit.SECONDS); } private boolean isDocumentIssue(SolrException e) { return e.code() == ErrorCode.BAD_REQUEST.code; } private void logOrThrowSolrException(SolrException solrException) { if (isDocumentIssue(solrException)) { log.error("Error updating Solr", solrException); } else { throw solrException; } } /** * Write a list of documents to Solr. * <p> * If a server occurs while writing the update, the exception will be thrown up the stack. If one or more of the * documents contain issues, the error will be logged and swallowed, with all other updates being performed. */ @Override public void add(int shard, Map<String, SolrInputDocument> inputDocumentMap) throws SolrServerException, IOException { Collection<SolrInputDocument> inputDocuments = inputDocumentMap.values(); try { solrServer.add(inputDocuments); indexAddMeter.mark(inputDocuments.size()); } catch (SolrException e) { if (isDocumentIssue(e)) { retryAddsIndividually(inputDocuments); } else { solrAddErrorMeter.mark(inputDocuments.size()); throw e; } } catch (SolrServerException sse) { solrAddErrorMeter.mark(inputDocuments.size()); throw sse; } } private void retryAddsIndividually(Collection<SolrInputDocument> inputDocuments) throws SolrServerException, IOException { for (SolrInputDocument inputDocument : inputDocuments) { try { solrServer.add(inputDocument); indexAddMeter.mark(); } catch (SolrException e) { logOrThrowSolrException(e); // No exception thrown through, so we can update the metric documentAddErrorMeter.mark(); } } } /** * Delete a list of documents ids from Solr. * <p> * If a server occurs while performing the delete, the exception will be thrown up the stack. If one or more of the * deletes cause issues, the error will be logged and swallowed, with all other updates being performed. */ @Override public void deleteById(int shard, List<String> idsToDelete) throws SolrServerException, IOException { try { solrServer.deleteById(idsToDelete); indexDeleteMeter.mark(idsToDelete.size()); } catch (SolrException e) { if (isDocumentIssue(e)) { retryDeletesIndividually(idsToDelete); } else { solrDeleteErrorMeter.mark(idsToDelete.size()); throw e; } } catch (SolrServerException sse) { solrDeleteErrorMeter.mark(idsToDelete.size()); throw sse; } } private void retryDeletesIndividually(List<String> idsToDelete) throws SolrServerException, IOException { for (String idToDelete : idsToDelete) { try { solrServer.deleteById(idToDelete); indexDeleteMeter.mark(); } catch (SolrException e) { logOrThrowSolrException(e); // No exception thrown through, so we can update the metric documentDeleteErrorMeter.mark(); } } } /** * Has the same behavior as {@link SolrServer#deleteByQuery(String)}. * * @param deleteQuery delete query to be executed */ @Override public void deleteByQuery(String deleteQuery) throws SolrServerException, IOException { try { solrServer.deleteByQuery(deleteQuery); } catch (SolrException e) { if (isDocumentIssue(e)) { documentDeleteErrorMeter.mark(1); } else { solrDeleteErrorMeter.mark(1); throw e; } } catch (SolrServerException sse) { solrDeleteErrorMeter.mark(1); throw sse; } } @Override public void close() { solrServer.shutdown(); } }
/* * Copyright 2012 Alex Usachev, thothbot@gmail.com * * This file is part of Parallax project. * * Parallax is free software: you can redistribute it and/or modify it * under the terms of the Creative Commons Attribution 3.0 Unported License. * * Parallax is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the Creative Commons Attribution * 3.0 Unported License. for more details. * * You should have received a copy of the the Creative Commons Attribution * 3.0 Unported License along with Parallax. * If not, see http://creativecommons.org/licenses/by/3.0/. */ package thothbot.parallax.core.client.gl2.enums; import thothbot.parallax.core.client.gl2.WebGLConstants; public enum FramebufferSlot implements GLEnum { COLOR_ATTACHMENT0(WebGLConstants.COLOR_ATTACHMENT0), DEPTH_ATTACHMENT(WebGLConstants.DEPTH_ATTACHMENT), STENCIL_ATTACHMENT(WebGLConstants.STENCIL_ATTACHMENT), DEPTH_STENCIL_ATTACHMENT(WebGLConstants.DEPTH_STENCIL_ATTACHMENT); private final int value; private FramebufferSlot(int value) { this.value = value; } @Override public int getValue() { return value; } }
package com.verdantartifice.primalmagick.common.runes; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.verdantartifice.primalmagick.PrimalMagick; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Rarity; /** * Base definition of a rune data structure. Runes come in different types and can be combined on items * to grant enchantment effects. Also contains a static registry of all types of runes in the mod. * * @author Daedalus4096 */ public abstract class Rune { protected static final Map<ResourceLocation, Rune> REGISTRY = new HashMap<>(); public static final SourceRune EARTH = new SourceRune("earth"); public static final SourceRune SEA = new SourceRune("sea"); public static final SourceRune SKY = new SourceRune("sky"); public static final SourceRune SUN = new SourceRune("sun"); public static final SourceRune MOON = new SourceRune("moon"); public static final SourceRune BLOOD = new SourceRune("blood"); public static final SourceRune INFERNAL = new SourceRune("infernal"); public static final SourceRune VOID = new SourceRune("void"); public static final SourceRune HALLOWED = new SourceRune("hallowed"); public static final VerbRune ABSORB = new VerbRune("absorb"); public static final VerbRune DISPEL = new VerbRune("dispel"); public static final VerbRune PROJECT = new VerbRune("project"); public static final VerbRune PROTECT = new VerbRune("protect"); public static final VerbRune SUMMON = new VerbRune("summon"); public static final NounRune AREA = new NounRune("area"); public static final NounRune CREATURE = new NounRune("creature"); public static final NounRune ITEM = new NounRune("item"); public static final NounRune SELF = new NounRune("self"); public static final PowerRune POWER = new PowerRune("power"); protected final ResourceLocation id; protected final Rarity rarity; protected final boolean glint; public Rune(@Nonnull String tag, @Nonnull Rarity rarity, boolean glint) { this(new ResourceLocation(PrimalMagick.MODID, tag), rarity, glint); } public Rune(@Nonnull ResourceLocation id, @Nonnull Rarity rarity, boolean glint) { if (REGISTRY.containsKey(id)) { // Don't allow a given rune to be registered more than once throw new IllegalArgumentException("Rune " + id.toString() + " already registered!"); } this.id = id; this.rarity = rarity; this.glint = glint; REGISTRY.put(id, this); } @Nonnull public ResourceLocation getId() { return this.id; } @Nonnull public Rarity getRarity() { return this.rarity; } public boolean hasGlint() { return this.glint; } @Nonnull public String getTooltipTranslationKey() { return "tooltip." + this.id.getNamespace() + ".rune." + this.id.getPath(); } @Nonnull public abstract RuneType getType(); @Nonnull public static Collection<Rune> getAllRunes() { return Collections.unmodifiableCollection(REGISTRY.values()); } @Nullable public static Rune getRune(@Nonnull ResourceLocation tag) { return REGISTRY.get(tag); } }
package org.ovirt.engine.core.common.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.ovirt.engine.core.common.businessentities.ArchitectureType; import org.ovirt.engine.core.common.businessentities.BiosType; public class VmCpuCountHelperTest { @Test public void testCommon() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(null, Integer.valueOf(16), Integer.valueOf(288), 2, 12, null); assertEquals(Integer.valueOf(192), maxVCpu); } @Test public void testPowerOf2() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(null, Integer.valueOf(16), Integer.valueOf(288), 2, 4, null); assertEquals(Integer.valueOf(128), maxVCpu); } @Test public void test256() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(null, Integer.valueOf(16), Integer.valueOf(288), 2, 8, null); assertEquals(Integer.valueOf(240), maxVCpu); } @Test public void testLimit() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(null, Integer.valueOf(16), Integer.valueOf(100), 2, 8, null); assertEquals(Integer.valueOf(96), maxVCpu); } @Test public void testCommonX86() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.x86, Integer.valueOf(16), Integer.valueOf(288), 2, 12, null); assertEquals(Integer.valueOf(192), maxVCpu); } @Test public void testPowerOf2X86() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.x86, Integer.valueOf(16), Integer.valueOf(288), 2, 4, null); assertEquals(Integer.valueOf(128), maxVCpu); } @Test public void test256X86() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.x86, Integer.valueOf(16), Integer.valueOf(288), 2, 8, null); assertEquals(Integer.valueOf(240), maxVCpu); } @Test public void testAtLimitX86() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.x86, Integer.valueOf(16), Integer.valueOf(240), 2, 8, null); assertEquals(Integer.valueOf(240), maxVCpu); } @Test public void testLimitX86() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.x86, Integer.valueOf(16), Integer.valueOf(240), 2, 16, null); assertEquals(Integer.valueOf(224), maxVCpu); } @Test public void testTooManyX86APIC() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.x86, Integer.valueOf(32), Integer.valueOf(710), 2, 16, null); assertEquals(Integer.valueOf(224), maxVCpu); } @Test public void testTooManyX86Q35() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.x86, Integer.valueOf(32), Integer.valueOf(710), 2, 16, BiosType.Q35_OVMF); assertEquals(Integer.valueOf(704), maxVCpu); } @Test public void testCommonPpc() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.ppc, Integer.valueOf(16), Integer.valueOf(288), 2, 12, null); assertEquals(Integer.valueOf(288), maxVCpu); } @Test public void testPowerOf2Ppc() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.ppc, Integer.valueOf(16), Integer.valueOf(288), 2, 4, null); assertEquals(Integer.valueOf(128), maxVCpu); } @Test public void test256Ppc() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.ppc, Integer.valueOf(16), Integer.valueOf(288), 2, 8, null); assertEquals(Integer.valueOf(256), maxVCpu); } @Test public void testLimitPpc() { Integer maxVCpu = VmCpuCountHelper.calcMaxVCpu(ArchitectureType.x86, Integer.valueOf(16), Integer.valueOf(240), 2, 16, null); assertEquals(Integer.valueOf(224), maxVCpu); } }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.cms.v20190321.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class VideoModerationRequest extends AbstractModel{ /** * 回调URL,音频识别结果将以POST请求方式发送到此地址 */ @SerializedName("CallbackUrl") @Expose private String CallbackUrl; /** * 视频文件MD5 */ @SerializedName("FileMD5") @Expose private String FileMD5; /** * 视频内容base64 */ @SerializedName("FileContent") @Expose private String FileContent; /** * 视频内容Url,其中FileUrl与FileContent二选一 */ @SerializedName("FileUrl") @Expose private String FileUrl; /** * Get 回调URL,音频识别结果将以POST请求方式发送到此地址 * @return CallbackUrl 回调URL,音频识别结果将以POST请求方式发送到此地址 */ public String getCallbackUrl() { return this.CallbackUrl; } /** * Set 回调URL,音频识别结果将以POST请求方式发送到此地址 * @param CallbackUrl 回调URL,音频识别结果将以POST请求方式发送到此地址 */ public void setCallbackUrl(String CallbackUrl) { this.CallbackUrl = CallbackUrl; } /** * Get 视频文件MD5 * @return FileMD5 视频文件MD5 */ public String getFileMD5() { return this.FileMD5; } /** * Set 视频文件MD5 * @param FileMD5 视频文件MD5 */ public void setFileMD5(String FileMD5) { this.FileMD5 = FileMD5; } /** * Get 视频内容base64 * @return FileContent 视频内容base64 */ public String getFileContent() { return this.FileContent; } /** * Set 视频内容base64 * @param FileContent 视频内容base64 */ public void setFileContent(String FileContent) { this.FileContent = FileContent; } /** * Get 视频内容Url,其中FileUrl与FileContent二选一 * @return FileUrl 视频内容Url,其中FileUrl与FileContent二选一 */ public String getFileUrl() { return this.FileUrl; } /** * Set 视频内容Url,其中FileUrl与FileContent二选一 * @param FileUrl 视频内容Url,其中FileUrl与FileContent二选一 */ public void setFileUrl(String FileUrl) { this.FileUrl = FileUrl; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "CallbackUrl", this.CallbackUrl); this.setParamSimple(map, prefix + "FileMD5", this.FileMD5); this.setParamSimple(map, prefix + "FileContent", this.FileContent); this.setParamSimple(map, prefix + "FileUrl", this.FileUrl); } }
/** * Copyright (C) 2002-2014 Fabrizio Giustina, the Displaytag team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.displaytag.export.excel; import com.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.HttpUnitOptions; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse; import com.meterware.servletunit.ServletRunner; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLDecoder; import java.util.Hashtable; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.displaytag.export.ExportViewFactory; import org.displaytag.properties.MediaTypeEnum; import org.displaytag.properties.TableProperties; import org.displaytag.tags.TableTagParameters; import org.displaytag.util.ParamEncoder; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Class ExportExcelTest. * * @author andy Date: Oct 30, 2010 Time: 12:04:04 PM */ public class ExportExcelHssfTest { /** * logger. */ protected final Logger log = LoggerFactory.getLogger(getClass()); /** * HttpUnit ServletRunner. */ protected ServletRunner runner; /** * Context mapped to the test application. */ public static final String CONTEXT = "/context"; /** * Gets the jsp url. * * @param jsp the jsp * @return the jsp url */ protected String getJspUrl(String jsp) { return "http://localhost" + CONTEXT + "/jsps/" + jsp; } /** * Sets the up. * * @throws Exception e * @see junit.framework.TestCase#setUp() */ @Before public void setUp() throws Exception { // need to pass a web.xml file to setup servletunit working directory ClassLoader classLoader = getClass().getClassLoader(); URL webXmlUrl = classLoader.getResource("WEB-INF/web.xml"); String path = URLDecoder.decode(webXmlUrl.getFile(), "UTF-8"); HttpUnitOptions.setDefaultCharacterSet("utf-8"); System.setProperty("file.encoding", "utf-8"); // start servletRunner this.runner = new ServletRunner(new File(path), CONTEXT); Hashtable<String, String> params = new Hashtable<>(); params.put("javaEncoding", "utf-8"); this.runner.registerServlet("*.jsp", "org.apache.jasper.servlet.JspServlet", params); this.log.debug("ServletRunner setup OK"); } /** * Tear down. * * @throws Exception e * @see junit.framework.TestCase#tearDown() */ @After public void tearDown() throws Exception { // shutdown servlet engine TableProperties.clearProperties(); this.runner.shutDown(); } /** * Test for content disposition and filename. jspName jsp name, with full path * @throws Exception any axception thrown during test. */ @Test public void doDefaultTest() throws Exception { byte[] res = runPage("exportExcel.jsp"); File f = File.createTempFile("exporttest", ".xls"); FileOutputStream fw = new FileOutputStream(f); fw.write(res); fw.flush(); fw.close(); FileInputStream istr = new FileInputStream(f); Workbook wb = new HSSFWorkbook(istr); Sheet sh = wb.getSheetAt(0); Assert.assertNotNull("Not all rows have been exported", sh.getRow(4)); Assert.assertEquals("bee", sh.getRow(4).getCell(0).getStringCellValue()); istr.close(); wb.close(); } /** * Run page. * * @param jspPage the jsp page * @return the byte[] * @throws Exception the exception */ public byte[] runPage(String jspPage) throws Exception { ParamEncoder encoder = new ParamEncoder("table"); String mediaParameter = encoder.encodeParameterName(TableTagParameters.PARAMETER_EXPORTTYPE); WebRequest request = new GetMethodWebRequest(getJspUrl(jspPage)); // this will force media type initialization ExportViewFactory evf= ExportViewFactory.getInstance(); evf.registerExportView("excel", "org.displaytag.export.excel.ExcelHssfView"); MediaTypeEnum excelMedia = MediaTypeEnum.EXCEL; Assert.assertNotNull("Excel export view not correctly registered.", excelMedia); request.setParameter(mediaParameter, Integer.toString(excelMedia.getCode())); WebResponse response = this.runner.getResponse(request); // we are really testing an xml output? Assert .assertEquals("Expected a different content type.", "application/vnd.ms-excel", response.getContentType()); InputStream stream = response.getInputStream(); byte[] result = new byte[9000]; stream.read(result); return result; } }
/*- * ========================LICENSE_START================================= * Bucket4j * %% * Copyright (C) 2015 - 2020 Vladimir Bukhtoyarov * %% * 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. * =========================LICENSE_END================================== */ package io.github.bucket4j; import io.github.bucket4j.grid.*; import io.github.bucket4j.local.LocalBucketBuilder; import io.github.bucket4j.serialization.SerializationHandle; import java.util.*; import static java.util.Collections.unmodifiableList; /** * This is entry point for functionality provided bucket4j library. */ public class Bucket4j { private static final Map<Class<?>, Extension<?>> extensions; static { extensions = new HashMap<>(); for (Extension<?> extension : ServiceLoader.load(Extension.class)) { extensions.put(extension.getClass(), extension); } } private static final List<SerializationHandle<?>> serializationHandles; static { Map<Integer, SerializationHandle<?>> serializersById = new HashMap<>(); List<SerializationHandle<?>> coreHandles = Arrays.asList( Bandwidth.SERIALIZATION_HANDLE, BucketConfiguration.SERIALIZATION_HANDLE, BucketState.SERIALIZATION_HANDLE, GridBucketState.SERIALIZATION_HANDLE, ReserveAndCalculateTimeToSleepCommand.SERIALIZATION_HANDLE, AddTokensCommand.SERIALIZATION_HANDLE, ConsumeAsMuchAsPossibleCommand.SERIALIZATION_HANDLE, CreateSnapshotCommand.SERIALIZATION_HANDLE, GetAvailableTokensCommand.SERIALIZATION_HANDLE, EstimateAbilityToConsumeCommand.SERIALIZATION_HANDLE, TryConsumeCommand.SERIALIZATION_HANDLE, TryConsumeAndReturnRemainingTokensCommand.SERIALIZATION_HANDLE, ReplaceConfigurationOrReturnPreviousCommand.SERIALIZATION_HANDLE, ConsumeIgnoringRateLimitsCommand.SERIALIZATION_HANDLE, CommandResult.SERIALIZATION_HANDLE, ConsumptionProbe.SERIALIZATION_HANDLE, EstimationProbe.SERIALIZATION_HANDLE, VerboseResult.SERIALIZATION_HANDLE, VerboseCommand.SERIALIZATION_HANDLE ); List<SerializationHandle<?>> allHandles = new ArrayList<>(coreHandles); for (Extension<?> extension : extensions.values()) { allHandles.addAll(extension.getSerializers()); } for (SerializationHandle<?> coreHandle : allHandles) { int typeId = coreHandle.getTypeId(); SerializationHandle<?> conflictingHandle = serializersById.get(typeId); if (conflictingHandle != null) { String msg = "Serialization ID " + typeId + " duplicated for " + coreHandle + " and " + conflictingHandle; throw new IllegalArgumentException(msg); } serializersById.put(typeId, coreHandle); } serializationHandles = Collections.unmodifiableList(allHandles); } public static List<SerializationHandle<?>> getSerializationHandles() { return serializationHandles; } private Bucket4j() { // to avoid initialization of utility class } /** * Creates the new builder of in-memory buckets. * * @return new instance of {@link LocalBucketBuilder} */ public static LocalBucketBuilder builder() { return new LocalBucketBuilder(); } /** * Creates new instance of {@link ConfigurationBuilder} * * @return instance of {@link ConfigurationBuilder} */ public static ConfigurationBuilder configurationBuilder() { return new ConfigurationBuilder(); } /** * Locates Bucket4j extension by class {@code extensionClass}. * * @param extensionClass must be registered in "/META-INF/services/io.github.bucket4j.Extension" according to java SPI rules. * @param <T> * @param <E> * * @return library extension */ public static <T extends AbstractBucketBuilder<T>, E extends Extension<T>> E extension(Class<E> extensionClass) { E extension = (E) extensions.get(extensionClass); if (extension == null) { String msg = "extension with class [" + extensionClass + "] is not registered"; throw new IllegalArgumentException(msg); } return extension; } }
/* * Copyright 2015 Open Networking Laboratory * * 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.onosproject.cluster; import java.util.Arrays; import org.junit.Test; import com.google.common.testing.EqualsTester; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /** * Unit tests for the leadership event test. */ public class LeadershipEventTest { private final NodeId node1 = new NodeId("1"); private final NodeId node2 = new NodeId("2"); private final Leadership lead1 = new Leadership("topic1", new Leader(node1, 1L, 2L), Arrays.asList(node1)); private final Leadership lead2 = new Leadership("topic1", new Leader(node1, 1L, 2L), Arrays.asList(node1, node2)); private final Leadership lead3 = new Leadership("topic1", new Leader(node2, 1L, 2L), Arrays.asList(node2)); private final LeadershipEvent event1 = new LeadershipEvent(LeadershipEvent.Type.LEADER_CHANGED, lead1); private final long time = System.currentTimeMillis(); private final LeadershipEvent event2 = new LeadershipEvent(LeadershipEvent.Type.CANDIDATES_CHANGED, lead2, time); private final LeadershipEvent sameAsEvent2 = new LeadershipEvent(LeadershipEvent.Type.CANDIDATES_CHANGED, lead2, time); private final LeadershipEvent event3 = new LeadershipEvent(LeadershipEvent.Type.LEADER_CHANGED, lead2); private final LeadershipEvent event4 = new LeadershipEvent(LeadershipEvent.Type.LEADER_AND_CANDIDATES_CHANGED, lead3); /** * Tests for proper operation of equals(), hashCode() and toString() methods. */ @Test public void checkEquals() { new EqualsTester() .addEqualityGroup(event1) .addEqualityGroup(event2, sameAsEvent2) .addEqualityGroup(event3) .addEqualityGroup(event4) .testEquals(); } /** * Tests that objects are created properly. */ @Test public void checkConstruction() { assertThat(event1.type(), is(LeadershipEvent.Type.LEADER_CHANGED)); assertThat(event1.subject(), is(lead1)); assertThat(event2.time(), is(time)); assertThat(event2.type(), is(LeadershipEvent.Type.CANDIDATES_CHANGED)); assertThat(event2.subject(), is(lead2)); } }
/* * 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. * * $Id: Comments.java,v 1.1.1.1 2008/09/29 22:33:08 sp208304 Exp $ */ package org.apache.olio.workload.loader; import com.sun.faban.driver.util.Random; import org.apache.olio.workload.util.ScaleFactors; import org.apache.olio.workload.util.UserName; import org.apache.olio.workload.loader.framework.Loadable; import org.apache.olio.workload.loader.framework.ThreadConnection; import org.apache.olio.workload.loader.framework.ThreadResource; import java.sql.Date; import java.util.logging.Logger; import java.util.logging.Level; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Comments Loader. */ public class Comments extends Loadable { // We use on average of 10 comments per event. Random 0..20 comments.. public static final Date BASE_DATE = new Date(System.currentTimeMillis()); private static final String STATEMENT = "insert into COMMENTS_RATING " + "(username, socialeventid, comments, ratings, created_at) values (?, ?, ?, ?, ?)"; static Logger logger = Logger.getLogger(Comments.class.getName()); int eventId; String[] userNames; String[] comments; int[] ratings; Date created_at; public String getClearStatement() { return "truncate table COMMENTS_RATING"; } public void prepare() { eventId = getSequence(); ++eventId; ThreadResource tr = ThreadResource.getInstance(); Random r = tr.getRandom(); int commentCount = r.random(0, 20); userNames = new String[commentCount]; comments = new String[commentCount]; ratings = new int[commentCount]; for (int i = 0; i < userNames.length; i++) { int userId = r.random(1, ScaleFactors.users); userNames[i] = UserName.getUserName(userId); comments[i] = r.makeCString(10, 1000); ratings[i] = r.random(2, 5); } created_at = r.makeDateInInterval( BASE_DATE, -540, 0); } public void load() { ThreadConnection c = ThreadConnection.getInstance(); try { for (int i = 0; i < userNames.length; i++) { PreparedStatement s = c.prepareStatement(STATEMENT); s.setString(1, userNames[i]); s.setInt(2, eventId); s.setString(3, comments[i]); s.setInt(4, ratings[i]); s.setDate(5, created_at); c.addBatch(); } } catch (SQLException e) { logger.log(Level.SEVERE, e.getMessage(), e); } } }
package br.com.zup.mercadolivre.repository; import br.com.zup.mercadolivre.modelo.Compra; import org.springframework.data.jpa.repository.JpaRepository; public interface CompraRepository extends JpaRepository<Compra, Long> { }
package org.inaetics.dronessimulator.visualisation.uiupdates; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; /** * RemoveBaseEntity extends UIUpdate and is a class representation used when removing a BaseEntity (drone, bullet, etc) */ public class RemoveBaseEntity extends UIUpdate { /** * The image of the base entity to remove */ private final ImageView imageView; /** * Instantiates an update to remove a base entity * @param imageView */ public RemoveBaseEntity(ImageView imageView) { this.imageView = imageView; } /** * Remove the base entity image from a pane */ @Override public void execute(Pane pane) { pane.getChildren().remove(this.imageView); } }
package jp.co.exacorp.matchingapp.logic.api; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import javax.ejb.Stateless; import jp.co.exacorp.matchingapp.util.LINEConstants; @Stateless public class ContentContact { /* この2行はConstantsクラスに記述する */ public static final String CONTENT_URL_HEAD = "https://api.line.me/v2/bot/message/"; public static final String CONTENT_URL_FOOT = "/content"; public byte[] getImage(String id) { // get inputstream HttpURLConnection con = null; InputStream in = null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { URL url = new URL(CONTENT_URL_HEAD + id + CONTENT_URL_FOOT); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Authorization", "Bearer " + LINEConstants.LINE_CHANNEL_ACCESS_TOKEN); con.connect(); if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { in = con.getInputStream(); } byte[] buffer = new byte[1024]; while (true) { int len = in.read(buffer); if (len < 0) { break; } bout.write(buffer, 0, len); } System.out.println("これでたぶん画像の取得はできてるんじゃないかな・・・・"); // String result = new String(bout.toByteArray(), "UTF-8"); // System.out.println("byte配列からStringに変換した結果の最初の50文字 : " // + result.substring(0, 50)); } catch (Exception e) { System.out.println("content接続時エラー"); // e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { // e.printStackTrace(); System.out.println("close時エラー"); } } return bout.toByteArray(); } }
package com.ray3k.template.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.TemporalAction; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.dongbat.jbump.World; import com.ray3k.template.*; import com.ray3k.template.OgmoReader.*; import com.ray3k.template.entities.*; import com.ray3k.template.entities.PlayerEntity.*; import com.ray3k.template.screens.DialogPause.*; import com.ray3k.template.transitions.*; import com.ray3k.template.vfx.*; import space.earlygrey.shapedrawer.ShapeDrawer; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*; import static com.ray3k.template.Core.Binding.*; import static com.ray3k.template.Core.*; import static com.ray3k.template.Resources.*; public class GameScreen extends JamScreen { public static GameScreen gameScreen; public static final Color BG_COLOR = new Color(Color.BLACK); public Stage stage; public static ShapeDrawer shapeDrawer; public boolean paused; private GlitchEffect vfxEffect; public Array<Entity> addEntities; public int currentId; public int levelId; public Array<PlayerEntity> playerEntities = new Array<>(); public boolean endGame = true; public static final int LAST_LEVEL = 9; public GameScreen() { this(null, 1, 0); } public GameScreen(Array<Entity> addEntities, int levelId, int currentId) { this.addEntities = addEntities == null ? new Array<>() : new Array<>(addEntities); this.levelId = levelId; this.currentId = currentId; } @Override public void show() { bgm_engine.setLooping(true); bgm_engine.setVolume(sfx); if (!bgm_engine.isPlaying()) bgm_engine.play(); world = new World<>(); gameScreen = this; paused = false; stage = new Stage(new ScreenViewport(), batch); stage.addListener(new InputListener() { @Override public boolean keyDown(InputEvent event, int keycode) { if (!paused && keycode == Keys.ESCAPE) { paused = true; DialogPause dialogPause = new DialogPause(GameScreen.this); dialogPause.show(stage); dialogPause.addListener(new PauseListener() { @Override public void resume() { paused = false; } @Override public void quit() { core.transition(new MenuScreen()); } }); } return super.keyDown(event, keycode); } }); shapeDrawer = new ShapeDrawer(batch, skin.getRegion("game/white")); shapeDrawer.setPixelSize(.5f); InputMultiplexer inputMultiplexer = new InputMultiplexer(stage, this); Gdx.input.setInputProcessor(inputMultiplexer); camera = new OrthographicCamera(); viewport = new FitViewport(1024, 576, camera); entityController.clear(); for (var entity : addEntities) { entity.item = null; entity.destroy = false; entityController.add(entity); if (entity instanceof PlayerEntity) { playerEntities.add((PlayerEntity) entity); } } vfxEffect = new GlitchEffect(); vfxEffect.setAmount(0); vfxEffect.rebind(); vfxManager.addEffect(vfxEffect); stage.addAction(sequence(delay(.05f), new TemporalAction(.25f) { @Override protected void update(float percent) { vfxEffect.setAmount(percent * .2f); vfxEffect.rebind(); } }, run(() -> sfx_glitch.play(sfx)), new TemporalAction(.25f) { @Override protected void update(float percent) { vfxEffect.setAmount((1 - percent) * .2f); vfxEffect.rebind(); } }, run(() -> vfxManager.removeEffect(vfxEffect)))); var ogmoReader = new OgmoReader(); ogmoReader.addListener(new OgmoAdapter() { @Override public void entity(String name, int id, int x, int y, int width, int height, boolean flippedX, boolean flippedY, int originX, int originY, int rotation, Array<EntityNode> nodes, ObjectMap<String, OgmoValue> valuesMap) { switch (name) { case "wall": float minX = x; float minY = y; float maxX = x; float maxY = y; for (var node : nodes) { if (node.x < minX) minX = node.x; if (node.x > maxX) maxX = node.x; if (node.y < minY) minY = node.y; if (node.y > maxY) maxY = node.y; } var wall = new WallEntity(minX, minY, maxX - minX, maxY - minY); entityController.add(wall); break; case "exit": minX = x; minY = y; maxX = x; maxY = y; for (var node : nodes) { if (node.x < minX) minX = node.x; if (node.x > maxX) maxX = node.x; if (node.y < minY) minY = node.y; if (node.y > maxY) maxY = node.y; } var exit = new ExitEntity(minX, minY, maxX - minX, maxY - minY, valuesMap.get("id").asInt()); entityController.add(exit); break; default: if (valuesMap.get("id").asInt() == currentId) { var player = new PlayerEntity(x, y, rotation, name, currentId); player.inputter = new PlayerInput(); player.inputRecorder = new InputRecorder(); entityController.add(player); playerEntities.add(player); endGame = false; var cameraEntity = new CameraEntity(player, levelWidth, levelHeight); entityController.add(cameraEntity); } break; } } private float levelWidth; private float levelHeight; @Override public void level(String ogmoVersion, int width, int height, int offsetX, int offsetY, ObjectMap<String, OgmoValue> valuesMap) { levelWidth = width; levelHeight = height; camera.position.set(width / 2f, height / 2f, 0); float widthRatio = (float) width / viewport.getWorldWidth(); float heightRatio = (float) height / viewport.getWorldHeight(); camera.zoom = Math.max(widthRatio, heightRatio); } private String layerName; @Override public void layer(String name, int gridCellWidth, int gridCellHeight, int offsetX, int offsetY) { layerName = name; } @Override public void decal(int centerX, int centerY, float scaleX, float scaleY, int rotation, String texture, String folder) { if (layerName.equals("background")) { var decal = new BackgroundEntity(texture, centerX, centerY); entityController.add(decal); decal.depth = BACKGROUND_DEPTH; } else if (layerName.equals("foreground")) { var decal = new BackgroundEntity(texture, centerX, centerY); entityController.add(decal); decal.depth = FOREGROUND_DEPTH; } } }); ogmoReader.readFile(Gdx.files.internal("levels/level-" + levelId + ".json")); } @Override public void act(float delta) { if (!paused) { entityController.act(delta); vfxManager.update(delta); } stage.act(delta); if (endGame) { boolean nextLevel = true; for (var player : playerEntities) { if (!player.destroy) { nextLevel = false; break; } } if (nextLevel) { if (levelId < LAST_LEVEL) core.transition(new GameScreen(null, levelId + 1, 0), new TransitionSlide(270, Interpolation.bounce), .5f); else core.transition(new CompleteScreen(), new TransitionSlide(270, Interpolation.bounce), .5f); } } else { if (isBindingJustPressed(RESET)) { core.transition(new GameScreen(null, levelId, 0), new TransitionSlide(270, Interpolation.bounce), .5f); } } } @Override public void draw(float delta) { batch.setBlendFunction(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA); vfxManager.cleanUpBuffers(); vfxManager.beginInputCapture(); Gdx.gl.glClearColor(BG_COLOR.r, BG_COLOR.g, BG_COLOR.b, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); viewport.apply(); batch.setProjectionMatrix(camera.combined); entityController.draw(paused ? 0 : delta); batch.end(); vfxManager.endInputCapture(); vfxManager.applyEffects(); vfxManager.renderToScreen(); batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); stage.draw(); } @Override public void resize(int width, int height) { if (width + height != 0) { vfxManager.resize(width, height); viewport.update(width, height); stage.getViewport().update(width, height, true); } } @Override public void dispose() { } @Override public void hide() { super.hide(); vfxManager.removeAllEffects(); vfxEffect.dispose(); entityController.dispose(); } }
// Copyright 2020 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 com.google.devtools.build.lib.actions; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import java.time.Duration; import java.util.EnumMap; import java.util.Map; import java.util.function.Function; import java.util.function.ToLongFunction; import javax.annotation.Nullable; /** Metrics aggregated per execution kind. */ public final class AggregatedSpawnMetrics { public static final AggregatedSpawnMetrics EMPTY = new AggregatedSpawnMetrics(ImmutableMap.of()); /** Static holder for lazy initialization. */ private static class EmptyMetrics { /** * Map with empty {@link SpawnMetrics}. * * <p>This is useful for {@link #getMetrics(SpawnMetrics.ExecKind)} where we need to return an * empty {@link SpawnMetrics} with the correct {@link SpawnMetrics.ExecKind}. */ private static final ImmutableMap<SpawnMetrics.ExecKind, SpawnMetrics> INSTANCE = createEmptyMetrics(); private static final ImmutableMap<SpawnMetrics.ExecKind, SpawnMetrics> createEmptyMetrics() { EnumMap<SpawnMetrics.ExecKind, SpawnMetrics> map = new EnumMap<>(SpawnMetrics.ExecKind.class); for (SpawnMetrics.ExecKind kind : SpawnMetrics.ExecKind.values()) { map.put(kind, new SpawnMetrics.Builder().setExecKind(kind).build()); } return Maps.immutableEnumMap(map); } } private final ImmutableMap<SpawnMetrics.ExecKind, SpawnMetrics> metricsMap; private AggregatedSpawnMetrics(ImmutableMap<SpawnMetrics.ExecKind, SpawnMetrics> metricsMap) { this.metricsMap = metricsMap; } /** * Returns all present {@link SpawnMetrics}. * * <p>There will be at most one {@link SpawnMetrics} object per {@link SpawnMetrics.ExecKind}. */ public ImmutableCollection<SpawnMetrics> getAllMetrics() { return metricsMap.values(); } /** * Returns {@link SpawnMetrics} for the provided execution kind. * * <p>This will never return {@code null}, but the {@link SpawnMetrics} can be empty. */ public SpawnMetrics getMetrics(SpawnMetrics.ExecKind kind) { @Nullable SpawnMetrics metrics = metricsMap.get(kind); if (metrics == null) { return EmptyMetrics.INSTANCE.get(kind); } return metrics; } /** * Returns {@link SpawnMetrics} for the remote execution. * * @see #getMetrics(SpawnMetrics.ExecKind) */ public SpawnMetrics getRemoteMetrics() { return getMetrics(SpawnMetrics.ExecKind.REMOTE); } /** * Returns a new {@link AggregatedSpawnMetrics} that incorporates the provided metrics by summing * them with the existing ones (if any). */ public AggregatedSpawnMetrics sumAllMetrics(SpawnMetrics other) { SpawnMetrics existing = getMetrics(other.execKind()); SpawnMetrics.Builder builder = new SpawnMetrics.Builder() .setExecKind(other.execKind()) .addDurations(existing) .addDurations(other) .addNonDurations(existing) .addNonDurations(other); EnumMap<SpawnMetrics.ExecKind, SpawnMetrics> map = new EnumMap<>(SpawnMetrics.ExecKind.class); map.putAll(metricsMap); map.put(other.execKind(), builder.build()); return new AggregatedSpawnMetrics(Maps.immutableEnumMap(map)); } /** * Returns a new {@link AggregatedSpawnMetrics} that incorporates the provided metrics by summing * the duration ones and taking the maximum for the non-duration ones. */ public AggregatedSpawnMetrics sumDurationsMaxOther(SpawnMetrics other) { SpawnMetrics existing = getMetrics(other.execKind()); SpawnMetrics.Builder builder = new SpawnMetrics.Builder() .setExecKind(other.execKind()) .addDurations(existing) .addDurations(other) .maxNonDurations(existing) .maxNonDurations(other); EnumMap<SpawnMetrics.ExecKind, SpawnMetrics> map = new EnumMap<>(SpawnMetrics.ExecKind.class); map.putAll(metricsMap); map.put(other.execKind(), builder.build()); return new AggregatedSpawnMetrics(Maps.immutableEnumMap(map)); } /** * Returns the total duration across all execution kinds. * * <p>Example: {@code getTotalDuration(SpawnMetrics::queueTime)} will give the total queue time * across all execution kinds. */ public Duration getTotalDuration(Function<SpawnMetrics, Duration> extract) { Duration result = Duration.ZERO; for (SpawnMetrics metric : metricsMap.values()) { result = result.plus(extract.apply(metric)); } return result; } /** * Returns the maximum value of a non-duration metric across all execution kinds. * * <p>Example: {@code getMaxNonDuration(0, SpawnMetrics::inputFiles)} returns the maximum number * of input files across all the execution kinds. */ public long getMaxNonDuration(long initialValue, ToLongFunction<SpawnMetrics> extract) { long result = initialValue; for (SpawnMetrics metric : metricsMap.values()) { result = Long.max(result, extract.applyAsLong(metric)); } return result; } public String toString(Duration total, boolean summary) { // For now keep compatibility with the old output and only report the remote execution. // TODO(michalt): Change this once the local and worker executions populate more metrics. return SpawnMetrics.ExecKind.REMOTE + " " + getRemoteMetrics().toString(total, summary); } /** Builder for {@link AggregatedSpawnMetrics}. */ public static class Builder { private final EnumMap<SpawnMetrics.ExecKind, SpawnMetrics.Builder> builderMap = new EnumMap<>(SpawnMetrics.ExecKind.class); public AggregatedSpawnMetrics build() { EnumMap<SpawnMetrics.ExecKind, SpawnMetrics> map = new EnumMap<>(SpawnMetrics.ExecKind.class); for (Map.Entry<SpawnMetrics.ExecKind, SpawnMetrics.Builder> entry : builderMap.entrySet()) { map.put(entry.getKey(), entry.getValue().build()); } return new AggregatedSpawnMetrics(Maps.immutableEnumMap(map)); } public Builder addDurations(SpawnMetrics metrics) { getBuilder(metrics.execKind()).addDurations(metrics); return this; } public Builder addDurations(AggregatedSpawnMetrics aggregated) { aggregated.getAllMetrics().forEach(this::addDurations); return this; } public Builder addNonDurations(SpawnMetrics metrics) { getBuilder(metrics.execKind()).addNonDurations(metrics); return this; } public Builder addNonDurations(AggregatedSpawnMetrics aggregated) { aggregated.getAllMetrics().forEach(this::addNonDurations); return this; } public Builder maxNonDurations(SpawnMetrics metrics) { getBuilder(metrics.execKind()).maxNonDurations(metrics); return this; } public Builder maxNonDurations(AggregatedSpawnMetrics aggregated) { aggregated.getAllMetrics().forEach(this::maxNonDurations); return this; } private SpawnMetrics.Builder getBuilder(SpawnMetrics.ExecKind kind) { return builderMap.computeIfAbsent( kind, (SpawnMetrics.ExecKind k) -> new SpawnMetrics.Builder().setExecKind(k)); } } }
package mage.cards.f; import java.util.UUID; import mage.MageInt; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.dynamicvalue.common.StaticValue; import mage.abilities.effects.common.LookLibraryAndPickControllerEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.FilterCard; /** * * @author LevelX */ public final class FaerieMechanist extends CardImpl { private static final FilterCard filter = new FilterCard("an artifact card"); static { filter.add(CardType.ARTIFACT.getPredicate()); } public FaerieMechanist(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT,CardType.CREATURE},"{3}{U}"); this.subtype.add(SubType.FAERIE); this.subtype.add(SubType.ARTIFICER); this.power = new MageInt(2); this.toughness = new MageInt(2); // Flying this.addAbility(FlyingAbility.getInstance()); // When Faerie Mechanist enters the battlefield, look at the top three cards of your library. // You may reveal an artifact card from among them and put it into your hand. Put the rest on the bottom of your library in any order. this.addAbility(new EntersBattlefieldTriggeredAbility(new LookLibraryAndPickControllerEffect(StaticValue.get(3), false, StaticValue.get(1), filter, false))); } private FaerieMechanist(final FaerieMechanist card) { super(card); } @Override public FaerieMechanist copy() { return new FaerieMechanist(this); } }
/* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. * </p> */ package io.shardingsphere.core.parsing.integrate.jaxb.token; import lombok.Getter; import lombok.Setter; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; @Getter @Setter @XmlAccessorType(XmlAccessType.FIELD) public final class ExpectedInsertColumnToken { @XmlAttribute(name = "begin-position") private int beginPosition; @XmlAttribute(name = "column-name") private String columnName; }
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: koubei.advert.delivery.item.apply response. * * @author auto create * @since 1.0, 2019-01-07 20:51:15 */ public class KoubeiAdvertDeliveryItemApplyResponse extends AlipayResponse { private static final long serialVersionUID = 2789378245416131572L; /** * 权益详细信息: partnerId:商户ID(用于打开手机钱包券详情) */ @ApiField("benefit_detail") private String benefitDetail; /** * 广告id对应的权益id */ @ApiField("benefit_id") private String benefitId; public void setBenefitDetail(String benefitDetail) { this.benefitDetail = benefitDetail; } public String getBenefitDetail( ) { return this.benefitDetail; } public void setBenefitId(String benefitId) { this.benefitId = benefitId; } public String getBenefitId( ) { return this.benefitId; } }
package com.alibaba.alink.params.io; import org.apache.flink.ml.api.misc.param.ParamInfo; import org.apache.flink.ml.api.misc.param.ParamInfoFactory; import org.apache.flink.ml.api.misc.param.WithParams; import com.alibaba.alink.common.annotation.DescCn; import com.alibaba.alink.common.annotation.NameCn; public interface RandomVectorSourceStreamParams<T> extends WithParams <T> { /** * Param "idColName" */ @NameCn("id 列名") @DescCn("列名,若列名非空,表示输出表中包含一个整形序列id列,否则无该列") ParamInfo <String> ID_COL = ParamInfoFactory .createParamInfo("idCol", String.class) .setDescription("id col name") .setHasDefaultValue("alink_id") .setAlias(new String[] {"idColName"}) .build(); /** * Param "outputColName" */ @NameCn("输出列名") @DescCn("输出随机生成的数据存储列名") ParamInfo <String> OUTPUT_COL = ParamInfoFactory .createParamInfo("outputCol", String.class) .setDescription("output col name") .setHasDefaultValue("tensor") .setAlias(new String[] {"outputColName"}) .build(); /** * Param "size" */ @NameCn("张量size") @DescCn("整型数组,张量的size") ParamInfo <Integer[]> SIZE = ParamInfoFactory .createParamInfo("size", Integer[].class) .setDescription("size") .setRequired() .build(); /** * Param "maxRows" */ @NameCn("最大行数") @DescCn("输出数据流的行数目的最大值") ParamInfo <Long> MAX_ROWS = ParamInfoFactory .createParamInfo("maxRows", Long.class) .setDescription("max rows") .setRequired() .build(); /** * Param "sparsity" */ @NameCn("稀疏度") @DescCn("非零元素在所有张量数据中的占比") ParamInfo <Double> SPARSITY = ParamInfoFactory .createParamInfo("sparsity", Double.class) .setDescription("sparsity") .setRequired() .build(); /** * Param "timePerSample" */ @NameCn("稀疏度") @DescCn("整型数组,张量的size") ParamInfo <Double> TIME_PER_SAMPLE = ParamInfoFactory .createParamInfo("timePerSample", Double.class) .setDescription("time per sample") .setHasDefaultValue(null) .build(); default String getIdCol() { return get(ID_COL); } default T setIdCol(String value) { return set(ID_COL, value); } default String getOutputCol() { return get(OUTPUT_COL); } default T setOutputCol(String value) { return set(OUTPUT_COL, value); } default Integer[] getSize() { return get(SIZE); } default T setSize(Integer[] value) { return set(SIZE, value); } default Long getMaxRows() { return get(MAX_ROWS); } default T setMaxRows(Long value) { return set(MAX_ROWS, value); } default Double getSparsity() { return get(SPARSITY); } default T setSparsity(Double value) { return set(SPARSITY, value); } default Double getTimePerSample() { return get(TIME_PER_SAMPLE); } default T setTimePerSample(Double value) { return set(TIME_PER_SAMPLE, value); } }
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.dfa; /** * @since Created on 14.07.2004 * @author raik */ public class VariableAccessException extends Exception { private static final long serialVersionUID = 7385246683069003412L; public VariableAccessException() { super("VariableAccess error."); // TODO redefinition } public VariableAccessException(String message) { super(message); } }
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. */ package com.ckfinder.connector.configuration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ckfinder.connector.data.EventArgs; import com.ckfinder.connector.data.EventCommandData; import com.ckfinder.connector.data.IEventHandler; import com.ckfinder.connector.data.PluginInfo; import com.ckfinder.connector.errors.ConnectorException; /** * Provides support for event handlers. */ public class Events { private Map<EventTypes, List<EventCommandData>> eventHandlers; /** * The list of events. */ public enum EventTypes { BeforeExecuteCommand, AfterFileUpload, InitCommand; } /** * default constructor. */ public Events() { eventHandlers = new HashMap<Events.EventTypes, List<EventCommandData>>(); eventHandlers.put(EventTypes.AfterFileUpload, new ArrayList<EventCommandData>()); eventHandlers.put(EventTypes.InitCommand, new ArrayList<EventCommandData>()); eventHandlers.put(EventTypes.BeforeExecuteCommand, new ArrayList<EventCommandData>()); } /** * register events handlers for event. * @param event selected event * @param eventHandler event class to register */ public void addEventHandler(final EventTypes event, final Class<? extends IEventHandler> eventHandler) { EventCommandData eventCommandData = new EventCommandData(eventHandler); eventHandlers.get(event).add(eventCommandData); } /** * register events handlers for event. * @param event selected event * @param eventHandler event class to register * @param pluginInfo plugin info */ public void addEventHandler(final EventTypes event, final Class<? extends IEventHandler> eventHandler, final PluginInfo pluginInfo) { EventCommandData eventCommandData = new EventCommandData(eventHandler); eventCommandData.setPluginInfo(pluginInfo); eventHandlers.get(event).add(eventCommandData); } /** * run event handlers for selected event. * @param eventTyp selected event. * @param args event execute arguments. * @param configuration connector configuration * @return false when end executing command. * @throws ConnectorException when error occurs. */ public boolean run(final EventTypes eventTyp, final EventArgs args, final IConfiguration configuration) throws ConnectorException { for (EventCommandData eventCommandData : eventHandlers.get(eventTyp)) { try { IEventHandler events = null; if (eventCommandData.getPluginInfo() != null) { events = eventCommandData.getEventListener() .getConstructor(PluginInfo.class) .newInstance(eventCommandData.getPluginInfo()); } else { events = eventCommandData.getEventListener().newInstance(); } if (!events.runEventHandler(args, configuration)) { return false; } } catch (Exception e) { throw new ConnectorException(e); } } return true; } }
package fileio; import java.io.*; public class FileIO implements IFileIO { private BufferedReader reader; private BufferedWriter writer; public FileIO(String inputFile, String outputFile) { try { this.reader = new BufferedReader(new FileReader(inputFile)); this.writer = new BufferedWriter(new FileWriter(outputFile)); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } } @Override public String loadLine() throws IOException { String line = this.reader.readLine(); if (line != null) return line.toUpperCase(); return null; } @Override public void saveLine(String line) throws IOException { line += "\n"; this.writer.write(line); } public void closeInputFile() throws IOException { this.reader.close(); } public void closeOutputFile() throws IOException { this.writer.close(); } }
package us.kbase.test.auth2.service; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static us.kbase.test.auth2.TestCommon.set; import java.net.URI; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import us.kbase.auth2.lib.identity.IdentityProviderConfig; import us.kbase.auth2.lib.token.IncomingToken; import us.kbase.auth2.service.AuthStartupConfig; import us.kbase.auth2.service.LoggingFilter; import us.kbase.auth2.service.SLF4JAutoLogger; import us.kbase.common.test.RegexMatcher; import us.kbase.test.auth2.MongoStorageTestManager; import us.kbase.test.auth2.StandaloneAuthServer; import us.kbase.test.auth2.TestCommon; import us.kbase.test.auth2.StandaloneAuthServer.ServerThread; public class LoggingFilterTest { private static final String DB_NAME = "test_link_ui"; private static final String COOKIE_NAME = "login-cookie"; private static final Client CLI = ClientBuilder.newClient(); private static MongoStorageTestManager manager = null; private static StandaloneAuthServer server = null; private static int port = -1; private static String host = null; private static List<ILoggingEvent> logEvents = new LinkedList<>(); private static SLF4JAutoLogger autologgermock = mock(SLF4JAutoLogger.class); public static class LoggingFilterTestConfig implements AuthStartupConfig { public static String mongohost; @Override public SLF4JAutoLogger getLogger() { return autologgermock; } @Override public Set<IdentityProviderConfig> getIdentityProviderConfigs() { return set(); } @Override public String getMongoHost() { return mongohost; } @Override public String getMongoDatabase() { return DB_NAME; } @Override public Optional<String> getMongoUser() { return Optional.absent(); } @Override public Optional<char[]> getMongoPwd() { return Optional.absent(); } @Override public String getTokenCookieName() { return COOKIE_NAME; } @Override public boolean isTestModeEnabled() { return false; } } @BeforeClass public static void beforeClass() throws Exception { TestCommon.stfuLoggers(); manager = new MongoStorageTestManager(DB_NAME); LoggingFilterTestConfig.mongohost = "localhost:" + manager.mongo.getServerPort(); server = new StandaloneAuthServer(LoggingFilterTestConfig.class.getName()); new ServerThread(server).start(); System.out.println("Main thread waiting for server to start up"); while (server.getPort() == null) { Thread.sleep(1000); } port = server.getPort(); host = "http://localhost:" + port; setUpSLF4JTestLoggerAppender(); } private static void setUpSLF4JTestLoggerAppender() { // MongoStorageTestManager turns off the logger, so reenable here final Logger logger = (Logger) LoggerFactory .getLogger("us.kbase.auth2.service.LoggingFilter"); logger.setLevel(ch.qos.logback.classic.Level.ALL); final Logger authRootLogger = (Logger) LoggerFactory.getLogger("us.kbase.auth2"); authRootLogger.setLevel(Level.ALL); authRootLogger.setAdditive(false); final AppenderBase<ILoggingEvent> appender = new AppenderBase<ILoggingEvent>() { @Override protected void append(final ILoggingEvent event) { logEvents.add(event); } }; appender.start(); authRootLogger.addAppender(appender); } @AfterClass public static void afterClass() throws Exception { if (server != null) { server.stop(); } if (manager != null) { manager.destroy(); } } @Before public void beforeTest() throws Exception { ServiceTestUtils.resetServer(manager, host, COOKIE_NAME); logEvents.clear(); reset(autologgermock); // bad practice but too expensive to restart server per test // should look into unit testing the logger again at some point, but difficult to find // good examples of how to test with @Context injections, and what I did see was absurdly // complex // not that this isn't absurdly complex, but I could get it working anyway } private class SetCallInfoAnswer implements Answer<Void> { private String recordedmethod; private String recordedid; private String recordedip; @Override public Void answer(final InvocationOnMock inv) throws Throwable { recordedmethod = inv.getArgument(0); recordedid = inv.getArgument(1); recordedip = inv.getArgument(2); return null; } public void check(final String method, final String ip) { assertThat("incorrect method", recordedmethod, is(method)); assertThat("invalid call id", recordedid, RegexMatcher.matches("\\d{16}")); assertThat("incorrect ip address", recordedip, is(ip)); } } @Test public void ignoreIPHeaders() throws Exception { final SetCallInfoAnswer ans = new SetCallInfoAnswer(); doAnswer(ans).when(autologgermock).setCallInfo( any(String.class), any(String.class), any(String.class)); final IncomingToken admintoken = ServiceTestUtils.getAdminToken(manager); ServiceTestUtils.ignoreIpHeaders(host, admintoken); logEvents.clear(); final URI target = UriBuilder.fromUri(host).path("/customroles").build(); final WebTarget wt = CLI.target(target); final Builder req = wt.request() .cookie(COOKIE_NAME, admintoken.getToken()) .header("user-agent", "a user agent") .header("x-forwarded-for", "127.0.0.2, 127.0.0.3") .header("x-real-ip", "127.0.0.4"); final Response res = req.get(); assertThat("incorrect status code", res.getStatus(), is(200)); ans.check("GET", "127.0.0.1"); checkInfoEvents(String.format("GET %s/customroles 200 a user agent", host)); } private void checkInfoEvents(final String... messages) { assertThat("incorrect number of log events: " + logEvents, logEvents.size(), is(messages.length)); final Iterator<ILoggingEvent> i = logEvents.iterator(); for (final String msg: messages) { final ILoggingEvent got = i.next(); assertThat("incorrect log level", got.getLevel(), is(Level.INFO)); assertThat("incorrect caller", got.getLoggerName(), is(LoggingFilter.class.getName())); assertThat("incorrect message", got.getFormattedMessage(), is(msg)); } } @Test public void withXForwardedFor() throws Exception { final SetCallInfoAnswer ans = new SetCallInfoAnswer(); doAnswer(ans).when(autologgermock).setCallInfo( any(String.class), any(String.class), any(String.class)); final URI target = UriBuilder.fromUri(host).path("/").build(); final WebTarget wt = CLI.target(target); final Builder req = wt.request() .header("user-agent", "an user agent") .header("x-forwarded-for", "127.0.0.2, 127.0.0.3"); final Response res = req.get(); assertThat("incorrect status code", res.getStatus(), is(200)); ans.check("GET", "127.0.0.2"); checkInfoEvents("X-Forwarded-For: 127.0.0.2, 127.0.0.3, Remote IP: 127.0.0.1", String.format("GET %s/ 200 an user agent", host)); } @Test public void withXRealIP() throws Exception { final SetCallInfoAnswer ans = new SetCallInfoAnswer(); doAnswer(ans).when(autologgermock).setCallInfo( any(String.class), any(String.class), any(String.class)); final URI target = UriBuilder.fromUri(host).path("/").build(); final WebTarget wt = CLI.target(target); final Builder req = wt.request() .header("user-agent", "the user specific agent") .header("x-real-ip", "127.0.0.4"); final Response res = req.get(); assertThat("incorrect status code", res.getStatus(), is(200)); ans.check("GET", "127.0.0.4"); checkInfoEvents("X-Real-IP: 127.0.0.4, Remote IP: 127.0.0.1", String.format("GET %s/ 200 the user specific agent", host)); } @Test public void withBothIPHeaders() throws Exception { final SetCallInfoAnswer ans = new SetCallInfoAnswer(); doAnswer(ans).when(autologgermock).setCallInfo( any(String.class), any(String.class), any(String.class)); final URI target = UriBuilder.fromUri(host).path("/").build(); final WebTarget wt = CLI.target(target); final Builder req = wt.request() .header("user-agent", "the user agent") .header("x-forwarded-for", " 127.0.0.2, 127.0.0.3 ") .header("x-real-ip", " 127.0.0.4 "); final Response res = req.get(); assertThat("incorrect status code", res.getStatus(), is(200)); ans.check("GET", "127.0.0.2"); checkInfoEvents("X-Forwarded-For: 127.0.0.2, 127.0.0.3, " + "X-Real-IP: 127.0.0.4, Remote IP: 127.0.0.1", String.format("GET %s/ 200 the user agent", host)); } @Test public void withNeitherIPHeader() throws Exception { final SetCallInfoAnswer ans = new SetCallInfoAnswer(); doAnswer(ans).when(autologgermock).setCallInfo( any(String.class), any(String.class), any(String.class)); final URI target = UriBuilder.fromUri(host).path("/").build(); final WebTarget wt = CLI.target(target); final Builder req = wt.request() .header("user-agent", "always a user agent, never your user agent"); final Response res = req.get(); assertThat("incorrect status code", res.getStatus(), is(200)); ans.check("GET", "127.0.0.1"); checkInfoEvents( String.format("GET %s/ 200 always a user agent, never your user agent", host)); } }
package com.order.orderapp.appcontroller; import com.order.orderapp.dto.input.OrderInput; import com.order.orderapp.model.*; import com.order.orderapp.service.ItemServiceInterface; import com.order.orderapp.service.ProductService; import com.order.orderapp.service.ServiceService; import org.modelmapper.Converter; import org.modelmapper.ModelMapper; import org.modelmapper.spi.MappingContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.List; @Component("orderIO") public class OrderIO { private ModelMapper modelMapper; @Autowired private ProductService productService; @Autowired private ServiceService serviceService; final Converter<OrderInput, Order> orderConverter = new Converter<OrderInput, Order>() { @Override public Order convert(MappingContext<OrderInput, Order> context) { OrderInput orderInput = context.getSource(); Order order = new Order(); order.setId(orderInput.getId()); order.setDateTime(Calendar.getInstance()); order.setDiscount(orderInput.getDiscount()); order.setOrderStatus(orderInput.getOrderStatus()); order.setItems(getItens(orderInput.getItems())); return order; } }; public OrderIO() { modelMapper = new ModelMapper(); modelMapper.addConverter(orderConverter); } public Order mapTo(OrderInput orderInput) { return this.modelMapper.map(orderInput, Order.class); } private List<OrderItem> getItens(List<Object> items){ ArrayList<OrderItem> orderItemList = new ArrayList<>(); OrderItem orderItem = null; for(Object o: items){ LinkedHashMap generic = ((LinkedHashMap)o); int idOrderItem = 0; if(generic.containsKey("id")){ idOrderItem = (int) generic.get("id"); }; int idItem = (int) generic.get("idItem"); String type = (String) generic.get("type"); ItemServiceInterface service = getService(type); Item item = (Item) service.get(idItem); if(item == null) continue; orderItem = new OrderItem(); orderItem.setId(idOrderItem); orderItem.setPrice(item.getPrice()); orderItem.setItem(item); orderItemList.add(orderItem); } return orderItemList; } private ItemServiceInterface getService(String type){ if(type ==null) return null; switch (type){ case "product": return productService; case "service": return serviceService; default: return null; } } }
import lejos.nxt.Button; import lejos.nxt.LCD; import lejos.nxt.Motor; import lejos.util.Delay; public class MotorLab{ public static void main(String[] args) { int motA, motB; LCD.drawString("Motor Test",0,0); //1 Button.waitForAnyPress(); //2 LCD.clear(); Motor.A.setSpeed(720);//3 Motor.B.setSpeed(720); do{ LCD.clear(); Motor.A.rotate(720,true); Motor.B.rotate(720,true); Delay.msDelay(1000); LCD.drawInt(Motor.A.getTachoCount(),0,0); LCD.drawInt(Motor.B.getTachoCount(),0,1); motA = Motor.A.getTachoCount(); motB = Motor.B.getTachoCount(); LCD.drawInt((motA - motB),0,2); //Motor.B.stop(); //Motor.A.stop(); Delay.msDelay(500); }while(Button.ESCAPE.isPressed() == false); } }