repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
CodyyAndroid/RxPermissions
rxpermissionslibrary/src/main/java/com/codyy/rx/permissions/RxPermissions.java
13205
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codyy.rx.permissions; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import io.reactivex.Observable; import io.reactivex.ObservableSource; import io.reactivex.ObservableTransformer; import io.reactivex.functions.Function; import io.reactivex.subjects.PublishSubject; public class RxPermissions { static final String TAG = "RxPermissions"; private RxPermissionsFragment mRxPermissionsFragment; public RxPermissions(@NonNull android.support.v4.app.FragmentManager fragmentManager) { mRxPermissionsFragment = getRxPermissionsFragment(fragmentManager); } private RxPermissionsFragment getRxPermissionsFragment(@NonNull android.support.v4.app.FragmentManager fragmentManager) { RxPermissionsFragment rxPermissionsFragment = findRxPermissionsFragment(fragmentManager); boolean isNewInstance = rxPermissionsFragment == null; if (isNewInstance) { rxPermissionsFragment = new RxPermissionsFragment(); fragmentManager .beginTransaction() .add(rxPermissionsFragment, TAG) .commitAllowingStateLoss(); fragmentManager.executePendingTransactions(); } return rxPermissionsFragment; } private RxPermissionsFragment findRxPermissionsFragment(@NonNull android.support.v4.app.FragmentManager fragmentManager) { return (RxPermissionsFragment) fragmentManager.findFragmentByTag(TAG); } public void setLogging(boolean logging) { mRxPermissionsFragment.setLogging(logging); } /** * Map emitted items from the source observable into {@code true} if permissions in parameters * are granted, or {@code false} if not. * <p> * If one or several permissions have never been requested, invoke the related framework method * to ask the user if he allows the permissions. */ @SuppressWarnings("WeakerAccess") public ObservableTransformer<Object, Boolean> ensure(final String... permissions) { return new ObservableTransformer<Object, Boolean>() { @Override public ObservableSource<Boolean> apply(Observable<Object> observable) { return request(observable, permissions) // Transform Observable<Permission> to Observable<Boolean> .buffer(permissions.length) .flatMap(new Function<List<Permission>, ObservableSource<Boolean>>() { @Override public ObservableSource<Boolean> apply(@io.reactivex.annotations.NonNull List<Permission> permissions) throws Exception { if (permissions.isEmpty()) { // Occurs during orientation change, when the subject receives onComplete. // In that case we don't want to propagate that empty list to the // subscriber, only the onComplete. return Observable.empty(); } // Return true if all permissions are granted. for (Permission p : permissions) { if (!p.granted) { return Observable.just(false); } } return Observable.just(true); } }); } }; } /** * Map emitted items from the source observable into {@link Permission} objects for each * permission in parameters. * <p> * If one or several permissions have never been requested, invoke the related framework method * to ask the user if he allows the permissions. */ @SuppressWarnings("WeakerAccess") public ObservableTransformer<Object, Permission> ensureEach(final String... permissions) { return new ObservableTransformer<Object, Permission>() { @Override public ObservableSource<Permission> apply(Observable<Object> observable) { return request(observable, permissions); } }; } /** * Request permissions immediately, <b>must be invoked during initialization phase * of your application</b>. */ @SuppressWarnings({"WeakerAccess", "unused"}) public Observable<Boolean> request(final String... permissions) { return Observable.just(1).compose(ensure(permissions)); } /** * Request permissions immediately, <b>must be invoked during initialization phase * of your application</b>. */ @SuppressWarnings({"WeakerAccess", "unused"}) public Observable<Permission> requestEach(final String... permissions) { return Observable.just(1).compose(ensureEach(permissions)); } private Observable<Permission> request(final Observable<?> trigger, final String... permissions) { if (permissions == null || permissions.length == 0) { throw new IllegalArgumentException("RxPermissions.request/requestEach requires at least one input permission"); } return oneOf(trigger, pending(permissions)) .flatMap(new Function<Object, ObservableSource<Permission>>() { @Override public ObservableSource<Permission> apply(@io.reactivex.annotations.NonNull Object o) throws Exception { return requestImplementation(permissions); } }); } private Observable<?> pending(final String... permissions) { for (String p : permissions) { if (!mRxPermissionsFragment.containsByPermission(p)) { return Observable.empty(); } } return Observable.just(1); } private Observable<?> oneOf(Observable<?> trigger, Observable<?> pending) { if (trigger == null) { return Observable.just(1); } return Observable.merge(trigger, pending); } private Observable<Permission> requestImplementation(final String... permissions) { List<Observable<Permission>> list = new ArrayList<>(permissions.length); List<String> unrequestedPermissions = new ArrayList<>(); // In case of multiple permissions, we create an Observable for each of them. // At the end, the observables are combined to have a unique response. for (String permission : permissions) { mRxPermissionsFragment.log("Requesting permission " + permission); if (isGranted(permission)) { // Already granted, or not Android M // Return a granted Permission object. list.add(Observable.just(new Permission(permission, true, false))); continue; } if (isRevoked(permission)) { // Revoked by a policy, return a denied Permission object. list.add(Observable.just(new Permission(permission, false, false))); continue; } PublishSubject<Permission> subject = mRxPermissionsFragment.getSubjectByPermission(permission); // Create a new subject if not exists if (subject == null) { unrequestedPermissions.add(permission); subject = PublishSubject.create(); mRxPermissionsFragment.setSubjectForPermission(permission, subject); } list.add(subject); } if (!unrequestedPermissions.isEmpty()) { String[] unrequestedPermissionsArray = unrequestedPermissions.toArray(new String[unrequestedPermissions.size()]); requestPermissionsFromFragment(unrequestedPermissionsArray); } return Observable.concat(Observable.fromIterable(list)); } /** * Invokes Activity.shouldShowRequestPermissionRationale and wraps * the returned value in an observable. * <p> * In case of multiple permissions, only emits true if * Activity.shouldShowRequestPermissionRationale returned true for * all revoked permissions. * <p> * You shouldn't call this method if all permissions have been granted. * <p> * For SDK &lt; 23, the observable will always emit false. */ @SuppressWarnings("WeakerAccess") public Observable<Boolean> shouldShowRequestPermissionRationale(final Activity activity, final String... permissions) { if (!isMarshmallow()) { return Observable.just(false); } return Observable.just(shouldShowRequestPermissionRationaleImplementation(activity, permissions)); } @TargetApi(Build.VERSION_CODES.M) private boolean shouldShowRequestPermissionRationaleImplementation(final Activity activity, final String... permissions) { for (String p : permissions) { if (!isGranted(p) && !activity.shouldShowRequestPermissionRationale(p)) { return false; } } return true; } @TargetApi(Build.VERSION_CODES.M) void requestPermissionsFromFragment(String[] permissions) { mRxPermissionsFragment.log("requestPermissionsFromFragment " + TextUtils.join(", ", permissions)); mRxPermissionsFragment.requestPermissions(permissions); } /** * Returns true if the permission is already granted. * <p> * Always true if SDK &lt; 23. */ @SuppressWarnings("WeakerAccess") public boolean isGranted(String permission) { return !isMarshmallow() || mRxPermissionsFragment.isGranted(permission); } /** * Returns true if the permission has been revoked by a policy. * <p> * Always false if SDK &lt; 23. */ @SuppressWarnings("WeakerAccess") public boolean isRevoked(String permission) { return isMarshmallow() && mRxPermissionsFragment.isRevoked(permission); } boolean isMarshmallow() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } void onRequestPermissionsResult(String permissions[], int[] grantResults) { mRxPermissionsFragment.onRequestPermissionsResult(permissions, grantResults, new boolean[permissions.length]); } /** * 未授予系统权限,弹窗提示并引导用户到应用设置页打开权限 * * @param context context * @param packageName 包名 * @param message 提示信息 */ public static void showDialog(@NonNull final Context context, @NonNull final String packageName, @NonNull String message) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("提示").setMessage(message); builder.setCancelable(true); builder.setPositiveButton("去打开", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { openPermissionSettings(context, packageName); } }).setNegativeButton("取消", null).create().show(); } /** * 打开权限设置页面 * * @param context context * @param packageName 包名 */ public static void openPermissionSettings(@NonNull Context context, @NonNull String packageName) { Intent intent = new Intent(); intent.setAction("miui.intent.action.APP_PERM_EDITOR");//适配小米MIUI系统权限管理 intent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra("extra_pkgname", packageName); if (intent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(intent); } else { Uri packageURI = Uri.parse("package:" + packageName); intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", packageURI);//谷歌原生系统权限管理 if (intent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(intent); } else { Toast.makeText(context, "打开系统权限管理功能失败", Toast.LENGTH_SHORT).show(); } } } }
apache-2.0
andrescabrera/gwt-dojo-toolkit
src/gwt/dojo/gridx/public/dojo/gridx/mobile/StoreObserver.js
1896
define([ 'dojo/_base/declare', 'dojo/dom-construct', 'dojo/_base/array', 'dojo/query' ], function(declare, dom, array, query){ return declare(null, { // summary: // This module is a mixin of the grid and // it makes the grid reflect the change of the store. onSet: function(/*Object*/item, /*String*/attribute, /*Object|Array*/oldValue, /*Object|Array*/newValue){ // summary: // See dojo.data.api.Notification.onSet() var rowId = this.store.getIdentity(item); var rowTable = query('*[rowId="'+rowId+'"] table', this.bodyNode)[0]; var colIndex = 0; for(colIndex = 0; colIndex < this.columns.length; colIndex++){ if(this.columns[colIndex].field == attribute){break;} } if(colIndex < this.columns.length){ rowTable.rows[0].cells[colIndex].innerHTML = this._getCellContent(this.columns[colIndex], item); } }, onNew: function(/*Object*/newItem, /*Object?*/parentInfo){ // summary: // See dojo.data.api.Notification.onNew() }, onDelete: function(/*Object*/deletedItem){ // summary: // See dojo.data.api.Notification.onDelete() }, onStoreClose: function(/*Object?*/request){ // summary: // Refresh list on close. }, onError: function(){}, _buildBody:function(){ //observe only after body is built this.inherited(arguments); // this._ob && this._ob.cancel(); // var self = this; // this._ob = this._queryResults.observe(function(object, removedFrom, insertedInto){ // if(removedFrom > -1){ // self._removeRow(object, removedFrom); // } // if(insertedInto > -1){ // self._insertRow(object, insertedInto); // } // }, this); }, _removeRow: function(item, idx){ dom.destroy(this.bodyNode.firstChild.childNodes[idx]); }, _insertRow: function(item, idx){ dom.place(this._createRow(item, idx), this.bodyNode.firstChild, idx); } }); });
apache-2.0
camptocamp/puppet-postfix
spec/classes/postfix_satellite_spec.rb
712
require 'spec_helper' describe 'postfix::satellite' do let :pre_condition do " class { 'augeas': } class { 'postfix': relayhost => 'foo', mydestination => 'bar', mynetworks => 'baz', }" end on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts.merge(augeasversion: '1.2.0', puppetversion: Puppet.version) end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_class('postfix::mta') } it { is_expected.to contain_postfix__virtual('@foo.example.com').with( ensure: 'present', destination: 'root' ) } end end end
apache-2.0
stori-es/stori_es
shared/src/main/java/org/consumersunion/stories/server/persistence/ContactPersister.java
32532
package org.consumersunion.stories.server.persistence; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.consumersunion.stories.common.shared.model.Address; import org.consumersunion.stories.common.shared.model.User; import org.consumersunion.stories.common.shared.model.entity.Contact; import org.consumersunion.stories.common.shared.model.entity.ContactStatus; import org.consumersunion.stories.common.shared.service.GeneralException; import org.consumersunion.stories.server.persistence.funcs.ProcessFunc; import org.springframework.stereotype.Component; import com.google.common.collect.Lists; @Component public class ContactPersister { private final PersistenceService persistenceService; @Inject ContactPersister(PersistenceService persistenceService) { this.persistenceService = persistenceService; } public Contact retrieveEmailContact(int profileId, final String email) { return persistenceService.process(new ProcessFunc<Integer, Contact>(profileId) { @Override public Contact process() { try { PreparedStatement retrieve = conn .prepareStatement("SELECT entityId, medium, type, value, status FROM contact " + "WHERE entityId = ? AND value = ?"); retrieve.setInt(1, input); retrieve.setString(2, email); ResultSet rs = retrieve.executeQuery(); if (rs.next()) { return new Contact(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), ContactStatus.valueOf(rs.getString(5))); } return null; } catch (SQLException e) { throw new GeneralException(e); } } }); } public List<Contact> retrieveEmails(User user) { return persistenceService.process(new ProcessFunc<User, List<Contact>>(user) { @Override public List<Contact> process() { try { PreparedStatement select = conn.prepareStatement( "SELECT c.entityId, c.medium, c.type, c.value, c.status FROM contact c " + "JOIN profile p ON p.id = c.entityId " + "JOIN user u ON p.user = u.id " + "WHERE c.medium = 'EMAIL' AND u.id = ? " + "GROUP BY c.value;"); select.setInt(1, input.getId()); ResultSet rs = select.executeQuery(); List<Contact> emails = Lists.newArrayList(); while (rs.next()) { Contact contact = new Contact(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), ContactStatus.valueOf(rs.getString(5))); emails.add(contact); } return emails; } catch (SQLException e) { throw new GeneralException(e); } } }); } public void setContactStatus(int profileId, final String email, final ContactStatus status) { persistenceService.process(new ProcessFunc<Integer, Void>(profileId) { @Override public Void process() { try { PreparedStatement update = conn.prepareStatement("UPDATE contact " + "SET status='" + status.name() + "' WHERE entityId = ? AND value = ?"); update.setInt(1, input); update.setString(2, email); update.executeUpdate(); return null; } catch (SQLException e) { throw new GeneralException(e); } } }); } public List<Contact> retrieveContacts(int entityId) { return persistenceService.process(new ContactPersister.RetrieveContactFunc(entityId)); } public List<Contact> retrieveSocialContacts(int entityId) { return persistenceService.process(new ContactPersister.RetrieveSocialContactFunc(entityId)); } public List<Contact> saveContacts(List<Contact> contacts, int entityId) { return persistenceService.process(new ContactPersister.SaveContactsFunc(contacts, entityId)); } public List<Contact> saveContacts(List<Contact> contacts, Integer entityId, Connection conn) { return persistenceService.process(conn, new ContactPersister.SaveContactsFunc(contacts, entityId)); } public List<Address> retrieveAddress(int entityId) { return persistenceService.process(new ContactPersister.RetrieveAddress(entityId)); } public List<Address> retrieveAddress(Integer entityId, Connection conn) { return persistenceService.process(conn, new ContactPersister.RetrieveAddress(entityId)); } public List<Address> saveAddresses(List<Address> addresses, int entityId) { return persistenceService.process(new UpdateAddressForEntity(addresses, entityId)); } public void saveContact( final int entityId, final String originalValue, Contact contact) { contact.setEntityId(entityId); persistenceService.process(new ProcessFunc<Contact, Contact>(contact) { @Override public Contact process() { try { boolean isNew = originalValue == null; PreparedStatement statement; if (isNew) { List<Integer> usedIndexes = ContactPersister.getUsedIdx(conn, entityId); statement = conn.prepareStatement( "INSERT INTO contact (type, medium, value, status, entityId, idx) VALUES(?,?,?,?,?,?)"); statement.setString(4, input.getStatus().name()); statement.setInt(6, ContactPersister.getAvailableIndex(0, usedIndexes)); } else { statement = conn.prepareStatement("UPDATE contact " + "SET type=?, medium=?, value=?, status=? " + "WHERE entityId = ? AND value = ?"); statement.setString(4, ContactStatus.UNVERIFIED.name()); statement.setString(6, originalValue); } statement.setString(1, input.getType()); statement.setString(2, input.getMedium()); statement.setString(3, input.getValue()); statement.setInt(5, input.getEntityId()); statement.executeUpdate(); input.setStatus(ContactStatus.UNVERIFIED); } catch (SQLException e) { e.printStackTrace(); } return input; } }); } public String retrievePrimaryEmail(int profile) { return persistenceService.process(new ProcessFunc<Integer, String>(profile) { @Override public String process() { try { PreparedStatement select = conn.prepareStatement("SELECT value AS email FROM contact c WHERE medium='EMAIL' " + "AND status LIKE '%VERIFIED' " + "AND c.entityId=? " + "ORDER BY FIELD(status, 'VERIFIED', 'UNVERIFIED'), FIELD(type, 'Home', 'Mobile', " + "'Other')"); select.setInt(1, input); ResultSet resultSet = select.executeQuery(); if (resultSet.next()) { return resultSet.getString(1); } return null; } catch (SQLException e) { throw new GeneralException(e); } } }); } public void updateEmailContactStatus(Map<String, ContactStatus> contactStatus) { persistenceService.process(new ProcessFunc<Map<String, ContactStatus>, Void>(contactStatus) { @Override public Void process() { try { PreparedStatement update = conn.prepareStatement("UPDATE contact " + "SET status=? WHERE value=?"); for (Map.Entry<String, ContactStatus> entry : input.entrySet()) { update.setString(1, entry.getValue().name()); update.setString(2, entry.getKey()); update.addBatch(); } update.executeBatch(); return null; } catch (SQLException e) { throw new GeneralException(e); } } }); } private static int getAvailableIndex(int index, List<Integer> usedIndexes) { while (usedIndexes.contains(index)) { index++; } return index; } private static List<Integer> getUsedIdx(Connection conn, int entityId) throws SQLException { PreparedStatement usedIndexesStatement = conn.prepareStatement( "SELECT idx FROM contact WHERE entityId = ? ORDER BY idx"); usedIndexesStatement.setInt(1, entityId); ResultSet indexesResultSet = usedIndexesStatement.executeQuery(); List<Integer> usedIndexes = Lists.newArrayList(); if (indexesResultSet.next()) { do { usedIndexes.add(indexesResultSet.getInt(1)); } while (indexesResultSet.next()); } return usedIndexes; } public static class UpdateAddress extends ProcessFunc<List<Address>, List<Address>> { public UpdateAddress(List<Address> address) { super(address); } @Override public List<Address> process() { try { if (!input.isEmpty()) { final PreparedStatement update = conn .prepareStatement("UPDATE address " + "SET address1=?, address2=?, city=?, state=?, country=?, postalCode=?, " + "latitude=?, longitude=?, geoCodeStatus=?, geoCodeProvider=?, geoCodeDate=? " + "WHERE entity=? AND idx=?"); for (Address address : input) { if (address.getAddress1() != null) { update.setString(1, address.getAddress1()); } else { update.setNull(1, Types.VARCHAR); } if (address.getAddress2() != null) { update.setString(2, address.getAddress2()); } else { update.setNull(2, Types.VARCHAR); } if (address.getCity() != null) { update.setString(3, address.getCity()); } else { update.setNull(3, Types.VARCHAR); } if (address.getState() != null) { update.setString(4, address.getState()); } else { update.setNull(4, Types.VARCHAR); } if (address.getCountry() != null) { update.setString(5, address.getCountry()); } else { update.setNull(5, Types.VARCHAR); } if (address.getCountry() != null) { update.setString(6, address.getPostalCode()); } else { update.setNull(6, Types.VARCHAR); } if (address.getLatitude() != null) { update.setBigDecimal(7, address.getLatitude()); } else { update.setNull(7, Types.BIGINT); } if (address.getLongitude() != null) { update.setBigDecimal(8, address.getLongitude()); } else { update.setNull(8, Types.BIGINT); } if (address.getGeoCodeStatus() != null) { update.setString(9, address.getGeoCodeStatus()); } else { update.setNull(9, Types.VARCHAR); } if (address.getGeoCodeProvider() != null) { update.setString(10, address.getGeoCodeProvider()); } else { update.setNull(10, Types.VARCHAR); } if (address.getGeoCodeDate() != null) { update.setTimestamp(11, new Timestamp(address.getGeoCodeDate().getTime())); } else { update.setNull(11, Types.DATE); } int idx = address.getIdx(); update.setInt(12, address.getEntity()); update.setInt(13, idx); update.addBatch(); } int[] updateCount = update.executeBatch(); if (updateCount.length != input.size()) { throw new GeneralException("Unexpected update count on update Address: " + updateCount.length); } } } catch (SQLException e) { throw new GeneralException(e); } return input; } } public static class DeleteAddress extends ProcessFunc<Address, Address> { public DeleteAddress(final Address input) { super(input); } @Override public Address process() { try { PreparedStatement delete = conn.prepareStatement( "DELETE FROM address WHERE entity = ? AND relation = ?"); delete.setInt(1, input.getEntity()); delete.setString(2, input.getRelation()); int deleteCount = delete.executeUpdate(); if (deleteCount != 1) { throw new GeneralException("Unexpected delete address: " + deleteCount); } return input; } catch (final SQLException ex) { throw new GeneralException(ex); } } } public static class RetrieveAddress extends ProcessFunc<Integer, List<Address>> { public RetrieveAddress(Integer entityId) { super(entityId); } @Override public List<Address> process() { List<Address> list = new ArrayList<Address>(); try { PreparedStatement select = conn .prepareStatement("SELECT entity, relation, address1, address2, city, state, country, " + "postalCode, latitude, longitude, geoCodeStatus, geoCodeProvider, geoCodeDate " + "FROM address WHERE entity = ? ORDER BY entity, relation, idx"); select.setInt(1, input); ResultSet rs = select.executeQuery(); if (rs.next()) { do { Address address = new Address(rs.getInt(1)); address.setRelation(rs.getString(2)); address.setRelation(rs.getString(2)); address.setAddress1(rs.getString(3)); address.setAddress2(rs.getString(4)); address.setCity(rs.getString(5)); address.setState(rs.getString(6)); address.setCountry(rs.getString(7)); address.setPostalCode(rs.getString(8)); address.setLatitude(rs.getBigDecimal(9)); address.setLongitude(rs.getBigDecimal(10)); address.setGeoCodeStatus(rs.getString(11)); address.setGeoCodeProvider(rs.getString(12)); address.setGeoCodeDate(rs.getDate(13)); list.add(address); } while (rs.next()); } } catch (SQLException ex) { throw new GeneralException(ex); } return list; } } public static class RetrieveRefreshAddresses extends ProcessFunc<Integer, List<Address>> { private final Integer nbDays; private final Integer maxResults; public RetrieveRefreshAddresses(Integer nbDays, Integer maxResults) { super(nbDays); this.nbDays = nbDays; this.maxResults = maxResults; } @Override public List<Address> process() { List<Address> list = Lists.newArrayList(); try { PreparedStatement select = conn .prepareStatement("SELECT entity, relation, address1, address2, city, state, country, " + "postalCode, latitude, longitude, geoCodeStatus, geoCodeProvider, geoCodeDate, idx " + "FROM address WHERE geoCodeDate < DATE_ADD(NOW(), INTERVAL -? DAY) " + "ORDER BY geoCodeDate ASC LIMIT ?"); select.setInt(1, nbDays); select.setInt(2, maxResults); ResultSet rs = select.executeQuery(); while (rs.next()) { final Address address = new Address(rs.getInt(1)); address.setRelation(rs.getString(2)); address.setRelation(rs.getString(2)); address.setAddress1(rs.getString(3)); address.setAddress2(rs.getString(4)); address.setCity(rs.getString(5)); address.setState(rs.getString(6)); address.setCountry(rs.getString(7)); address.setPostalCode(rs.getString(8)); address.setLatitude(rs.getBigDecimal(9)); address.setLongitude(rs.getBigDecimal(10)); address.setGeoCodeStatus(rs.getString(11)); address.setGeoCodeProvider(rs.getString(12)); address.setGeoCodeDate(rs.getDate(13)); address.setIdx(rs.getInt(14)); list.add(address); } } catch (SQLException ex) { throw new GeneralException(ex); } return list; } } public static class SaveContactsFunc extends ProcessFunc<List<Contact>, List<Contact>> { private final Integer entityId; public SaveContactsFunc(List<Contact> input) { this(input, input.get(0).getEntityId()); } public SaveContactsFunc(List<Contact> input, Integer entityId) { super(input); this.entityId = entityId; } @Override public List<Contact> process() { List<Contact> savedContacts = PersistenceUtil.process(conn, new RetrieveContactFunc(entityId)); for (Contact contact : input) { boolean exists = false; for (Contact savedContact : savedContacts) { if (!Contact.SOCIAL.equals(savedContact.getType()) && contact.getValue().equals( savedContact.getValue())) { exists = true; contact.setStatus(savedContact.getStatus()); break; } } if (!exists) { contact.setStatus(ContactStatus.UNVERIFIED); } } try { PreparedStatement delete = conn.prepareStatement( "DELETE FROM contact WHERE entityId = ? AND type <> ?"); delete.setInt(1, entityId); delete.setString(2, Contact.SOCIAL); delete.executeUpdate(); conn.commit(); if (!input.isEmpty()) { PreparedStatement usedIndexesStatement = conn.prepareStatement("SELECT idx FROM contact WHERE entityId = ? ORDER BY idx"); usedIndexesStatement.setInt(1, entityId); ResultSet indexesResultSet = usedIndexesStatement.executeQuery(); List<Integer> usedIndexes = Lists.newArrayList(); if (indexesResultSet.next()) { do { usedIndexes.add(indexesResultSet.getInt(1)); } while (indexesResultSet.next()); } PreparedStatement insert = conn.prepareStatement( "INSERT INTO contact (entityId, idx, type, medium, value, status) VALUES(?,?,?,?,?,?)"); int index = 0; for (Contact contact : input) { index = getAvailableIndex(index, usedIndexes); insert.setInt(1, entityId); insert.setInt(2, index++); insert.setString(3, contact.getType()); insert.setString(4, contact.getMedium()); insert.setString(5, contact.getValue()); insert.setString(6, contact.getStatus().name()); insert.addBatch(); } insert.executeBatch(); } return input; } catch (SQLException e) { throw new GeneralException(e); } } } public static class SaveSocialContactFunc extends ProcessFunc<List<Contact>, List<Contact>> { private final int entityId; public SaveSocialContactFunc(List<Contact> input, int entityId) { super(input); this.entityId = entityId; } @Override public List<Contact> process() { try { PreparedStatement delete = conn.prepareStatement( "DELETE FROM contact WHERE entityId = ? AND type = ?"); delete.setInt(1, entityId); delete.setString(2, Contact.SOCIAL); delete.executeUpdate(); conn.commit(); if (input != null && !input.isEmpty()) { List<Integer> usedIndexes = getUsedIdx(conn, entityId); PreparedStatement insert = conn.prepareStatement( "INSERT INTO contact (entityId, idx, type, medium, value) VALUES(?,?,?,?,?)"); int index = 0; for (Contact contact : input) { index = getAvailableIndex(index, usedIndexes); insert.setInt(1, entityId); insert.setInt(2, index++); insert.setString(3, contact.getType()); insert.setString(4, contact.getMedium()); insert.setString(5, contact.getValue()); insert.addBatch(); } insert.executeBatch(); } return input; } catch (SQLException e) { throw new GeneralException(e); } } } public static class RetrieveContactFunc extends ProcessFunc<Integer, List<Contact>> { public RetrieveContactFunc(Integer input) { super(input); } @Override public List<Contact> process() { try { PreparedStatement retrieve = conn .prepareStatement("SELECT entityId, medium, type, value, status FROM contact " + "WHERE entityId = ? ORDER BY idx"); retrieve.setInt(1, input); ResultSet rs = retrieve.executeQuery(); List<Contact> contacts = new ArrayList<Contact>(); if (rs.next()) { do { contacts.add(new Contact(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), ContactStatus.valueOf(rs.getString(5)))); } while (rs.next()); } return contacts; } catch (SQLException e) { throw new GeneralException(e); } } } public static class RetrieveSocialContactFunc extends ProcessFunc<Integer, List<Contact>> { public RetrieveSocialContactFunc(Integer input) { super(input); } @Override public List<Contact> process() { try { PreparedStatement retrieve = conn.prepareStatement( "SELECT entityId, medium, type, value FROM contact " + "WHERE entityId = ? AND type = ? ORDER BY idx"); retrieve.setInt(1, input); retrieve.setString(2, Contact.SOCIAL); ResultSet rs = retrieve.executeQuery(); List<Contact> contacts = new ArrayList<Contact>(); if (rs.next()) { do { contacts.add(new Contact(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4))); } while (rs.next()); } return contacts; } catch (SQLException e) { throw new GeneralException(e); } } } public static class DeleteContactFunc extends ProcessFunc<Contact, Contact> { public DeleteContactFunc(Contact input) { super(input); } @Override public Contact process() { try { PreparedStatement delete = conn .prepareStatement("DELETE FROM contact WHERE entityId = ? AND type =? " + "AND medium = ? AND value = ?"); delete.setInt(1, input.getEntityId()); delete.setString(2, input.getType()); delete.setString(3, input.getMedium()); delete.setString(4, input.getValue()); int deleteCount = delete.executeUpdate(); if (deleteCount != 1) { throw new GeneralException("Unexpected delete count: " + deleteCount); } return input; } catch (SQLException e) { throw new GeneralException(e); } } } public static class UpdateAddressForEntity extends ProcessFunc<List<Address>, List<Address>> { private final Integer entityId; public UpdateAddressForEntity(List<Address> address) { this(address, address.get(0).getEntity()); } public UpdateAddressForEntity(List<Address> addresses, Integer entityId) { super(addresses); this.entityId = entityId; } @Override public List<Address> process() { try { PreparedStatement delete = conn.prepareStatement("DELETE FROM address WHERE entity = ?"); delete.setInt(1, entityId); delete.executeUpdate(); if (!input.isEmpty()) { PreparedStatement insert = conn .prepareStatement("INSERT INTO address (entity, relation, idx, address1, address2, city, " + "state, country, postalCode, latitude, longitude, geoCodeStatus, " + "geoCodeProvider, geoCodeDate) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); for (int i = 0; i < input.size(); i++) { insert.setInt(1, entityId); insert.setString(2, input.get(i).getRelation()); insert.setInt(3, i); if (input.get(i).getAddress1() != null) { insert.setString(4, input.get(i).getAddress1()); } else { insert.setNull(4, Types.VARCHAR); } if (input.get(i).getAddress2() != null) { insert.setString(5, input.get(i).getAddress2()); } else { insert.setNull(5, Types.VARCHAR); } if (input.get(i).getCity() != null) { insert.setString(6, input.get(i).getCity()); } else { insert.setNull(6, Types.VARCHAR); } if (input.get(i).getState() != null) { insert.setString(7, input.get(i).getState()); } else { insert.setNull(7, Types.VARCHAR); } if (input.get(i).getCountry() != null) { insert.setString(8, input.get(i).getCountry()); } else { insert.setNull(8, Types.VARCHAR); } if (input.get(i).getCountry() != null) { insert.setString(9, input.get(i).getPostalCode()); } else { insert.setNull(9, Types.VARCHAR); } if (input.get(i).getLatitude() != null) { insert.setBigDecimal(10, input.get(i).getLatitude()); } else { insert.setNull(10, Types.BIGINT); } if (input.get(i).getLongitude() != null) { insert.setBigDecimal(11, input.get(i).getLongitude()); } else { insert.setNull(11, Types.BIGINT); } if (input.get(i).getGeoCodeStatus() != null) { insert.setString(12, input.get(i).getGeoCodeStatus()); } else { insert.setNull(12, Types.VARCHAR); } if (input.get(i).getGeoCodeProvider() != null) { insert.setString(13, input.get(i).getGeoCodeProvider()); } else { insert.setNull(13, Types.VARCHAR); } if (input.get(i).getGeoCodeDate() != null) { insert.setTimestamp(14, new Timestamp(input.get(i).getGeoCodeDate().getTime())); } else { insert.setNull(14, Types.DATE); } insert.addBatch(); } int[] insertCount = insert.executeBatch(); if (insertCount.length != input.size()) { throw new GeneralException("Unexpected insert count on update Address: " + insertCount.length); } } } catch (SQLException e) { throw new GeneralException(e); } return input; } } }
apache-2.0
brianhuangxp/FullMoon
fm-common/src/main/java/com/ringcentral/fullmoon/common/SysLogger.java
463
/* * Id: SysLogger.java * Type Name: com.ccb.cclbm.common.SysLogger * Create Date: 2005-3-15 * Author: robert.luo * * * Project: CCLBM * * * */ package com.ringcentral.fullmoon.common; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author robert.luo * * TODO */ public class SysLogger { public static Log getLog(Object obj){ return LogFactory.getLog(obj.getClass()); } }
apache-2.0
sabob/ratel
ratel/src/com/google/ratel/deps/jackson/databind/ser/DefaultSerializerProvider.java
17404
package com.google.ratel.deps.jackson.databind.ser; import java.io.IOException; import java.util.*; import com.google.ratel.deps.jackson.annotation.ObjectIdGenerator; import com.google.ratel.deps.jackson.core.JsonGenerationException; import com.google.ratel.deps.jackson.core.JsonGenerator; import com.google.ratel.deps.jackson.databind.*; import com.google.ratel.deps.jackson.databind.annotation.NoClass; import com.google.ratel.deps.jackson.databind.cfg.HandlerInstantiator; import com.google.ratel.deps.jackson.databind.introspect.Annotated; import com.google.ratel.deps.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; import com.google.ratel.deps.jackson.databind.jsonschema.SchemaAware; import com.google.ratel.deps.jackson.databind.node.ObjectNode; import com.google.ratel.deps.jackson.databind.ser.impl.WritableObjectId; import com.google.ratel.deps.jackson.databind.util.ClassUtil; /** * Standard implementation used by {@link ObjectMapper}: * adds methods only exposed to {@link ObjectMapper}, * as well as constructors. *<p> * Note that class is abstract just because it does not * define {@link #createInstance} method. *<p> * Also note that all custom {@link SerializerProvider} * implementations must sub-class this class: {@link ObjectMapper} * requires this type, not basic provider type. */ public abstract class DefaultSerializerProvider extends SerializerProvider implements java.io.Serializable // since 2.1; only because ObjectWriter needs it { private static final long serialVersionUID = 1L; /* /********************************************************** /* State, for non-blueprint instances: Object Id handling /********************************************************** */ /** * Per-serialization map Object Ids that have seen so far, iff * Object Id handling is enabled. */ protected transient IdentityHashMap<Object, WritableObjectId> _seenObjectIds; protected transient ArrayList<ObjectIdGenerator<?>> _objectIdGenerators; /* /********************************************************** /* Life-cycle /********************************************************** */ protected DefaultSerializerProvider() { super(); } protected DefaultSerializerProvider(SerializerProvider src, SerializationConfig config,SerializerFactory f) { super(src, config, f); } /* /********************************************************** /* Extended API: methods that ObjectMapper will call /********************************************************** */ /** * Overridable method, used to create a non-blueprint instances from the blueprint. * This is needed to retain state during serialization. */ public abstract DefaultSerializerProvider createInstance(SerializationConfig config, SerializerFactory jsf); /** * The method to be called by {@link ObjectMapper} and {@link ObjectWriter} * for serializing given value, using serializers that * this provider has access to (via caching and/or creating new serializers * as need be). */ public void serializeValue(JsonGenerator jgen, Object value) throws IOException, JsonGenerationException { JsonSerializer<Object> ser; final boolean wrap; if (value == null) { // no type provided; must just use the default null serializer ser = getDefaultNullValueSerializer(); wrap = false; // no name to use for wrapping; can't do! } else { Class<?> cls = value.getClass(); // true, since we do want to cache root-level typed serializers (ditto for null property) ser = findTypedValueSerializer(cls, true, null); // Ok: should we wrap result in an additional property ("root name")? String rootName = _config.getRootName(); if (rootName == null) { // not explicitly specified // [JACKSON-163] wrap = _config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE); if (wrap) { jgen.writeStartObject(); jgen.writeFieldName(_rootNames.findRootName(value.getClass(), _config)); } } else if (rootName.length() == 0) { wrap = false; } else { // [JACKSON-764] // empty String means explicitly disabled; non-empty that it is enabled wrap = true; jgen.writeStartObject(); jgen.writeFieldName(rootName); } } try { ser.serialize(value, jgen, this); if (wrap) { jgen.writeEndObject(); } } catch (IOException ioe) { // As per [JACKSON-99], pass IOException and subtypes as-is throw ioe; } catch (Exception e) { // but wrap RuntimeExceptions, to get path information String msg = e.getMessage(); if (msg == null) { msg = "[no message for "+e.getClass().getName()+"]"; } throw new JsonMappingException(msg, e); } } /** * The method to be called by {@link ObjectMapper} and {@link ObjectWriter} * for serializing given value (assumed to be of specified root type, * instead of runtime type of value), * using serializers that * this provider has access to (via caching and/or creating new serializers * as need be), * * @param rootType Type to use for locating serializer to use, instead of actual * runtime type. Must be actual type, or one of its super types */ public void serializeValue(JsonGenerator jgen, Object value, JavaType rootType) throws IOException, JsonGenerationException { final boolean wrap; JsonSerializer<Object> ser; if (value == null) { ser = getDefaultNullValueSerializer(); wrap = false; } else { // Let's ensure types are compatible at this point if (!rootType.getRawClass().isAssignableFrom(value.getClass())) { _reportIncompatibleRootType(value, rootType); } // root value, not reached via property: ser = findTypedValueSerializer(rootType, true, null); // [JACKSON-163] wrap = _config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE); if (wrap) { jgen.writeStartObject(); jgen.writeFieldName(_rootNames.findRootName(rootType, _config)); } } try { ser.serialize(value, jgen, this); if (wrap) { jgen.writeEndObject(); } } catch (IOException ioe) { // no wrapping for IO (and derived) throw ioe; } catch (Exception e) { // but others do need to be, to get path etc String msg = e.getMessage(); if (msg == null) { msg = "[no message for "+e.getClass().getName()+"]"; } throw new JsonMappingException(msg, e); } } /** * The method to be called by {@link ObjectWriter} * for serializing given value (assumed to be of specified root type, * instead of runtime type of value), when it may know specific * {@link JsonSerializer} to use. * * @param rootType Type to use for locating serializer to use, instead of actual * runtime type, if no serializer is passed * @param ser Root Serializer to use, if not null * * @since 2.1 */ public void serializeValue(JsonGenerator jgen, Object value, JavaType rootType, JsonSerializer<Object> ser) throws IOException, JsonGenerationException { final boolean wrap; if (value == null) { ser = getDefaultNullValueSerializer(); wrap = false; } else { // Let's ensure types are compatible at this point if (rootType != null) { if (!rootType.getRawClass().isAssignableFrom(value.getClass())) { _reportIncompatibleRootType(value, rootType); } } // root value, not reached via property: if (ser == null) { ser = findTypedValueSerializer(rootType, true, null); } wrap = _config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE); if (wrap) { jgen.writeStartObject(); jgen.writeFieldName(_rootNames.findRootName(rootType, _config)); } } try { ser.serialize(value, jgen, this); if (wrap) { jgen.writeEndObject(); } } catch (IOException ioe) { // no wrapping for IO (and derived) throw ioe; } catch (Exception e) { // but others do need to be, to get path etc String msg = e.getMessage(); if (msg == null) { msg = "[no message for "+e.getClass().getName()+"]"; } throw new JsonMappingException(msg, e); } } /** * The method to be called by {@link ObjectMapper} and {@link ObjectWriter} * to generate <a href="http://json-schema.org/">JSON schema</a> for * given type. * * @param type The type for which to generate schema */ @SuppressWarnings("deprecation") public com.google.ratel.deps.jackson.databind.jsonschema.JsonSchema generateJsonSchema(Class<?> type) throws JsonMappingException { if (type == null) { throw new IllegalArgumentException("A class must be provided"); } /* no need for embedded type information for JSON schema generation (all * type information it needs is accessible via "untyped" serializer) */ JsonSerializer<Object> ser = findValueSerializer(type, null); JsonNode schemaNode = (ser instanceof SchemaAware) ? ((SchemaAware) ser).getSchema(this, null) : com.google.ratel.deps.jackson.databind.jsonschema.JsonSchema.getDefaultSchemaNode(); if (!(schemaNode instanceof ObjectNode)) { throw new IllegalArgumentException("Class " + type.getName() +" would not be serialized as a JSON object and therefore has no schema"); } return new com.google.ratel.deps.jackson.databind.jsonschema.JsonSchema((ObjectNode) schemaNode); } /** * The method to be called by {@link ObjectMapper} and {@link ObjectWriter} * to to expose the format of the given to to the given visitor * * @param javaType The type for which to generate format * @param visitor the visitor to accept the format */ public void acceptJsonFormatVisitor(JavaType javaType, JsonFormatVisitorWrapper visitor) throws JsonMappingException { if (javaType == null) { throw new IllegalArgumentException("A class must be provided"); } /* no need for embedded type information for JSON schema generation (all * type information it needs is accessible via "untyped" serializer) */ visitor.setProvider(this); findValueSerializer(javaType, null).acceptJsonFormatVisitor(visitor, javaType); } /** * Method that can be called to see if this serializer provider * can find a serializer for an instance of given class. *<p> * Note that no Exceptions are thrown, including unchecked ones: * implementations are to swallow exceptions if necessary. */ public boolean hasSerializerFor(Class<?> cls) { try { return _findExplicitUntypedSerializer(cls) != null; } catch (JsonMappingException e) { // usually bad practice, but here caller only asked if a serializer // could be found; for which exception is useless return false; } } /* /******************************************************** /* Access to caching details /******************************************************** */ /** * Method that can be used to determine how many serializers this * provider is caching currently * (if it does caching: default implementation does) * Exact count depends on what kind of serializers get cached; * default implementation caches all serializers, including ones that * are eagerly constructed (for optimal access speed) *<p> * The main use case for this method is to allow conditional flushing of * serializer cache, if certain number of entries is reached. */ public int cachedSerializersCount() { return _serializerCache.size(); } /** * Method that will drop all serializers currently cached by this provider. * This can be used to remove memory usage (in case some serializers are * only used once or so), or to force re-construction of serializers after * configuration changes for mapper than owns the provider. */ public void flushCachedSerializers() { _serializerCache.flush(); } /* /********************************************************** /* Object Id handling /********************************************************** */ @Override public WritableObjectId findObjectId(Object forPojo, ObjectIdGenerator<?> generatorType) { if (_seenObjectIds == null) { _seenObjectIds = new IdentityHashMap<Object,WritableObjectId>(); } else { WritableObjectId oid = _seenObjectIds.get(forPojo); if (oid != null) { return oid; } } // Not seen yet; must add an entry, return it. For that, we need generator ObjectIdGenerator<?> generator = null; if (_objectIdGenerators == null) { _objectIdGenerators = new ArrayList<ObjectIdGenerator<?>>(8); } else { for (int i = 0, len = _objectIdGenerators.size(); i < len; ++i) { ObjectIdGenerator<?> gen = _objectIdGenerators.get(i); if (gen.canUseFor(generatorType)) { generator = gen; break; } } } if (generator == null) { generator = generatorType.newForSerialization(this); _objectIdGenerators.add(generator); } WritableObjectId oid = new WritableObjectId(generator); _seenObjectIds.put(forPojo, oid); return oid; } /* /********************************************************** /* Factory method impls /********************************************************** */ @Override public JsonSerializer<Object> serializerInstance(Annotated annotated, Object serDef) throws JsonMappingException { if (serDef == null) { return null; } JsonSerializer<?> ser; if (serDef instanceof JsonSerializer) { ser = (JsonSerializer<?>) serDef; } else { /* Alas, there's no way to force return type of "either class * X or Y" -- need to throw an exception after the fact */ if (!(serDef instanceof Class)) { throw new IllegalStateException("AnnotationIntrospector returned serializer definition of type " +serDef.getClass().getName()+"; expected type JsonSerializer or Class<JsonSerializer> instead"); } Class<?> serClass = (Class<?>)serDef; // there are some known "no class" markers to consider too: if (serClass == JsonSerializer.None.class || serClass == NoClass.class) { return null; } if (!JsonSerializer.class.isAssignableFrom(serClass)) { throw new IllegalStateException("AnnotationIntrospector returned Class " +serClass.getName()+"; expected Class<JsonSerializer>"); } HandlerInstantiator hi = _config.getHandlerInstantiator(); ser = (hi == null) ? null : hi.serializerInstance(_config, annotated, serClass); if (ser == null) { ser = (JsonSerializer<?>) ClassUtil.createInstance(serClass, _config.canOverrideAccessModifiers()); } } return (JsonSerializer<Object>) _handleResolvable(ser); } /* /********************************************************** /* Helper classes /********************************************************** */ /** * Concrete implementation that defines factory method(s), * defined as final. */ public final static class Impl extends DefaultSerializerProvider { private static final long serialVersionUID = 1L; public Impl() { super(); } protected Impl(SerializerProvider src, SerializationConfig config,SerializerFactory f) { super(src, config, f); } @Override public Impl createInstance(SerializationConfig config, SerializerFactory jsf) { return new Impl(this, config, jsf); } } }
apache-2.0
PkayJava/FAClient
src/main/java/com/angkorteam/finance/faclient/dto/client/ClientWithdraw.java
1027
package com.angkorteam.finance.faclient.dto.client; import java.io.Serializable; /** * Created by socheatkhauv on 4/6/17. */ public class ClientWithdraw implements Serializable { private String withdrawalDate; private Long withdrawalReasonId; private String locale; private String dateFormat; public String getWithdrawalDate() { return withdrawalDate; } public void setWithdrawalDate(String withdrawalDate) { this.withdrawalDate = withdrawalDate; } public Long getWithdrawalReasonId() { return withdrawalReasonId; } public void setWithdrawalReasonId(Long withdrawalReasonId) { this.withdrawalReasonId = withdrawalReasonId; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public String getDateFormat() { return dateFormat; } public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; } }
apache-2.0
stweil/tesseract-ocr.github.io
4.00.00dev/a02681.js
485
var a02681 = [ [ "BLOCK_RECT_IT", "a02681.html#a1344f314e5e85908725bac7a15726802", null ], [ "bounding_box", "a02681.html#a1e3195249b6b6934be9060f1d5ee60c2", null ], [ "cycled_rects", "a02681.html#af8914c72cc93eeb96ed231db37ab5043", null ], [ "forward", "a02681.html#ab56b686d27e5eea704424470024456f4", null ], [ "set_to_block", "a02681.html#a67e8a119f8c28be404bd1770fa22ce7f", null ], [ "start_block", "a02681.html#a74b1d75085d9f1ba313439ddbd9bc320", null ] ];
apache-2.0
JAVA201708/Homework
201711/20171103/Team1/ShenXingSheng/works/PetStore2/src/main/java/com/cheer/petstore/PetType.java
960
/** * */ package com.cheer.petstore; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * @author Cheer * @date 2017年10月25日 * @time 下午1:46:37 */ @Entity @Table(name = "tbl_pet_type") public class PetType { @Id @GeneratedValue(generator="uuid") @GenericGenerator(name="uuid", strategy="uuid") private String id; @Column private String name; /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } }
apache-2.0
vydra/cas
core/cas-server-core-tickets/src/test/java/org/apereo/cas/ticket/support/TicketGrantingTicketExpirationPolicyTests.java
3231
package org.apereo.cas.ticket.support; import org.apereo.cas.authentication.TestUtils; import org.apereo.cas.ticket.TicketGrantingTicket; import org.apereo.cas.ticket.TicketGrantingTicketImpl; import org.junit.Before; import org.junit.Test; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import static org.junit.Assert.*; /** * @author William G. Thompson, Jr. * @since 3.4.10 */ public class TicketGrantingTicketExpirationPolicyTests { private static final long HARD_TIMEOUT = 2; private static final long SLIDING_TIMEOUT = 2; private static final long TIMEOUT_BUFFER = 2; // needs to be long enough for timeouts to be triggered private TicketGrantingTicketExpirationPolicy expirationPolicy; private TicketGrantingTicket ticketGrantingTicket; @Before public void setUp() throws Exception { this.expirationPolicy = new TicketGrantingTicketExpirationPolicy(HARD_TIMEOUT, SLIDING_TIMEOUT); this.ticketGrantingTicket = new TicketGrantingTicketImpl("test", TestUtils.getAuthentication(), this.expirationPolicy); } @Test public void verifyTgtIsExpiredByHardTimeOut() throws InterruptedException { // keep tgt alive via sliding window until within SLIDING_TIME / 2 of the HARD_TIMEOUT final ZonedDateTime creationTime = ticketGrantingTicket.getCreationTime(); while (creationTime.plus(HARD_TIMEOUT - SLIDING_TIMEOUT / 2, ChronoUnit.SECONDS).isAfter(ZonedDateTime.now(ZoneOffset.UTC))) { ticketGrantingTicket.grantServiceTicket("test", org.apereo.cas.services.TestUtils.getService(), expirationPolicy, false, true); Thread.sleep((SLIDING_TIMEOUT - TIMEOUT_BUFFER) * 1_000); assertFalse(this.ticketGrantingTicket.isExpired()); } // final sliding window extension past the HARD_TIMEOUT ticketGrantingTicket.grantServiceTicket("test", org.apereo.cas.services.TestUtils.getService(), expirationPolicy, false, true); Thread.sleep((SLIDING_TIMEOUT / 2 + TIMEOUT_BUFFER) * 1_000); assertTrue(ticketGrantingTicket.isExpired()); } @Test public void verifyTgtIsExpiredBySlidingWindow() throws InterruptedException { ticketGrantingTicket.grantServiceTicket("test", org.apereo.cas.services.TestUtils.getService(), expirationPolicy, false, true); Thread.sleep((SLIDING_TIMEOUT - TIMEOUT_BUFFER) * 1_000); assertFalse(ticketGrantingTicket.isExpired()); ticketGrantingTicket.grantServiceTicket("test", org.apereo.cas.services.TestUtils.getService(), expirationPolicy, false, true); Thread.sleep((SLIDING_TIMEOUT - TIMEOUT_BUFFER) * 1_000); assertFalse(ticketGrantingTicket.isExpired()); ticketGrantingTicket.grantServiceTicket("test", org.apereo.cas.services.TestUtils.getService(), expirationPolicy, false, true); Thread.sleep((SLIDING_TIMEOUT + TIMEOUT_BUFFER) * 1_000); assertTrue(ticketGrantingTicket.isExpired()); } }
apache-2.0
begla/Intrinsic
IntrinsicRenderer/src/IntrinsicRendererResourcesPipelineLayout.cpp
10035
// Copyright 2017 Benjamin Glatzel // // 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. // Precompiled header files #include "stdafx.h" namespace Intrinsic { namespace Renderer { namespace Resources { void PipelineLayoutManager::createResources( const PipelineLayoutRefArray& p_PipelineLayouts) { for (uint32_t pplLayoutIdx = 0u; pplLayoutIdx < p_PipelineLayouts.size(); ++pplLayoutIdx) { PipelineLayoutRef ref = p_PipelineLayouts[pplLayoutIdx]; VkDescriptorSetLayout& descriptorSetLayout = _vkDescriptorSetLayout(ref); VkPipelineLayout& pipelineLayout = _vkPipelineLayout(ref); VkDescriptorPool& pool = _vkDescriptorPool(ref); _INTR_ARRAY(BindingDescription)& bindingInfos = _descBindingDescs(ref); _INTR_ARRAY(VkDescriptorSetLayoutBinding) layoutBindings; layoutBindings.resize(bindingInfos.size()); _INTR_ARRAY(VkDescriptorSetLayout) descSetLayouts; for (uint32_t biIdx = 0u; biIdx < bindingInfos.size(); ++biIdx) { BindingDescription& info = bindingInfos[biIdx]; layoutBindings[biIdx].binding = info.binding; layoutBindings[biIdx].descriptorType = Helper::mapBindingTypeToVkDescriptorType( (BindingType::Enum)info.bindingType); layoutBindings[biIdx].descriptorCount = 1u; layoutBindings[biIdx].stageFlags = Helper::mapGpuProgramTypeToVkShaderStage( (GpuProgramType::Enum)info.shaderStage); layoutBindings[biIdx].pImmutableSamplers = nullptr; } VkDescriptorSetLayoutCreateInfo descLayout = {}; { descLayout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descLayout.pNext = nullptr; descLayout.bindingCount = (uint32_t)layoutBindings.size(); descLayout.pBindings = layoutBindings.data(); VkResult result = vkCreateDescriptorSetLayout( RenderSystem::_vkDevice, &descLayout, nullptr, &descriptorSetLayout); _INTR_VK_CHECK_RESULT(result); descSetLayouts.push_back(descriptorSetLayout); } // Add global image descriptor set layouts descSetLayouts.push_back(ImageManager::_globalTextureDescriptorSetLayout); { VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {}; pPipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pPipelineLayoutCreateInfo.pNext = nullptr; pPipelineLayoutCreateInfo.pushConstantRangeCount = 0; pPipelineLayoutCreateInfo.pPushConstantRanges = nullptr; pPipelineLayoutCreateInfo.setLayoutCount = (uint32_t)descSetLayouts.size(); pPipelineLayoutCreateInfo.pSetLayouts = descSetLayouts.data(); VkResult result = vkCreatePipelineLayout(RenderSystem::_vkDevice, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout); _INTR_VK_CHECK_RESULT(result); } if (!bindingInfos.empty()) { _INTR_ARRAY(VkDescriptorPoolSize) poolSizes; poolSizes.resize(bindingInfos.size()); uint32_t maxPoolCount = 0u; for (uint32_t i = 0u; i < bindingInfos.size(); ++i) { BindingDescription& info = bindingInfos[i]; poolSizes[i].type = Helper::mapBindingTypeToVkDescriptorType( (BindingType::Enum)info.bindingType); poolSizes[i].descriptorCount = info.poolCount; maxPoolCount = std::max(maxPoolCount, info.poolCount); } VkDescriptorPoolCreateInfo descriptorPool = {}; descriptorPool.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; descriptorPool.pNext = nullptr; descriptorPool.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; descriptorPool.maxSets = maxPoolCount; descriptorPool.poolSizeCount = (uint32_t)poolSizes.size(); descriptorPool.pPoolSizes = poolSizes.data(); VkResult result = vkCreateDescriptorPool(RenderSystem::_vkDevice, &descriptorPool, nullptr, &pool); _INTR_VK_CHECK_RESULT(result); } } } // <- void PipelineLayoutManager::destroyResources( const PipelineLayoutRefArray& p_PipelineLayouts) { for (uint32_t i = 0u; i < p_PipelineLayouts.size(); ++i) { PipelineLayoutRef ref = p_PipelineLayouts[i]; VkPipelineLayout& pipelineLayout = _vkPipelineLayout(ref); if (pipelineLayout != VK_NULL_HANDLE) { vkDestroyPipelineLayout(RenderSystem::_vkDevice, pipelineLayout, nullptr); pipelineLayout = VK_NULL_HANDLE; } VkDescriptorSetLayout& descSetLayout = _vkDescriptorSetLayout(ref); if (descSetLayout != VK_NULL_HANDLE) { vkDestroyDescriptorSetLayout(RenderSystem::_vkDevice, descSetLayout, nullptr); descSetLayout = VK_NULL_HANDLE; } VkDescriptorPool& descPool = _vkDescriptorPool(ref); if (descPool != VK_NULL_HANDLE) { vkDestroyDescriptorPool(RenderSystem::_vkDevice, descPool, nullptr); descPool = VK_NULL_HANDLE; // Invalidate descriptor sets allocated from this pool for (uint32_t dcIdx = 0u; dcIdx < DrawCallManager::_activeRefs.size(); ++dcIdx) { DrawCallRef dcRef = DrawCallManager::_activeRefs[dcIdx]; PipelineRef pRef = DrawCallManager::_descPipeline(dcRef); if (pRef.isValid()) { PipelineLayoutRef plRef = PipelineManager::_descPipelineLayout(pRef); if (plRef == ref) { DrawCallManager::_vkDescriptorSet(dcRef) = nullptr; } } } } } } // <- VkDescriptorSet PipelineLayoutManager::allocateAndWriteDescriptorSet( PipelineLayoutRef p_Ref, const _INTR_ARRAY(BindingInfo) & p_BindInfos) { if (_vkDescriptorPool(p_Ref)) { VkDescriptorSetAllocateInfo allocInfo = {}; { allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.pNext = nullptr; allocInfo.descriptorPool = _vkDescriptorPool(p_Ref); allocInfo.descriptorSetCount = 1u; allocInfo.pSetLayouts = &_vkDescriptorSetLayout(p_Ref); } VkDescriptorSet descSet; VkResult result = vkAllocateDescriptorSets(RenderSystem::_vkDevice, &allocInfo, &descSet); _INTR_VK_CHECK_RESULT(result); _INTR_ARRAY(VkWriteDescriptorSet) writes; _INTR_ARRAY(VkDescriptorImageInfo) imageInfos; _INTR_ARRAY(VkDescriptorBufferInfo) bufferInfos; writes.resize(p_BindInfos.size()); imageInfos.resize(p_BindInfos.size()); bufferInfos.resize(p_BindInfos.size()); for (uint32_t i = 0u; i < p_BindInfos.size(); ++i) { const BindingInfo& info = p_BindInfos[i]; writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writes[i].pNext = nullptr; writes[i].dstSet = descSet; writes[i].descriptorCount = 1u; writes[i].descriptorType = Helper::mapBindingTypeToVkDescriptorType( (BindingType::Enum)info.bindingType); if (info.bindingType >= BindingType::kRangeStartBuffer && info.bindingType <= BindingType::kRangeEndBuffer) { VkDescriptorBufferInfo& bufferInfo = bufferInfos[i]; bufferInfo.buffer = Resources::BufferManager::_vkBuffer(info.resource); bufferInfo.offset = 0u; bufferInfo.range = info.bufferData.rangeInBytes; writes[i].pBufferInfo = &bufferInfo; } else if (info.bindingType >= BindingType::kRangeStartImage && info.bindingType <= BindingType::kRangeEndImage) { VkDescriptorImageInfo& imageInfo = imageInfos[i]; if (info.bindingType == BindingType::kImageAndSamplerCombined || info.bindingType == BindingType::kStorageImage || info.bindingType == BindingType::kSampledImage) { if ((info.bindingFlags & BindingFlags::kAdressSubResource) == 0u) { if ((info.bindingFlags & BindingFlags::kForceGammaSampling) > 0u) { imageInfo.imageView = Resources::ImageManager::_vkImageViewGamma(info.resource); } else if ((info.bindingFlags & BindingFlags::kForceLinearSampling) > 0u) { imageInfo.imageView = Resources::ImageManager::_vkImageViewLinear(info.resource); } else { imageInfo.imageView = Resources::ImageManager::_vkImageView(info.resource); } } else { imageInfo.imageView = Resources::ImageManager::_vkSubResourceImageView( info.resource, info.imageData.arrayLayerIdx, info.imageData.mipLevelIdx); } imageInfo.imageLayout = info.bindingType != BindingType::kStorageImage ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL; } if (info.bindingType == BindingType::kImageAndSamplerCombined || info.bindingType == BindingType::kSampler) { imageInfo.sampler = Samplers::samplers[info.imageData.samplerIdx]; } writes[i].pImageInfo = &imageInfo; } writes[i].dstArrayElement = 0u; writes[i].dstBinding = info.binding; } vkUpdateDescriptorSets(RenderSystem::_vkDevice, (uint32_t)writes.size(), writes.data(), 0u, nullptr); return descSet; } return VK_NULL_HANDLE; } } } }
apache-2.0
bitmonk/chef-freeswitch
recipes/setup_env.rb
4276
# # Cookbook Name:: freeswitch # Recipe:: install-source # # Author:: Justin Alan Ryan (<bitmonk@bitmonk.net>) # # Copyright 2013, Justin Alan Ryan # # 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. # fsbase = node[:freeswitch][:base_dir] fsinst = node[:freeswitch][:install_dir] fssrc = node[:freeswitch][:src_dir] directory 'create_freeswitch_base' do path fsbase mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_conf' do path "#{fsbase}/conf/" # use path joining methods mode '0700' owner :freeswitch group :freeswitch end template 'fs_conf_freeswitch_xml' do path "#{fsbase}/conf/freeswitch.xml" source 'freeswitch.xml.erb' end directory 'create_freeswitch_directories_parent' do path "#{fsbase}/conf/directory/" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customers_data_dir' do path "#{fsbase}/customers/" mode '0700' owner :freeswitch group :freeswitch end search(:freeswitch_customers, "*:*").each do |customer| cust_data_dir = "#{fsbase}/customers/#{customer.hostname}" cust_conf_dir = "#{fsbase}/customers/#{customer.hostname}" directory 'create_freeswitch_customer_conf_dir' do path cust_conf_dir mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_data_dir' do path cust_data_dir mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_dialplan_default_dir' do path "#{cust_data_dir}/dialplan/ivr" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_dialplan_dialplan_dir' do path "#{cust_data_dir}/dialplan/dialplan" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_dialplan_ivr_dir' do path "#{cust_data_dir}/dialplan/ivr" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_dialplan_public_dir' do path "#{cust_data_dir}/dialplan/public" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_dialplan_dir' do path "#{cust_data_dir}/dialplan" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_directory_dir' do path "#{cust_data_dir}/directory" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_ivr_dir' do path "#{cust_data_dir}/ivr" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_recordings_dir' do path "#{cust_data_dir}/recordings" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_scripts_dir' do path "#{cust_data_dir}/scripts" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_sounds_dir' do path "#{cust_data_dir}/sounds" mode '0700' owner :freeswitch group :freeswitch end directory 'create_freeswitch_customer_voicemail_dir' do path "#{cust_data_dir}/voicemail" mode '0700' owner :freeswitch group :freeswitch end customer[:extensions].each do |extension| template "create_freeswitch_customer_extension_#{extension.number}@#{customer.hostname}" do path "#{fsbase}/conf/directory/#{customer.hostname}/#{extension.number}.xml" source 'freeswitch_customer_extension.xml.erb' mode '0700' owner :freeswitch group :freeswitch variables({ :extension => extension[:number], :customer_hostname => customer[:hostname] }) end end end
apache-2.0
facebook/fbthrift
thrift/perf/cpp2/util/Util.cpp
1380
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/perf/cpp2/util/Util.h> namespace apache { namespace thrift { namespace perf { folly::AsyncSocket::UniquePtr getSocket( folly::EventBase* evb, folly::SocketAddress const& addr, bool encrypted, std::list<std::string> advertizedProtocols) { folly::AsyncSocket::UniquePtr sock(new folly::AsyncSocket(evb, addr)); if (encrypted) { auto sslContext = std::make_shared<folly::SSLContext>(); sslContext->setAdvertisedNextProtocols(advertizedProtocols); auto sslSock = new TAsyncSSLSocket( sslContext, evb, sock->detachNetworkSocket(), false); sslSock->sslConn(nullptr); sock.reset(sslSock); } sock->setZeroCopy(true); return sock; } } // namespace perf } // namespace thrift } // namespace apache
apache-2.0
vjanmey/EpicMudfia
com/planet_ink/coffee_mud/WebMacros/PollID.java
1957
package com.planet_ink.coffee_mud.WebMacros; import com.planet_ink.miniweb.interfaces.*; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.net.URLEncoder; import java.util.*; /* Copyright 2000-2014 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class PollID extends StdWebMacro { @Override public String name() { return "PollID"; } @Override public String runMacro(HTTPRequest httpReq, String parm) { final String last=httpReq.getUrlParameter("POLL"); if(last==null) return " @break@"; final java.util.Map<String,String> parms=parseParms(parm); try { if(parms.containsKey("ENCODED")) return URLEncoder.encode(last,"UTF-8"); } catch(final Exception e) {} return clearWebMacros(last); } }
apache-2.0
haakom/EnergiWeb-remake
energiweb/src/no/noen/server/commond/SMS.java
6513
package no.noen.server.commond; import java.io.*; import java.net.InetAddress; import java.net.Socket; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.komsa.domain.StringUtils; import org.komsa.log.LogWriter; import org.w3c.dom.*; import org.xml.sax.InputSource; /** * SMS communicator. */ public class SMS { /** * Send SMS messages to a list of receivers. * @param sender Message sender * @param rcvList List of receivers (phonenr) * @param message Message to send * @return Map of response text for each receiver */ public static Map<String,String> send(String sender, Set<String> rcvList, String message) { SMS inst = new SMS(); return inst.doSend(sender, rcvList, message); } /** * Send SMS messages to a list of receivers. * @param sender Message sender * @param rcvList List of receivers (phonenr) * @param message Message to send * @return Map of response text for each receiver */ public Map<String,String> doSend(String sender, Set<String> rcvList, String message) { // NB! Midlertidlig løsning pga tidsnød StringBuilder xmlMsg = new StringBuilder(); xmlMsg.append("<?xml version=\"1.0\"?>\n") .append("<!DOCTYPE SESSION SYSTEM \"pswincom_submit_response.dtd\">\n") .append("<SESSION>\n<CLIENT>noen</CLIENT>\n<PW>dKr7gA9</PW>\n") .append("<MSGLST>\n"); int itemCount = 1; Map<Integer,String> statusMap = new HashMap<Integer,String>(); String strMsg = StringUtils.replaceString(message, "<", "&lt;"); strMsg = StringUtils.replaceString(strMsg, ">", "&gt;"); for (Iterator<String> it = rcvList.iterator(); it.hasNext(); itemCount++) { String strRcv = it.next(); statusMap.put(new Integer(itemCount), ""); xmlMsg.append("<MSG>\n") .append("<TEXT>").append(strMsg).append("</TEXT>\n") .append("<SND>").append(sender).append("</SND>\n") .append("<RCV>47").append(strRcv).append("</RCV>\n") .append("</MSG>\n"); } xmlMsg.append("</MSGLST>\n</SESSION>\n"); try { InetAddress addr = InetAddress.getByName("sms.pswin.com"); Socket socket = new Socket(addr, 1111); OutputStream out = socket.getOutputStream(); //LogWriter.ilog("SMS send: " + xmlMsg.toString()); out.write(xmlMsg.toString().getBytes("ISO-8859-1")); out.flush(); //LogWriter.ilog("SMS read response"); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); StringBuilder buf = new StringBuilder(); String strLine = br.readLine(); while (strLine != null) { if (strLine.length() > 1) buf.append(strLine).append("\n"); strLine = br.readLine(); } br.close(); socket.close(); // Parse and set response text //LogWriter.ilog("SMS response: " + buf.toString()); if (buf.length() > 0) parseResponse(buf.toString(), statusMap); } catch (Exception ex) { LogWriter.elog(ex, "SMS"); itemCount = 1; for (Iterator it = rcvList.iterator(); it.hasNext(); itemCount++) statusMap.put(new Integer(itemCount), ex.getMessage()); } itemCount = 1; Map<String,String> respMap = new HashMap<String,String>(); Iterator<String> it = rcvList.iterator(); for (; it.hasNext(); itemCount++) { String strRcv = it.next(); String strStat = statusMap.get(new Integer(itemCount)); respMap.put(strRcv, strStat); //LogWriter.ilog("SMS: " + strRcv + "=" + strStat); } return respMap; } /** * Parse response. */ private void parseResponse(String xmlResp, Map<Integer,String> respMap) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new InputSource(new StringReader(xmlResp))); Element root = doc.getDocumentElement(); NodeList nodes = root.getElementsByTagName("LOGON"); if (nodes.getLength() != 1) throw new Exception("Invalid response"); nodes = root.getElementsByTagName("MSGLST"); if (nodes.getLength() != 1) throw new Exception("Invalid response (msglist missing)"); Element element = (Element)nodes.item(0); NodeList m_nodes = element.getElementsByTagName("MSG"); for (int i = 0; i < m_nodes.getLength(); i++) { Node node = m_nodes.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element elem = (Element)node; String strStatus = getSubElementValue("STATUS", elem); respMap.put(new Integer(i+1), strStatus); } } catch (Exception ex) { LogWriter.ilog("SMS response: " + xmlResp); LogWriter.elog(ex, "SMS.parseResponse"); } } /** * Get value of a specific sub-element for an element. */ private String getSubElementValue(String elementName, Element root) { String elemValue = null; NodeList nodes = root.getElementsByTagName(elementName); if (nodes.getLength() == 1) { Node node = nodes.item(0); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element)node; if (element.getFirstChild() != null) elemValue = element.getFirstChild().getNodeValue(); } } return elemValue; } /*public static void main(String[] args) { java.util.Set list = new java.util.HashSet(); list.add("91556025"); list.add("95273584"); list.add("99710038"); SMS.send("K2", list, "Test 2"); }*/ }
apache-2.0
tribou/react-template
webpack.config.js
290
// @flow const { NODE_ENV } = process.env; if (NODE_ENV !== "development" && NODE_ENV !== "production") { process.env.NODE_ENV = "production"; } const browser = require("./config/webpack/browser"); const server = require("./config/webpack/server"); module.exports = [browser, server];
apache-2.0
awsdocs/aws-doc-sdk-examples
javascript/example_code/iam/iam_createpolicy.js
2318
/** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is 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/ * * 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. * */ //snippet-sourcedescription:[iam_createpolicy.js demonstrates how to create a managed policy for an AWS account.] //snippet-keyword:[JavaScript] //snippet-sourcesyntax:[javascript] //snippet-keyword:[Code Sample] //snippet-keyword:[AWS Identity and Access Management (IAM)] //snippet-service:[iam] //snippet-sourcetype:[full-example] //snippet-sourcedate:[2018-06-02] //snippet-sourceauthor:[AWS-JSDG] // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html // snippet-start:[iam.JavaScript.policies.createPolicy] // Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create the IAM service object var iam = new AWS.IAM({apiVersion: '2010-05-08'}); var myManagedPolicy = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "logs:CreateLogGroup", "Resource": "RESOURCE_ARN" }, { "Effect": "Allow", "Action": [ "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Scan", "dynamodb:UpdateItem" ], "Resource": "RESOURCE_ARN" } ] }; var params = { PolicyDocument: JSON.stringify(myManagedPolicy), PolicyName: 'myDynamoDBPolicy', }; iam.createPolicy(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } }); // snippet-end:[iam.JavaScript.policies.createPolicy]
apache-2.0
GoogleForCreators/web-stories-wp
packages/e2e-test-utils/src/index.js
3398
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ export { default as createNewStory } from './createNewStory'; export { default as previewStory } from './previewStory'; export { default as visitDashboard } from './visitDashboard'; export { default as visitSettings } from './visitSettings'; export { default as addRequestInterception } from './addRequestInterception'; export { default as withExperimentalFeatures } from './experimentalFeatures'; export { default as withDisabledToolbarOnFrontend } from './toolbarProfileOption'; export { default as withUser } from './withUser'; export { default as withPlugin } from './withPlugin'; export { default as withRTL } from './withRTL'; export { default as deactivateRTL } from './deactivateRTL'; export { default as activateRTL } from './activateRTL'; export { default as publishPost } from './publishPost'; export { default as publishStory } from './publishStory'; export { default as addTextElement } from './addTextElement'; export { default as insertStoryTitle } from './insertStoryTitle'; export { default as setAnalyticsCode } from './setAnalyticsCode'; export { default as clickButton } from './clickButton'; export { default as uploadFile } from './uploadFile'; export { default as uploadMedia } from './uploadMedia'; export { default as uploadPublisherLogo } from './uploadPublisherLogo'; export { default as toggleVideoOptimization } from './toggleVideoOptimization'; export { default as deleteMedia } from './deleteMedia'; export { default as deleteAllMedia } from './deleteAllMedia'; export { default as deleteWidgets } from './deleteWidgets'; export { default as getFileName } from './getFileName'; export { default as trashAllPosts } from './trashAllPosts'; export { default as trashAllTerms } from './trashAllTerms'; export { default as visitAdminPage } from './visitAdminPage'; export { setCurrentUser, getCurrentUser } from './user'; export { default as activatePlugin } from './activatePlugin'; export { default as deactivatePlugin } from './deactivatePlugin'; export { default as createNewPost } from './createNewPost'; export { default as minWPVersionRequired } from './minWPVersionRequired'; export { default as visitBlockWidgetScreen } from './visitBlockWidgetScreen'; export { default as insertWidget } from './insertWidget'; export { default as triggerHighPriorityChecklistSection } from './triggerHighPriorityChecklistSection'; export { default as disableCheckbox } from './disableCheckbox'; export { default as enableCheckbox } from './enableCheckbox'; export { default as takeSnapshot } from './takeSnapshot'; export { default as uploadPublisherLogoEditor } from './uploadPublisherLogoEditor'; export { getEditedPostContent, setPostContent, enablePageDialogAccept, setBrowserViewport, insertBlock, createURL, clearLocalStorage, } from '@wordpress/e2e-test-utils';
apache-2.0
FederatedAI/FATE
python/fate_arch/storage/hive/__init__.py
159
from fate_arch.storage.hive._table import StorageTable from fate_arch.storage.hive._session import StorageSession __all__ = ["StorageTable", "StorageSession"]
apache-2.0
mymuyi/coolweather
app/src/main/java/com/example/coolweather/gson/AQI.java
179
package com.example.coolweather.gson; public class AQI { public AQICity city; public class AQICity { public String aqi; public String pm25; } }
apache-2.0
googleads/google-ads-python
google/ads/googleads/v7/services/services/feed_mapping_service/client.py
22895
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from collections import OrderedDict from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.ads.googleads.v7.resources.types import feed_mapping from google.ads.googleads.v7.services.types import feed_mapping_service from google.rpc import status_pb2 as status # type: ignore from .transports.base import FeedMappingServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import FeedMappingServiceGrpcTransport class FeedMappingServiceClientMeta(type): """Metaclass for the FeedMappingService client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[FeedMappingServiceTransport]] _transport_registry["grpc"] = FeedMappingServiceGrpcTransport def get_transport_class( cls, label: str = None, ) -> Type[FeedMappingServiceTransport]: """Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class FeedMappingServiceClient(metaclass=FeedMappingServiceClientMeta): """Service to manage feed mappings.""" @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") DEFAULT_ENDPOINT = "googleads.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: FeedMappingServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_info( info ) kwargs["credentials"] = credentials return cls(*args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: FeedMappingServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename ) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @property def transport(self) -> FeedMappingServiceTransport: """Return the transport used by the client instance. Returns: FeedMappingServiceTransport: The transport used by the client instance. """ return self._transport @staticmethod def feed_path(customer_id: str, feed_id: str,) -> str: """Return a fully-qualified feed string.""" return "customers/{customer_id}/feeds/{feed_id}".format( customer_id=customer_id, feed_id=feed_id, ) @staticmethod def parse_feed_path(path: str) -> Dict[str, str]: """Parse a feed path into its component segments.""" m = re.match( r"^customers/(?P<customer_id>.+?)/feeds/(?P<feed_id>.+?)$", path ) return m.groupdict() if m else {} @staticmethod def feed_mapping_path( customer_id: str, feed_id: str, feed_mapping_id: str, ) -> str: """Return a fully-qualified feed_mapping string.""" return "customers/{customer_id}/feedMappings/{feed_id}~{feed_mapping_id}".format( customer_id=customer_id, feed_id=feed_id, feed_mapping_id=feed_mapping_id, ) @staticmethod def parse_feed_mapping_path(path: str) -> Dict[str, str]: """Parse a feed_mapping path into its component segments.""" m = re.match( r"^customers/(?P<customer_id>.+?)/feedMappings/(?P<feed_id>.+?)~(?P<feed_mapping_id>.+?)$", path, ) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str,) -> str: """Return a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @staticmethod def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_folder_path(folder: str,) -> str: """Return a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P<folder>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_organization_path(organization: str,) -> str: """Return a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P<organization>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_project_path(project: str,) -> str: """Return a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_location_path(project: str, location: str,) -> str: """Return a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @staticmethod def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match( r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path ) return m.groupdict() if m else {} def __init__( self, *, credentials: Optional[credentials.Credentials] = None, transport: Union[str, FeedMappingServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the feed mapping service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.FeedMappingServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. use_client_cert = bool( util.strtobool( os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") ) ) ssl_credentials = None is_mtls = False if use_client_cert: if client_options.client_cert_source: import grpc # type: ignore cert, key = client_options.client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) is_mtls = True else: creds = SslCredentials() is_mtls = creds.is_mtls ssl_credentials = creds.ssl_credentials if is_mtls else None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint else: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": api_endpoint = ( self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, FeedMappingServiceTransport): # transport is a FeedMappingServiceTransport instance. if credentials: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) self._transport = transport elif isinstance(transport, str): Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, host=self.DEFAULT_ENDPOINT ) else: self._transport = FeedMappingServiceGrpcTransport( credentials=credentials, host=api_endpoint, ssl_channel_credentials=ssl_credentials, client_info=client_info, ) def get_feed_mapping( self, request: feed_mapping_service.GetFeedMappingRequest = None, *, resource_name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> feed_mapping.FeedMapping: r"""Returns the requested feed mapping in full detail. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `RequestError <>`__ Args: request (:class:`google.ads.googleads.v7.services.types.GetFeedMappingRequest`): The request object. Request message for [FeedMappingService.GetFeedMapping][google.ads.googleads.v7.services.FeedMappingService.GetFeedMapping]. resource_name (:class:`str`): Required. The resource name of the feed mapping to fetch. This corresponds to the ``resource_name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v7.resources.types.FeedMapping: A feed mapping. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([resource_name]): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a feed_mapping_service.GetFeedMappingRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, feed_mapping_service.GetFeedMappingRequest): request = feed_mapping_service.GetFeedMappingRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if resource_name is not None: request.resource_name = resource_name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.get_feed_mapping] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( (("resource_name", request.resource_name),) ), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response def mutate_feed_mappings( self, request: feed_mapping_service.MutateFeedMappingsRequest = None, *, customer_id: str = None, operations: Sequence[feed_mapping_service.FeedMappingOperation] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> feed_mapping_service.MutateFeedMappingsResponse: r"""Creates or removes feed mappings. Operation statuses are returned. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `DatabaseError <>`__ `DistinctError <>`__ `FeedMappingError <>`__ `FieldError <>`__ `HeaderError <>`__ `IdError <>`__ `InternalError <>`__ `MutateError <>`__ `NotEmptyError <>`__ `OperationAccessDeniedError <>`__ `OperatorError <>`__ `QuotaError <>`__ `RangeError <>`__ `RequestError <>`__ `SizeLimitError <>`__ `StringFormatError <>`__ `StringLengthError <>`__ Args: request (:class:`google.ads.googleads.v7.services.types.MutateFeedMappingsRequest`): The request object. Request message for [FeedMappingService.MutateFeedMappings][google.ads.googleads.v7.services.FeedMappingService.MutateFeedMappings]. customer_id (:class:`str`): Required. The ID of the customer whose feed mappings are being modified. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. operations (:class:`Sequence[google.ads.googleads.v7.services.types.FeedMappingOperation]`): Required. The list of operations to perform on individual feed mappings. This corresponds to the ``operations`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v7.services.types.MutateFeedMappingsResponse: Response message for a feed mapping mutate. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([customer_id, operations]): raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a feed_mapping_service.MutateFeedMappingsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance( request, feed_mapping_service.MutateFeedMappingsRequest ): request = feed_mapping_service.MutateFeedMappingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if customer_id is not None: request.customer_id = customer_id if operations is not None: request.operations = operations # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ self._transport.mutate_feed_mappings ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( (("customer_id", request.customer_id),) ), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response __all__ = ("FeedMappingServiceClient",)
apache-2.0
freedomtan/tensorflow
tensorflow/lite/micro/micro_interpreter.cc
17117
/* Copyright 2020 The TensorFlow 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. ==============================================================================*/ #include "tensorflow/lite/micro/micro_interpreter.h" #include <cstdarg> #include <cstddef> #include <cstdint> #include "flatbuffers/flatbuffers.h" // from @flatbuffers #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/core/api/error_reporter.h" #include "tensorflow/lite/core/api/tensor_utils.h" #include "tensorflow/lite/micro/memory_helpers.h" #include "tensorflow/lite/micro/micro_allocator.h" #include "tensorflow/lite/micro/micro_op_resolver.h" #include "tensorflow/lite/micro/micro_profiler.h" #include "tensorflow/lite/schema/schema_generated.h" namespace tflite { namespace { #ifndef TF_LITE_STRIP_ERROR_STRINGS const char* OpNameFromRegistration(const TfLiteRegistration* registration) { if (registration->builtin_code == BuiltinOperator_CUSTOM) { return registration->custom_name; } else { return EnumNameBuiltinOperator(BuiltinOperator(registration->builtin_code)); } } #endif // !defined(TF_LITE_STRIP_ERROR_STRINGS) } // namespace namespace internal { ContextHelper::ContextHelper(ErrorReporter* error_reporter, MicroAllocator* allocator, const Model* model) : allocator_(allocator), error_reporter_(error_reporter), model_(model) {} void* ContextHelper::AllocatePersistentBuffer(TfLiteContext* ctx, size_t bytes) { return reinterpret_cast<ContextHelper*>(ctx->impl_) ->allocator_->AllocatePersistentBuffer(bytes); } TfLiteStatus ContextHelper::RequestScratchBufferInArena(TfLiteContext* ctx, size_t bytes, int* buffer_idx) { ContextHelper* helper = reinterpret_cast<ContextHelper*>(ctx->impl_); return helper->allocator_->RequestScratchBufferInArena(bytes, buffer_idx); } void* ContextHelper::GetScratchBuffer(TfLiteContext* ctx, int buffer_idx) { ContextHelper* helper = reinterpret_cast<ContextHelper*>(ctx->impl_); ScratchBufferHandle* handle = helper->scratch_buffer_handles_ + buffer_idx; return handle->data; } void ContextHelper::ReportOpError(struct TfLiteContext* context, const char* format, ...) { #ifndef TF_LITE_STRIP_ERROR_STRINGS ContextHelper* helper = static_cast<ContextHelper*>(context->impl_); va_list args; va_start(args, format); TF_LITE_REPORT_ERROR(helper->error_reporter_, format, args); va_end(args); #endif } TfLiteTensor* ContextHelper::GetTensor(const struct TfLiteContext* context, int tensor_idx) { ContextHelper* helper = static_cast<ContextHelper*>(context->impl_); return helper->allocator_->AllocateTempTfLiteTensor( helper->model_, helper->eval_tensors_, tensor_idx); } TfLiteEvalTensor* ContextHelper::GetEvalTensor( const struct TfLiteContext* context, int tensor_idx) { ContextHelper* helper = reinterpret_cast<ContextHelper*>(context->impl_); return &helper->eval_tensors_[tensor_idx]; } void ContextHelper::SetTfLiteEvalTensors(TfLiteEvalTensor* eval_tensors) { eval_tensors_ = eval_tensors; } void ContextHelper::SetScratchBufferHandles( ScratchBufferHandle* scratch_buffer_handles) { scratch_buffer_handles_ = scratch_buffer_handles; } } // namespace internal MicroInterpreter::MicroInterpreter(const Model* model, const MicroOpResolver& op_resolver, uint8_t* tensor_arena, size_t tensor_arena_size, ErrorReporter* error_reporter, tflite::Profiler* profiler) : model_(model), op_resolver_(op_resolver), error_reporter_(error_reporter), allocator_(*MicroAllocator::Create(tensor_arena, tensor_arena_size, error_reporter)), tensors_allocated_(false), initialization_status_(kTfLiteError), eval_tensors_(nullptr), context_helper_(error_reporter_, &allocator_, model), input_tensor_(nullptr), output_tensor_(nullptr) { Init(profiler); } MicroInterpreter::MicroInterpreter(const Model* model, const MicroOpResolver& op_resolver, MicroAllocator* allocator, ErrorReporter* error_reporter, tflite::Profiler* profiler) : model_(model), op_resolver_(op_resolver), error_reporter_(error_reporter), allocator_(*allocator), tensors_allocated_(false), initialization_status_(kTfLiteError), eval_tensors_(nullptr), context_helper_(error_reporter_, &allocator_, model), input_tensor_(nullptr), output_tensor_(nullptr) { Init(profiler); } MicroInterpreter::~MicroInterpreter() { if (node_and_registrations_ != nullptr) { for (size_t i = 0; i < subgraph_->operators()->size(); ++i) { TfLiteNode* node = &(node_and_registrations_[i].node); const TfLiteRegistration* registration = node_and_registrations_[i].registration; // registration is allocated outside the interpreter, so double check to // make sure it's not nullptr; if (registration != nullptr && registration->free != nullptr) { registration->free(&context_, node->user_data); } } } } void MicroInterpreter::Init(tflite::Profiler* profiler) { const flatbuffers::Vector<flatbuffers::Offset<SubGraph>>* subgraphs = model_->subgraphs(); if (subgraphs->size() != 1) { TF_LITE_REPORT_ERROR(error_reporter_, "Only 1 subgraph is currently supported.\n"); initialization_status_ = kTfLiteError; return; } subgraph_ = (*subgraphs)[0]; context_.impl_ = static_cast<void*>(&context_helper_); context_.ReportError = context_helper_.ReportOpError; context_.GetTensor = context_helper_.GetTensor; context_.GetEvalTensor = context_helper_.GetEvalTensor; context_.recommended_num_threads = 1; context_.profiler = profiler; initialization_status_ = kTfLiteOk; } void MicroInterpreter::CorrectTensorEndianness(TfLiteEvalTensor* tensorCorr) { int32_t tensorSize = 1; for (int d = 0; d < tensorCorr->dims->size; ++d) tensorSize *= reinterpret_cast<const int32_t*>(tensorCorr->dims->data)[d]; switch (tensorCorr->type) { case TfLiteType::kTfLiteFloat32: CorrectTensorDataEndianness(tensorCorr->data.f, tensorSize); break; case TfLiteType::kTfLiteFloat16: CorrectTensorDataEndianness(tensorCorr->data.f16, tensorSize); break; case TfLiteType::kTfLiteInt64: CorrectTensorDataEndianness(tensorCorr->data.i64, tensorSize); break; case TfLiteType::kTfLiteUInt64: CorrectTensorDataEndianness(tensorCorr->data.u64, tensorSize); break; case TfLiteType::kTfLiteInt32: CorrectTensorDataEndianness(tensorCorr->data.i32, tensorSize); break; case TfLiteType::kTfLiteInt16: CorrectTensorDataEndianness(tensorCorr->data.i16, tensorSize); break; case TfLiteType::kTfLiteComplex64: CorrectTensorDataEndianness(tensorCorr->data.c64, tensorSize); break; case TfLiteType::kTfLiteComplex128: CorrectTensorDataEndianness(tensorCorr->data.c128, tensorSize); break; default: // Do nothing for other data types. break; } } template <class T> void MicroInterpreter::CorrectTensorDataEndianness(T* data, int32_t size) { for (int32_t i = 0; i < size; ++i) { data[i] = flatbuffers::EndianScalar(data[i]); } } TfLiteStatus MicroInterpreter::AllocateTensors() { if (allocator_.StartModelAllocation(model_, op_resolver_, &node_and_registrations_, &eval_tensors_) != kTfLiteOk) { TF_LITE_REPORT_ERROR(error_reporter_, "Failed starting model allocation.\n"); initialization_status_ = kTfLiteError; return kTfLiteError; } // Update the pointer now that TfLiteEvalTensor allocation has completed on // the context helper. // TODO(b/16157777): This call would not be needed if ContextHelper rolled // into the interpreter. context_helper_.SetTfLiteEvalTensors(eval_tensors_); context_.tensors_size = subgraph_->tensors()->size(); // If the system is big endian then convert weights from the flatbuffer from // little to big endian on startup so that it does not need to be done during // inference. // NOTE: This requires that the flatbuffer is held in memory which can be // modified by this process. if (!FLATBUFFERS_LITTLEENDIAN) { for (size_t t = 0; t < subgraph_->tensors()->size(); ++t) { if (auto* buffer = (*model_->buffers())[subgraph_->tensors()->Get(t)->buffer()]) { // If we've found a buffer, does it have any data? if (auto* array = buffer->data()) { // If it has any data, is the data size larger than zero? if (array->size()) { // Update the endianness of the corresponding eval tensor since that // struct holds the buffer used at inference time. CorrectTensorEndianness(&eval_tensors_[t]); } } } } } // Only allow AllocatePersistentBuffer in Init stage. context_.AllocatePersistentBuffer = context_helper_.AllocatePersistentBuffer; context_.RequestScratchBufferInArena = nullptr; context_.GetScratchBuffer = nullptr; for (size_t i = 0; i < subgraph_->operators()->size(); ++i) { auto* node = &(node_and_registrations_[i].node); auto* registration = node_and_registrations_[i].registration; size_t init_data_size; const char* init_data; if (registration->builtin_code == BuiltinOperator_CUSTOM) { init_data = reinterpret_cast<const char*>(node->custom_initial_data); init_data_size = node->custom_initial_data_size; } else { init_data = reinterpret_cast<const char*>(node->builtin_data); init_data_size = 0; } if (registration->init) { node->user_data = registration->init(&context_, init_data, init_data_size); } } // Both AllocatePersistentBuffer and RequestScratchBufferInArena is // available in Prepare stage. context_.RequestScratchBufferInArena = context_helper_.RequestScratchBufferInArena; for (size_t i = 0; i < subgraph_->operators()->size(); ++i) { auto* node = &(node_and_registrations_[i].node); auto* registration = node_and_registrations_[i].registration; if (registration->prepare) { TfLiteStatus prepare_status = registration->prepare(&context_, node); if (prepare_status != kTfLiteOk) { TF_LITE_REPORT_ERROR( error_reporter_, "Node %s (number %df) failed to prepare with status %d", OpNameFromRegistration(registration), i, prepare_status); return kTfLiteError; } } allocator_.FinishPrepareNodeAllocations(/*node_id=*/i); } // Prepare is done, we're ready for Invoke. Memory allocation is no longer // allowed. Kernels can only fetch scratch buffers via GetScratchBuffer. context_.AllocatePersistentBuffer = nullptr; context_.RequestScratchBufferInArena = nullptr; context_.GetScratchBuffer = context_helper_.GetScratchBuffer; TF_LITE_ENSURE_OK(&context_, allocator_.FinishModelAllocation(model_, eval_tensors_, &scratch_buffer_handles_)); // TODO(b/16157777): Remove this when ContextHelper is rolled into this class. context_helper_.SetScratchBufferHandles(scratch_buffer_handles_); TF_LITE_ENSURE_STATUS(ResetVariableTensors()); tensors_allocated_ = true; return kTfLiteOk; } TfLiteStatus MicroInterpreter::Invoke() { if (initialization_status_ != kTfLiteOk) { TF_LITE_REPORT_ERROR(error_reporter_, "Invoke() called after initialization failed\n"); return kTfLiteError; } // Ensure tensors are allocated before the interpreter is invoked to avoid // difficult to debug segfaults. if (!tensors_allocated_) { TF_LITE_ENSURE_OK(&context_, AllocateTensors()); } for (size_t i = 0; i < subgraph_->operators()->size(); ++i) { auto* node = &(node_and_registrations_[i].node); auto* registration = node_and_registrations_[i].registration; if (registration->invoke) { TfLiteStatus invoke_status; #ifndef NDEBUG // Omit profiler overhead from release builds. // The case where profiler == nullptr is handled by // ScopedOperatorProfile. tflite::Profiler* profiler = reinterpret_cast<tflite::Profiler*>(context_.profiler); ScopedOperatorProfile scoped_profiler( profiler, OpNameFromRegistration(registration), i); #endif invoke_status = registration->invoke(&context_, node); // All TfLiteTensor structs used in the kernel are allocated from temp // memory in the allocator. This creates a chain of allocations in the // temp section. The call below resets the chain of allocations to // prepare for the next call. allocator_.ResetTempAllocations(); if (invoke_status == kTfLiteError) { TF_LITE_REPORT_ERROR( error_reporter_, "Node %s (number %d) failed to invoke with status %d", OpNameFromRegistration(registration), i, invoke_status); return kTfLiteError; } else if (invoke_status != kTfLiteOk) { return invoke_status; } } } return kTfLiteOk; } TfLiteTensor* MicroInterpreter::input(size_t index) { const size_t length = inputs_size(); if (index >= length) { TF_LITE_REPORT_ERROR(error_reporter_, "Input index %d out of range (length is %d)", index, length); return nullptr; } if (index != 0) { TF_LITE_REPORT_ERROR( error_reporter_, "Input tensors not at index 0 are allocated from the " "persistent memory arena. Repeat calls will cause excess " "allocation!"); return allocator_.AllocatePersistentTfLiteTensor(model_, eval_tensors_, inputs().Get(index)); } if (input_tensor_ == nullptr) { input_tensor_ = allocator_.AllocatePersistentTfLiteTensor( model_, eval_tensors_, inputs().Get(index)); } return input_tensor_; } TfLiteTensor* MicroInterpreter::output(size_t index) { const size_t length = outputs_size(); if (index >= length) { TF_LITE_REPORT_ERROR(error_reporter_, "Output index %d out of range (length is %d)", index, length); return nullptr; } if (index != 0) { TF_LITE_REPORT_ERROR( error_reporter_, "Output tensors not at index 0 are allocated from the " "persistent memory arena. Repeat calls will cause excess " "allocation!"); return allocator_.AllocatePersistentTfLiteTensor(model_, eval_tensors_, outputs().Get(index)); } if (output_tensor_ == nullptr) { // TODO(b/162311891): Drop these allocations when the interpreter supports // handling buffers from TfLiteEvalTensor. output_tensor_ = allocator_.AllocatePersistentTfLiteTensor( model_, eval_tensors_, outputs().Get(index)); } return output_tensor_; } TfLiteTensor* MicroInterpreter::tensor(size_t index) { const size_t length = tensors_size(); if (index >= length) { TF_LITE_REPORT_ERROR(error_reporter_, "Tensor index %d out of range (length is %d)", index, length); return nullptr; } return allocator_.AllocatePersistentTfLiteTensor(model_, eval_tensors_, index); } TfLiteStatus MicroInterpreter::ResetVariableTensors() { for (size_t i = 0; i < subgraph_->tensors()->size(); ++i) { auto* tensor = subgraph_->tensors()->Get(i); if (tensor->is_variable()) { size_t buffer_size; TF_LITE_ENSURE_STATUS( TfLiteEvalTensorByteLength(&eval_tensors_[i], &buffer_size)); int value = 0; if (tensor->type() == tflite::TensorType_INT8) { value = tensor->quantization()->zero_point()->Get(0); } memset(eval_tensors_[i].data.raw, value, buffer_size); } } return kTfLiteOk; } } // namespace tflite
apache-2.0
carnegiespeech/translations
es_mx/grading.php
6119
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'grading', language 'es_mx', branch 'MOODLE_22_STABLE' * * @package grading * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['activemethodinfo'] = 'Se ha seleccionado \'{$a->method}\' como el método activo de calificación para el área \'{$a->area}'; $string['activemethodinfonone'] = 'No se ha seleccionado el método avanzado de calificación para el área \'{$a->area}\'. Se usará el método simple directo de calificación.'; $string['changeactivemethod'] = 'Cambiar método de calificación activo a'; $string['clicktoclose'] = 'clic para cerrar'; $string['exc_gradingformelement'] = 'No es posible crear un elemento del formato de calificación'; $string['formnotavailable'] = 'El método de calificación avanzada fue seleccionado para su uso, pero el formato de calificación aún no está disponible. Usted debería definirlo previamente utilizando el enlace existente en el menú Ajustes.'; $string['gradingformunavailable'] = 'Tenga en cuenta que el formato de calificación avanzada no está listo en este momento. Se utilizará el método simple de calificación hasta que el formato tenga un estatus válido'; $string['gradingmanagement'] = 'Calificación avanzada'; $string['gradingmanagementtitle'] = 'Calificación avanzada: {$a->component} ({$a->area})'; $string['gradingmethod'] = 'Método de calificación'; $string['gradingmethod_help'] = 'Elija el método de calificación avanzada que se debe utilizar para calcular las calificaciones en este contexto. Para deshabilitar la calificación avanzada y volver al método de calificación por defecto, elija \'Calificación simple directa\'.'; $string['gradingmethodnone'] = 'Calificación simple directa'; $string['gradingmethods'] = 'Métodos de calificación'; $string['manageactionclone'] = 'Crear un nuevo formato de calificación a partir de una plantilla'; $string['manageactiondelete'] = 'Eliminar el formato actualmente definido'; $string['manageactiondeleteconfirm'] = 'Usted va a eliminar el formato de calificación \'{$a->formname}\' y toda la información asociada de \'{$a->component} ({$a->area})\'. Por favor, asegúrese de que comprende las siguientes consecuencias: * No hay forma de deshacer la operación. * Usted puede cambiar a otro método de calificación, incluida la "Calificación simple directa" sin eliminar este formato. * Toda la información almacenada mediante los formatos de calificación se perderá. * Los resultados de las calificaciones calculadas guardadas en el libro de calificaciones no se verá afectados. Sin embargo, la explicación de cómo se han calculado no estará disponible. * Esta operación no afecta a eventuales copias de este formato en otras actividades.'; $string['manageactiondeletedone'] = 'El formato se eliminó correctamente'; $string['manageactionedit'] = 'Editar la definición del formato actual'; $string['manageactionnew'] = 'Defina un nuevo formato de calificación desde cero'; $string['manageactionshare'] = 'Publicar el formato como una nueva plantilla'; $string['manageactionshareconfirm'] = 'Está a punto de cuardar una copia del formato de calificación \'{$a}\' como una plantilla pública. Otros usuarios de su sitio podrán crear nuevos formatos de calificación para sus actividades a partir de esta plantilla.'; $string['manageactionsharedone'] = 'El formato se guardó correctamente como plantilla'; $string['noitemid'] = 'No es posible calificar. El elemento de calificación no existe.'; $string['nosharedformfound'] = 'No se ha encontrado plantilla'; $string['searchownforms'] = 'Incluir mis propios formatos'; $string['searchtemplate'] = 'Búsqueda de formatos de calificación'; $string['searchtemplate_help'] = 'Usted puede buscar aquí un formato de calificación y utilizarlo como una plantilla para crear un nuevo formato de calificación. Simplemente escriba palabras que formen parte del nombre del formato, la descripción o el cuerpo del mismo. Para buscar una frase, ponga toda la consulta entre comillas dobles. Por defecto, sólo los formatos de calificación que se han guardado como plantillas compartidas se incluyen en los resultados de búsqueda. También puede incluir todos sus propios formatos de calificación en los resultados de la búsqueda. De esta manera, puede reutilizar sus formatos de calificación, sin necesidad de compartirlos. Sólo los formatos marcados como "Listo para su uso" pueden ser reutilizados de esta manera.'; $string['statusdraft'] = 'Borrador'; $string['statusready'] = 'Listo para usar'; $string['templatedelete'] = 'Eliminar'; $string['templatedeleteconfirm'] = 'Esta a punto de borrar la plantilla compartida \'{$a}\'. Eliminar una plantilla no afecta a los formatos existentes creados a partir de la misma.'; $string['templateedit'] = 'Editar'; $string['templatepick'] = 'Usar esta plantilla'; $string['templatepickconfirm'] = '¿Desea usar el formato de calificación \'{$a->formname}\' como una plantilla para el nuevo formato de calificación en \'{$a->component} ({$a->area})\'?'; $string['templatepickownform'] = 'Utilice este formato como plantilla'; $string['templatesource'] = 'Localización: {$a->component} ({$a->area})'; $string['templatetypeown'] = 'Formato propio'; $string['templatetypeshared'] = 'Plantilla compartida';
apache-2.0
kiritbasu/datacollector
aws-lib/src/test/java/com/streamsets/pipeline/stage/origin/s3/TestAmazonS3Perf.java
3387
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.pipeline.stage.origin.s3; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.S3ClientOptions; import com.amazonaws.services.s3.iterable.S3Objects; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.S3ObjectSummary; import org.junit.Ignore; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.UUID; @Ignore public class TestAmazonS3Perf { @Ignore @Test public void testUpload() { AWSCredentials credentials = new BasicAWSCredentials("AKIAJ6S5Q43F4BT6ZJLQ", "tgKMwR5/GkFL5IbkqwABgdpzjEsN7n7qOEkFWgWX"); AmazonS3Client s3Client = new AmazonS3Client(credentials, new ClientConfiguration()); s3Client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); s3Client.setRegion(Region.getRegion(Regions.US_WEST_1)); for(int i = 0; i < 10; i++) { InputStream in = new ByteArrayInputStream("Hello World".getBytes()); PutObjectRequest putObjectRequest = new PutObjectRequest("hari-perf-test", "folder1/folder4/" + UUID.randomUUID().toString(), in, new ObjectMetadata()); s3Client.putObject(putObjectRequest); } } @Ignore @Test public void testBrowse() { AWSCredentials credentials = new BasicAWSCredentials("AKIAJ6S5Q43F4BT6ZJLQ", "tgKMwR5/GkFL5IbkqwABgdpzjEsN7n7qOEkFWgWX"); AmazonS3Client s3Client = new AmazonS3Client(credentials, new ClientConfiguration()); s3Client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); s3Client.setRegion(Region.getRegion(Regions.US_WEST_1)); //Browse all objects in folder1/folder2 System.out.println("Browse all objects in folder1/folder2"); int n = 1; int count = 0; long cummulativeSum = 0; for(int i = 0; i < n; i++) { long start = System.currentTimeMillis(); count = 0; //error-bucket/error-folder756847 for (S3ObjectSummary s : S3Objects.withPrefix(s3Client, "hari-perf-test", "folder1/folder-archive/")) { System.out.println(s.getKey()); count++; } long end = System.currentTimeMillis(); cummulativeSum += (end - start); } System.out.println("Time to browse " + count + " objects is : " + cummulativeSum/n + " ms"); } }
apache-2.0
dbflute-test/dbflute-test-option-compatible10x
src/test/java/org/docksidestage/compatible10x/dbflute/howto/BehaviorMiddleTest.java
31817
package org.docksidestage.compatible10x.dbflute.howto; import java.sql.Timestamp; import java.util.Date; import java.util.List; import org.dbflute.bhv.referrer.ConditionBeanSetupper; import org.dbflute.cbean.result.ListResultBean; import org.dbflute.cbean.result.PagingResultBean; import org.dbflute.cbean.scoping.ScalarQuery; import org.dbflute.exception.EntityAlreadyDeletedException; import org.dbflute.util.DfTypeUtil; import org.docksidestage.compatible10x.dbflute.cbean.MemberCB; import org.docksidestage.compatible10x.dbflute.cbean.PurchaseCB; import org.docksidestage.compatible10x.dbflute.exbhv.MemberBhv; import org.docksidestage.compatible10x.dbflute.exbhv.pmbean.MemberNamePmb; import org.docksidestage.compatible10x.dbflute.exbhv.pmbean.OptionMemberPmb; import org.docksidestage.compatible10x.dbflute.exbhv.pmbean.PurchaseMaxPriceMemberPmb; import org.docksidestage.compatible10x.dbflute.exbhv.pmbean.UnpaidSummaryMemberPmb; import org.docksidestage.compatible10x.dbflute.exentity.Member; import org.docksidestage.compatible10x.dbflute.exentity.Purchase; import org.docksidestage.compatible10x.dbflute.exentity.customize.OptionMember; import org.docksidestage.compatible10x.dbflute.exentity.customize.PurchaseMaxPriceMember; import org.docksidestage.compatible10x.dbflute.exentity.customize.UnpaidSummaryMember; import org.docksidestage.compatible10x.unit.UnitContainerTestCase; /** * Behaviorの中級編Example実装。 * <pre> * ターゲットは以下の通り: * o DBFluteってどういう機能があるのかを探っている方 * o DBFluteで実装を開始する方・実装している方 * * コンテンツは以下の通り: * o ページング検索: selectPage(). * o カラムの最大値検索(ScalarSelect): scalarSelect(), max(). * o one-to-many検索(LoadReferrer): loadXxxList(). * o 一件登録もしくは排他制御ありの一件更新: insertOrUpdate(). * o 一件登録もしくは排他制御なし一件更新: insertOrUpdateNonstrict(). * o Queryを使った更新: queryUpdate(). * o Queryを使った削除: queryDelete(). * o 外だしSQLでカラム一つだけのリスト検索: outsideSql().selectList(). * o 外だしSQLでエスケープ付き曖昧検索: outsideSql().selectList(). * o 外だしSQLで日付のFromTo検索: outsideSql().selectList(). * o 外だしSQLの手動ページング検索: outsideSql().manualPaging().selectPage(). * o 外だしSQLの自動ページング検索: outsideSql().autoPaging().selectPage(). * o 外だしSQLで一件検索: outsideSql().entitnHandling().selectEntity(). * o 外だしSQLでチェック付き一件検索: outsideSql().entitnHandling().selectEntityWithDeletedCheck(). * o 外だしSQLでカラム一つだけの一件検索: outsideSql().entitnHandling().selectEntity(). * </pre> * @author jflute * @since 0.7.3 (2008/05/31 Saturday) */ public class BehaviorMiddleTest extends UnitContainerTestCase { // =================================================================================== // Attribute // ========= /** The behavior of Member. (Injection Component) */ private MemberBhv memberBhv; // =================================================================================== // Paging(Page Select) // =================== /** * ページング検索: selectPage(). * 会員名称の昇順のリストを「1ページ4件」の「3ページ目」(9件目から12件目)を検索。 * <pre> * ConditionBean.paging(pageSize, pageNumber)にてページング条件を指定: * o pageSize : ページサイズ(1ページあたりのレコード数) * o pageNumber : ページ番号(検索する対象のページ) * * selectPage()だけでページングの基本が全て実行される: * 1. ページングなし件数取得 * 2. ページング実データ検索 * 3. ページング結果計算処理 * * PagingResultBeanから様々な要素が取得可能: * o ページングなし総件数 * o 現在ページ番号 * o 総ページ数 * o 前ページの有無判定 * o 次ページの有無判定 * o ページングナビゲーション要素 ※詳しくはBehaviorPlatinumTestにて * o などなど * </pre> */ @SuppressWarnings("deprecation") public void test_selectPage() { // ## Arrange ## MemberCB cb = new MemberCB(); cb.query().addOrderBy_MemberName_Asc(); cb.paging(4, 3);// The page size is 4 records per 1 page, and The page number is 3. // ## Act ## PagingResultBean<Member> page3 = memberBhv.selectPage(cb); // ## Assert ## assertNotSame(0, page3.size()); log("PagingResultBean.toString():" + ln() + " " + page3); for (Member member : page3) { log(member.toString()); } log("allRecordCount=" + page3.getAllRecordCount()); log("allPageCount=" + page3.getAllPageCount()); log("currentPageNumber=" + page3.getCurrentPageNumber()); log("currentStartRecordNumber=" + page3.getCurrentStartRecordNumber()); log("currentEndRecordNumber=" + page3.getCurrentEndRecordNumber()); log("isExistPrePage=" + page3.isExistPrePage()); log("isExistNextPage=" + page3.isExistNextPage()); // [Description] // A. paging()メソッドはDBFlute-0.7.3よりサポート。 // DBFlute-0.7.2までは以下の通り: // fetchFirst(4); // fetchPage(3); // // B. paging()メソッド第一引数のpageSizeは、マイナス値や0が指定されると例外発生 // --> 基本的にシステムで固定で指定する値であるため // // C. paging()メソッド第二引数のpageNumberは、マイナス値や0を指定されると「1ページ目」として扱われる。 // --> 基本的に画面リクエストの値で、予期せぬ数値が来る可能性があるため。 // // ※関連して、総ページ数を超えるページ番号が指定された場合は「最後のページ」として扱われる。 // (但し、ここは厳密にはpaging()の機能ではなくselectPage()の機能である) } // =================================================================================== // Scalar Select // ============= /** * カラムの最大値検索(ScalarSelect): scalarSelect(), max(). * 正式会員で一番最近(最大)の誕生日を検索。 * @since 0.8.6 */ public void test_scalarSelect_max() { // ## Arrange ## MemberCB cb = new MemberCB(); cb.specify().columnBirthdate(); cb.query().setMemberStatusCode_Equal_Formalized(); cb.query().setBirthdate_IsNotNull(); cb.query().addOrderBy_Birthdate_Desc(); cb.fetchFirst(1); Date expected = memberBhv.selectEntityWithDeletedCheck(cb).getBirthdate(); // ## Act ## memberBhv.scalarSelect(Date.class).max(new ScalarQuery<MemberCB>() { public void query(MemberCB cb) { cb.specify().columnBirthdate(); // *Point! cb.query().setMemberStatusCode_Equal_Formalized(); } }).alwaysPresent(birthdate -> { /* ## Assert ## */ assertEquals(expected, birthdate); }); // [Description] // A. max()/min()/sum()/avg()をサポート // B. サポートされない型を指定された場合は例外発生(例えばsum()に日付型を指定など) // C. コールバックのConditionBeanにて対象のカラムを指定。 // --> 必ず「一つだけ」を指定すること(無しもしくは複数の場合は例外発生) } // =================================================================================== // Load Referrer // ============= /** * one-to-many検索(LoadReferrer): loadXxxList(). * 検索した会員リストに対して、会員毎の購入カウントが2件以上の購入リストを購入カウントの降順でロード。 * 子テーブル(Referrer)を取得する「一発」のSQLを発行してマッピングをする(SubSelectフェッチ)。 * DBFluteではこのone-to-manyをロードする機能を「LoadReferrer」と呼ぶ。 */ public void test_loadReferrer() { // ## Arrange ## MemberCB cb = new MemberCB(); // At first, it selects the list of Member. ListResultBean<Member> memberList = memberBhv.selectList(cb); // ## Act ## // And it loads the list of Purchase with its conditions. memberBhv.loadPurchaseList(memberList, new ConditionBeanSetupper<PurchaseCB>() { public void setup(PurchaseCB cb) { cb.query().setPurchaseCount_GreaterEqual(2); cb.query().addOrderBy_PurchaseCount_Desc(); } }); // ## Assert ## assertFalse(memberList.isEmpty()); for (Member member : memberList) { log("[MEMBER]: " + member.getMemberName()); List<Purchase> purchaseList = member.getPurchaseList();// *Point! for (Purchase purchase : purchaseList) { log(" [PURCHASE]: " + purchase.toString()); } } // [SQL] // {1}: memberBhv.selectList(cb); // select ... // from MEMBER dfloc // // {2}: memberBhv.loadPurchaseList(memberList, ...); // select ... // from PURCHASE dfloc // where dfloc.MEMBER_ID in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20) // and dfloc.PURCHASE_COUNT >= 2 // order by dfloc.MEMBER_ID asc, dfloc.PURCHASE_COUNT desc // [Description] // A. 基点テーブルが複合PKの場合はサポートされない。 // --> このExampleでは会員テーブル。もし複合PKならloadPurchaseList()メソッド自体が生成されない。 // B. SubSelectフェッチなので「n+1問題」は発生しない。 // C. 枝分かれの子テーブルを取得することも可能。 // D. 子テーブルの親テーブルを取得することも可能。詳しくはBehaviorPlatinumTestにて // E. 子テーブルの子テーブル(孫テーブル)を取得することも可能。詳しくはBehaviorPlatinumTestにて } // =================================================================================== // Entity Update // ============= // ----------------------------------------------------- // InsertOrUpdate // -------------- /** * 一件登録もしくは排他制御ありの一件更新: insertOrUpdate(). */ public void test_insertOrUpdate() { // ## Arrange ## Member member = new Member(); member.setMemberName("testName"); member.setMemberAccount("testAccount"); member.setMemberStatusCode_Formalized(); // ## Act ## memberBhv.insertOrUpdate(member); member.setMemberName("testName2"); memberBhv.insertOrUpdate(member); // ## Assert ## MemberCB cb = new MemberCB(); cb.query().setMemberId_Equal(member.getMemberId()); Member actual = memberBhv.selectEntityWithDeletedCheck(cb); log(actual); assertEquals("testName2", actual.getMemberName()); // [Description] // A. 登録処理はinsert()、更新処理はupdate()に委譲する。 // B. PKの値が存在しない場合は、自動採番と判断し問答無用で登録処理となる。 // C. PK値が存在する場合は、先に更新処理をしてから結果を判断して登録処理をする。 } /** * 一件登録もしくは排他制御なし一件更新: insertOrUpdateNonstrict(). */ public void test_insertOrUpdateNonstrict() { // ## Arrange ## Member member = new Member(); member.setMemberName("testName"); member.setMemberAccount("testAccount"); member.setMemberStatusCode_Formalized(); // ## Act ## memberBhv.insertOrUpdateNonstrict(member); member.setMemberName("testName2"); member.setVersionNo(null); memberBhv.insertOrUpdateNonstrict(member); // ## Assert ## MemberCB cb = new MemberCB(); cb.query().setMemberId_Equal(member.getMemberId()); Member actual = memberBhv.selectEntityWithDeletedCheck(cb); log(actual); assertEquals("testName2", actual.getMemberName()); // [Description] // A. 登録処理はinsert()、更新処理はupdateNonstrict()に委譲する。 // B. PKの値が存在しない場合は、自動採番と判断し問答無用で登録処理となる。 // C. PK値が存在する場合は、先に更新処理をしてから結果を判断して登録処理をする。 } // =================================================================================== // Query Update // ============ /** * Queryを使った更新: queryUpdate(). * 会員ステータスが正式会員の会員を全て仮会員にする。 * ConditionBeanで設定した条件で一括削除が可能である。(排他制御はない) * @since 0.7.5 */ public void test_queryUpdate() { // ## Arrange ## deleteMemberReferrer();// for Test Member member = new Member(); member.setMemberStatusCode_Provisional();// 会員ステータスを「仮会員」に member.setFormalizedDatetime(null);// 正式会員日時を「null」に MemberCB cb = new MemberCB(); cb.query().setMemberStatusCode_Equal_Formalized();// 正式会員 // ## Act ## int updatedCount = memberBhv.queryUpdate(member, cb); // ## Assert ## assertNotSame(0, updatedCount); MemberCB actualCB = new MemberCB(); actualCB.query().setMemberStatusCode_Equal_Provisional(); actualCB.query().setFormalizedDatetime_IsNull(); actualCB.query().setUpdateUser_Equal(getAccessContext().getAccessUser());// Common Column ListResultBean<Member> actualList = memberBhv.selectList(actualCB); assertEquals(actualList.size(), updatedCount); // [Description] // A. 条件として、結合先のカラムによる条件やexists句を使ったサブクエリーなども利用可能。 // B. setupSelect_Xxx()やaddOrderBy_Xxx()を呼び出しても意味はない。 // C. 排他制御はせずに問答無用で更新する。(バージョンNOは自動インクリメント) // D. 更新結果が0件でも特に例外は発生しない。 // E. 共通カラム(CommonColumn)の自動設定は有効。 } /** * Queryを使った削除: queryDelete(). * 会員ステータスが正式会員の会員を全て削除する。 * ConditionBeanで設定した条件で一括削除が可能である。(排他制御はない) */ public void test_queryDelete() { // ## Arrange ## deleteMemberReferrer();// for Test MemberCB cb = new MemberCB(); cb.query().setMemberStatusCode_Equal_Formalized();// 正式会員 // ## Act ## int deletedCount = memberBhv.queryDelete(cb); // ## Assert ## assertNotSame(0, deletedCount); assertEquals(0, memberBhv.selectCount(cb)); // [Description] // A. 条件として、結合先のカラムによる条件やexists句を使ったサブクエリーなども利用可能。 // B. setupSelect_Xxx()やaddOrderBy_Xxx()を呼び出しても意味はない。 // C. 排他制御はせずに問答無用で削除する。 // D. 削除結果が0件でも特に例外は発生しない。 } // =================================================================================== // OutsideSql // ========== // ----------------------------------------------------- // List // ---- // /- - - - - - - - - - - - - - - - - - - - - - - - - - - // 基本的なselectList()に関しては、BehaviorBasicTestにて // - - - - - - - - - -/ /** * 外だしSQLでカラム一つだけのリスト検索: outsideSql().selectList(). */ public void test_outsideSql_selectList_selectMemberName() { // ## Arrange ## // SQLのパス String path = MemberBhv.PATH_selectMemberName; // 検索条件 MemberNamePmb pmb = new MemberNamePmb(); pmb.setMemberName_PrefixSearch("S"); // 戻り値Entityの型(String) Class<String> entityType = String.class;// *Point! // ## Act ## // SQL実行! List<String> memberNameList = memberBhv.outsideSql().selectList(path, pmb, entityType); // ## Assert ## assertNotSame(0, memberNameList.size()); log("{MemberName}"); for (String memberName : memberNameList) { log(" " + memberName); assertNotNull(memberName); assertTrue(memberName.startsWith("S")); } } // ----------------------------------------------------- // Option // ------ /** * 外だしSQLでエスケープ付き曖昧検索: outsideSql().selectList(). * <pre> * ParameterBeanの定義にて、以下のようにオプション「:like」を付与すると利用可能になる。 * -- !OptionMemberPmb! * -- !!Integer memberId!! * -- !!String memberName:like!! * </pre> */ public void test_outsideSql_selectList_selectOptionMember_LikeSearchOption() { // ## Arrange ## // テストのためにワイルドカード含みのテスト会員を作成 Member testMember1 = new Member(); testMember1.setMemberId(1); testMember1.setMemberName("ストイコ100%ビッチ_その1"); memberBhv.updateNonstrict(testMember1); Member testMember4 = new Member(); testMember4.setMemberId(4); testMember4.setMemberName("ストイコ100%ビッチ_その4"); memberBhv.updateNonstrict(testMember4); // SQLのパス String path = "selectOptionMember"; // 検索条件 OptionMemberPmb pmb = new OptionMemberPmb(); pmb.setMemberName_PrefixSearch("ストイコ100%ビッチ_その"); // 戻り値Entityの型 Class<OptionMember> entityType = OptionMember.class; // ## Act ## // SQL実行! List<OptionMember> memberList = memberBhv.outsideSql().selectList(path, pmb, entityType); // ## Assert ## assertNotSame("テストの成立のため1件以上は必ずあること: " + memberList.size(), 0, memberList.size()); log("{OptionMember}"); for (OptionMember member : memberList) { Integer memberId = member.getMemberId(); String memberName = member.getMemberName(); String memberStatusName = member.getMemberStatusName(); // Sql2EntityでもClassification機能が利用可能 boolean formalized = member.isMemberStatusCodeFormalized(); boolean dummyFlg = member.isDummyFlgTrue(); log(" " + memberId + ", " + memberName + ", " + memberStatusName + ", " + formalized + dummyFlg); try { member.getClass().getMethod("isDummyNoflgTrue", new Class[] {}); fail("The method 'isDummyNoflgTrue' must not exist!"); } catch (SecurityException e) { throw new IllegalStateException(e); } catch (NoSuchMethodException e) { // OK } assertNotNull(memberId); assertNotNull(memberName); assertNotNull(memberStatusName); assertTrue(memberName.startsWith("ストイコ100%ビッチ_その")); } // [Description] // A. 外だしSQLにおいては、LikeSearchOptionはlikeXxx()のみ利用可能。 // B. likeXxx()を指定すると自動でエスケープ処理が施される。 // C. CustomizeEntity(Sql2Entityで生成したEntity)でも区分値機能は利用可能。 } /** * 外だしSQLで日付のFromTo検索: outsideSql().selectList(). * ParameterBeanの定義にて、オプション「:fromDate, :toDate」を付与すると利用可能になる。 * <pre> * -- !OptionMemberPmb! * -- !!Integer memberId!! * -- !!Date fromFormalizedDate:fromDate!! * -- !!Date toFormalizedDate:toDate!! * </pre> */ public void test_outsideSql_selectList_selectOptionMember_DateFromTo() { // ## Arrange ## final String firstDate = "2003-02-25"; final String lastDate = "2006-09-04"; final String lastNextDate = "2006-09-05"; String path = MemberBhv.PATH_selectOptionMember; OptionMemberPmb pmb = new OptionMemberPmb(); pmb.setFromFormalizedDate_FromDate(DfTypeUtil.toTimestamp("2003-02-25")); pmb.setToFormalizedDate_ToDate(DfTypeUtil.toTimestamp(lastDate)); Class<OptionMember> entityType = OptionMember.class; // ## Act ## List<OptionMember> memberList = memberBhv.outsideSql().selectList(path, pmb, entityType); // ## Assert ## assertFalse(memberList.isEmpty()); boolean existsLastDate = false; for (OptionMember member : memberList) { String memberName = member.getMemberName(); Timestamp formalizedDatetime = member.getFormalizedDatetime(); log(memberName + ", " + formalizedDatetime); if (DfTypeUtil.toString(formalizedDatetime, "yyyy-MM-dd").equals(lastDate)) { existsLastDate = true; } } assertEquals(firstDate, DfTypeUtil.toString(pmb.getFromFormalizedDate(), "yyyy-MM-dd")); assertEquals(lastNextDate, DfTypeUtil.toString(pmb.getToFormalizedDate(), "yyyy-MM-dd")); assertTrue(existsLastDate); } // ----------------------------------------------------- // Paging // ------ @SuppressWarnings("deprecation") public void test_outsideSql_manualPaging_selectPage() { // ## Arrange ## PurchaseMaxPriceMemberPmb pmb = new PurchaseMaxPriceMemberPmb(); // ## Act ## int pageSize = 3; pmb.paging(pageSize, 1); // 1st page PagingResultBean<PurchaseMaxPriceMember> page1 = memberBhv.outsideSql().manualPaging().selectPage(pmb); pmb.paging(pageSize, 2); // 2nd page PagingResultBean<PurchaseMaxPriceMember> page2 = memberBhv.outsideSql().manualPaging().selectPage(pmb); pmb.paging(pageSize, 3); // 3rd page PagingResultBean<PurchaseMaxPriceMember> page3 = memberBhv.outsideSql().manualPaging().selectPage(pmb); pmb.paging(pageSize, page1.getAllPageCount()); // latest page PagingResultBean<PurchaseMaxPriceMember> lastPage = memberBhv.outsideSql().manualPaging().selectPage(pmb); // ## Assert ## showPage(page1, page2, page3, lastPage); assertEquals(3, page1.size()); assertEquals(3, page2.size()); assertEquals(3, page3.size()); assertNotSame(page1.get(0).getMemberId(), page2.get(0).getMemberId()); assertNotSame(page2.get(0).getMemberId(), page3.get(0).getMemberId()); assertEquals(1, page1.getCurrentPageNumber()); assertEquals(2, page2.getCurrentPageNumber()); assertEquals(3, page3.getCurrentPageNumber()); assertEquals(page1.getAllRecordCount(), page2.getAllRecordCount()); assertEquals(page2.getAllRecordCount(), page3.getAllRecordCount()); assertEquals(page1.getAllPageCount(), page2.getAllPageCount()); assertEquals(page2.getAllPageCount(), page3.getAllPageCount()); assertFalse(page1.isExistPrePage()); assertTrue(page1.isExistNextPage()); assertTrue(lastPage.isExistPrePage()); assertFalse(lastPage.isExistNextPage()); } /** * 外だしSQLの自動ページング検索: outsideSql().autoPaging().selectPage(). * 未払い合計金額の会員一覧を検索。 * <pre> * ParameterBean.paging(pageSize, pageNumber)にてページング条件を指定: * o pageSize : ページサイズ(1ページあたりのレコード数) * o pageNumber : ページ番号(検索する対象のページ) * * ※SQL上のParameterBeanの定義にて、以下のようにSimplePagingBeanを継承すること。 * -- !XxxPmb extends SPB! * * selectPage()だけでページングの基本が全て実行される: * 1. ページングなし件数取得 * 2. ページング実データ検索 * 3. ページング結果計算処理 * * PagingResultBeanから様々な要素が取得可能: * o ページングなし総件数 * o 現在ページ番号 * o 総ページ数 * o 前ページの有無判定 * o 次ページの有無判定 * o ページングナビゲーション要素ページリスト * o などなど * </pre> */ @SuppressWarnings("deprecation") public void test_outsideSql_autoPaging_selectPage() { // ## Arrange ## UnpaidSummaryMemberPmb pmb = new UnpaidSummaryMemberPmb(); pmb.setMemberStatusCode_Formalized(); // ## Act ## int pageSize = 3; pmb.paging(pageSize, 1); // 1st page PagingResultBean<UnpaidSummaryMember> page1 = memberBhv.outsideSql().autoPaging().selectPage(pmb); pmb.paging(pageSize, 2); // 2st page PagingResultBean<UnpaidSummaryMember> page2 = memberBhv.outsideSql().autoPaging().selectPage(pmb); pmb.paging(pageSize, 3); // 3st page PagingResultBean<UnpaidSummaryMember> page3 = memberBhv.outsideSql().autoPaging().selectPage(pmb); pmb.paging(pageSize, page1.getAllPageCount()); // latest page PagingResultBean<UnpaidSummaryMember> lastPage = memberBhv.outsideSql().autoPaging().selectPage(pmb); // ## Assert ## showPage(page1, page2, page3, lastPage); assertEquals(3, page1.size()); assertEquals(3, page2.size()); assertEquals(3, page3.size()); assertNotSame(page1.get(0).getUnpaidManId(), page2.get(0).getUnpaidManId()); assertNotSame(page2.get(0).getUnpaidManId(), page3.get(0).getUnpaidManId()); assertEquals(1, page1.getCurrentPageNumber()); assertEquals(2, page2.getCurrentPageNumber()); assertEquals(3, page3.getCurrentPageNumber()); assertEquals(page1.getAllRecordCount(), page2.getAllRecordCount()); assertEquals(page2.getAllRecordCount(), page3.getAllRecordCount()); assertEquals(page1.getAllPageCount(), page2.getAllPageCount()); assertEquals(page2.getAllPageCount(), page3.getAllPageCount()); assertFalse(page1.isExistPrePage()); assertTrue(page1.isExistNextPage()); assertTrue(lastPage.isExistPrePage()); assertFalse(lastPage.isExistNextPage()); } // ----------------------------------------------------- // Entity // ------ /** * 外だしSQLで一件検索: outsideSql().entitnHandling().selectEntity(). */ public void test_outsideSql_selectEntity_selectUnpaidSummaryMember() { // ## Arrange ## // SQLのパス String path = MemberBhv.PATH_selectUnpaidSummaryMember; // 検索条件 UnpaidSummaryMemberPmb pmb = new UnpaidSummaryMemberPmb(); pmb.setMemberId(3); // 戻り値Entityの型 Class<UnpaidSummaryMember> entityType = UnpaidSummaryMember.class; // ## Act ## UnpaidSummaryMember member = memberBhv.outsideSql().entityHandling().selectEntity(path, pmb, entityType); // ## Assert ## log("unpaidSummaryMember=" + member); assertNotNull(member); assertEquals(3, member.getUnpaidManId().intValue()); // [Description] // A. 存在しないIDを指定した場合はnullが戻る。 // B. 結果が複数件の場合は例外発生。{EntityDuplicatedException} } /** * 外だしSQLでチェック付き一件検索: outsideSql().entitnHandling().selectEntityWithDeletedCheck(). */ public void test_outsideSql_selectEntityWithDeletedCheck_selectUnpaidSummaryMember() { // ## Arrange ## // SQLのパス String path = MemberBhv.PATH_selectUnpaidSummaryMember; // 検索条件 UnpaidSummaryMemberPmb pmb = new UnpaidSummaryMemberPmb(); pmb.setMemberId(99999); // 戻り値Entityの型 Class<UnpaidSummaryMember> entityType = UnpaidSummaryMember.class; // ## Act & Assert ## try { memberBhv.outsideSql().entityHandling().selectEntityWithDeletedCheck(path, pmb, entityType); fail(); } catch (EntityAlreadyDeletedException e) { // OK log(e.getMessage()); } // 【Description】 // A. 存在しないIDを指定した場合は例外発生。{EntityAlreadyDeletedException} // B. 結果が複数件の場合は例外発生。{EntityDuplicatedException} } /** * 外だしSQLでカラム一つだけの一件検索: outsideSql().entitnHandling().selectEntity(). */ public void test_outsideSql_SelectEntityWithDeletedCheck_selectLatestFormalizedDatetimee() { // ## Arrange ## // SQLのパス String path = MemberBhv.PATH_selectLatestFormalizedDatetime; // 検索条件 Object pmb = null; // 戻り値Entityの型 Class<Timestamp> entityType = Timestamp.class;// *Point! // ## Act ## Timestamp maxValue = memberBhv.outsideSql().entityHandling().selectEntity(path, pmb, entityType); // ## Assert ## log("maxValue=" + maxValue); assertNotNull(maxValue); } }
apache-2.0
Narutuffy/Android_Storage
app/src/main/java/com/example/android/pets/CatalogActivity.java
5509
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.pets; import android.app.LoaderManager; import android.content.ContentUris; import android.content.ContentValues; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.ListView; import com.example.android.pets.data.PetContract.PetEntry; import com.example.android.pets.data.PetDbHelper; import com.example.android.pets.data.PetProvider; import org.w3c.dom.Text; /** * Displays list of pets that were entered and stored in the app. */ public class CatalogActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { private PetDbHelper mDbHelper; private static final int PET_LOADER=0; PetCursorAdapter mCursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_catalog); // Setup FAB to open EditorActivity FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(CatalogActivity.this, EditorActivity.class); startActivity(intent); } }); ListView petListView=(ListView)findViewById(R.id.list_view); View emptyView = findViewById(R.id.empty_view); petListView.setEmptyView(emptyView); mDbHelper= new PetDbHelper(this); //Set item up an Adapter to create a list item for each row of pet data in the cursor. //There is no pet data yet(until) the loader finishes to fetch the data, hence null.o mCursorAdapter=new PetCursorAdapter(this,null); petListView.setAdapter(mCursorAdapter); petListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Intent intent = new Intent(CatalogActivity.this, PetProvider.class); Uri currentPetUri = ContentUris.withAppendedId(PetEntry.CONTENT_URI,id); intent.setData(currentPetUri); startActivity(intent); } }); getLoaderManager().initLoader(PET_LOADER,null,this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu options from the res/menu/menu_catalog.xml file. // This adds menu items to the app bar. getMenuInflater().inflate(R.menu.menu_catalog, menu); return true; } private void insertPet(){ //Get the data repository in write mode ContentValues values= new ContentValues(); values.put(PetEntry.COLUMN_PET_NAME,"Toto"); values.put(PetEntry.COLUMN_PET_BREED,"Terrier"); values.put(PetEntry.COLUMN_PET_GENDER,PetEntry.GENDER_MALE); values.put(PetEntry.COLUMN_PET_WEIGHT,7); Uri newUri= getContentResolver().insert(PetEntry.CONTENT_URI,values); } @Override public boolean onOptionsItemSelected(MenuItem item) { // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { // Respond to a click on the "Insert dummy data" menu option case R.id.action_insert_dummy_data: insertPet(); return true; // Respond to a click on the "Delete all entries" menu option case R.id.action_delete_all_entries: int rowsDeleted= getContentResolver().delete(PetEntry.CONTENT_URI,null,null); return true; } return super.onOptionsItemSelected(item); } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { String[] projection ={ PetEntry._ID, PetEntry.COLUMN_PET_NAME, PetEntry.COLUMN_PET_BREED }; return new CursorLoader(this, PetEntry.CONTENT_URI, projection, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mCursorAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mCursorAdapter.swapCursor(null); } }
apache-2.0
GoogleCloudPlatform/opentelemetry-operations-java
e2e-test-server/src/main/java/com/google/cloud/opentelemetry/endtoend/ScenarioHandler.java
838
/* * Copyright 2022 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.opentelemetry.endtoend; /** A handler for testing scenarios. */ public interface ScenarioHandler { /** Handles a given tracing scenario request. Failures should be thrown. */ public Response handle(Request request); }
apache-2.0
iikira/BaiduPCS-Go
pcsutil/delay/delay.go
206
package delay import ( "time" ) // NewDelayChan 发送延时信号 func NewDelayChan(t time.Duration) <-chan struct{} { c := make(chan struct{}) go func() { time.Sleep(t) close(c) }() return c }
apache-2.0
prasanna08/oppia
core/domain/image_services_test.py
5358
# coding: utf-8 # # Copyright 2018 The Oppia 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. """Tests for methods in the image_services.""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import unicode_literals # pylint: disable=import-only-modules import io import os from PIL import Image from PIL import ImageChops from core.domain import image_services from core.tests import test_utils import feconf import python_utils class ImageServicesUnitTests(test_utils.GenericTestBase): """Tests for image_services.""" TEST_IMAGE_WIDTH = 3000 TEST_IMAGE_HEIGHT = 2092 def setUp(self): super(ImageServicesUnitTests, self).setUp() with python_utils.open_file( os.path.join(feconf.TESTS_DATA_DIR, 'dummy_large_image.jpg'), 'rb', encoding=None) as f: self.jpeg_raw_image = f.read() with python_utils.open_file( os.path.join(feconf.TESTS_DATA_DIR, 'img.png'), 'rb', encoding=None) as f: self.png_raw_image = f.read() def test_image_dimensions_are_output_correctly(self): height, width = ( image_services.get_image_dimensions(self.jpeg_raw_image)) self.assertEqual(self.TEST_IMAGE_HEIGHT, height) self.assertEqual(self.TEST_IMAGE_WIDTH, width) def test_compress_image_returns_correct_dimensions(self): compressed_image = ( image_services.compress_image(self.jpeg_raw_image, 0.5)) height, width = ( image_services.get_image_dimensions(compressed_image)) self.assertEqual(self.TEST_IMAGE_HEIGHT * 0.5, height) self.assertEqual(self.TEST_IMAGE_WIDTH * 0.5, width) def test_invalid_scaling_factor_triggers_value_error(self): value_exception = self.assertRaisesRegexp( ValueError, r'Scaling factor should be in the interval \(0, 1], received 1.1.') with value_exception: image_services.compress_image(self.jpeg_raw_image, 1.1) value_exception = self.assertRaisesRegexp( ValueError, r'Scaling factor should be in the interval \(0, 1], received 0.') with value_exception: image_services.compress_image(self.jpeg_raw_image, 0) value_exception = self.assertRaisesRegexp( ValueError, r'Scaling factor should be in the interval \(0, 1], received -1.') with value_exception: image_services.compress_image(self.jpeg_raw_image, -1) def test_compression_results_in_correct_format(self): compressed_image = ( image_services.compress_image(self.jpeg_raw_image, 0.7)) pil_image = Image.open(io.BytesIO(compressed_image)) self.assertEqual(pil_image.format, 'JPEG') compressed_image = ( image_services.compress_image(self.png_raw_image, 0.7)) pil_image = Image.open(io.BytesIO(compressed_image)) self.assertEqual(pil_image.format, 'PNG') def test_compression_results_in_identical_files(self): with python_utils.open_file( os.path.join( feconf.TESTS_DATA_DIR, 'compressed_image.jpg'), 'rb', encoding=None) as f: correct_compressed_image = f.read() correct_height, correct_width = ( image_services.get_image_dimensions(correct_compressed_image)) compressed_image = ( image_services.compress_image(self.jpeg_raw_image, 0.5)) # In order to make sure the images are the same, the function needs to # open and save the image specifically using PIL since the "golden # image" (image that we compare the compressed image to) is saved using # PIL. This applies a slight quality change that won't appear unless we # save it using PIL. temp_image = Image.open(io.BytesIO(compressed_image)) image_format = temp_image.format with io.BytesIO() as output: temp_image.save(output, format=image_format) compressed_image_content = output.getvalue() height, width = image_services.get_image_dimensions( compressed_image_content) self.assertEqual(correct_height, height) self.assertEqual(correct_width, width) image1 = Image.open(io.BytesIO(correct_compressed_image)).convert('RGB') image2 = Image.open(io.BytesIO(compressed_image_content)).convert('RGB') diff = ImageChops.difference(image1, image2) # Function diff.getbbox() returns a bounding box on all islands or # regions of non-zero pixels. In other words, if we have a bounding # box, there will be areas that are not 0 in the difference meaning # that the 2 images are not equal. self.assertFalse(diff.getbbox())
apache-2.0
rrdial/bing-ads-sdk-v9
src/BingAds/Reporting/ConversionPerformanceReportFilter.php
911
<?php namespace BingAds\Reporting; /** * Defines the criteria to use to filter the conversion performance report data. * * @link http://msdn.microsoft.com/en-us/library/gg262849(v=msads.90).aspx ConversionPerformanceReportFilter Data Object * * @uses AdDistributionReportFilter * @uses DeviceTypeReportFilter * @used-by ConversionPerformanceReportRequest */ final class ConversionPerformanceReportFilter { /** * The report will include data for only the specified distribution medium. * * @var AdDistributionReportFilter */ public $AdDistribution; /** * The report will include data for only the specified types of devices on which the ad is displayed. * * @var DeviceTypeReportFilter */ public $DeviceType; /** * The report will include data for only the specified keywords. * * @var string[] */ public $Keywords; }
apache-2.0
DatGye/AV-Mod
lua/av/shared.lua
423
av = {} -- must always be called before initializing additional scripts -- create metadata table _avmod = {} _avmod.name = "AV-Mod" _avmod.version = "0.0.1" _avmod.developer = "Rogavox Development" _avmod.authors = { ["Lead Programmer"] = "DatGye (Wyatt Phillips)", ["Entity Modeler"] = "Endless (Gregory Allen)" } -- load shared configuration av.config = {} -- initialize shared scripts include("av/console.lua")
apache-2.0
dbflute-test/dbflute-test-active-dockside
src/test/java/org/docksidestage/dockside/dbflute/whitebox/cbean/bigartist/scalarcondition/WxCBScalarConditionDreamCruiseTest.java
2914
package org.docksidestage.dockside.dbflute.whitebox.cbean.bigartist.scalarcondition; import org.dbflute.cbean.scoping.SubQuery; import org.dbflute.cbean.scoping.UnionQuery; import org.dbflute.exception.SQLFailureException; import org.dbflute.utflute.core.exception.ExceptionExaminer; import org.docksidestage.dockside.dbflute.cbean.MemberCB; import org.docksidestage.dockside.dbflute.exbhv.MemberBhv; import org.docksidestage.dockside.unit.UnitContainerTestCase; /** * @author jflute * @since 1.0.5K (2014/07/29 Tuesday) */ public class WxCBScalarConditionDreamCruiseTest extends UnitContainerTestCase { // =================================================================================== // Attribute // ========= private MemberBhv memberBhv; // =================================================================================== // Basic // ===== public void test_ScalarCondition_DreamCruise_basic() { // ## Arrange ## memberBhv.selectList(cb -> { /* ## Act ## */ cb.query().scalar_Equal().max(new SubQuery<MemberCB>() { public void query(MemberCB subCB) { MemberCB dreamCruiseCB = subCB.dreamCruiseCB(); subCB.specify().columnMemberId().plus(dreamCruiseCB.specify().columnVersionNo()); } }); pushCB(cb); }); // expects no exception // ## Assert ## String sql = popCB().toDisplaySql(); assertTrue(sql.contains("where dfloc.MEMBER_ID = (select max(sub1loc.MEMBER_ID + sub1loc.VERSION_NO)")); } public void test_ScalarCondition_DreamCruise_correlation_same_as_calculation() { // ## Arrange ## assertException(SQLFailureException.class, new ExceptionExaminer() { public void examine() { // ## Assert ## memberBhv.selectList(cb -> { /* ## Act ## */ cb.query().scalar_Equal().max(new SubQuery<MemberCB>() { public void query(MemberCB subCB) { MemberCB dreamCruiseCB = subCB.dreamCruiseCB(); subCB.specify().columnMemberId().plus(dreamCruiseCB.specify().columnVersionNo()); subCB.union(new UnionQuery<MemberCB>() { public void query(MemberCB unionCB) { } }); } }); pushCB(cb); }); } }); } }
apache-2.0
clearwavebuild/elmah
tests/TypeExtensionsTests.cs
2034
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace Elmah.Tests { #region Imports using System; using System.Linq; using Xunit; #endregion public class TypeExtensionsTests { [Fact] public void GetEnumMembersThrowsWithNullThis() { var e = Assert.Throws<ArgumentNullException>(() => TypeExtensions.GetEnumMembers(null)); Assert.Equal("type", e.ParamName); } [Fact] public void GetEnumMembersThrowsWithNonEnumThis() { var e = Assert.Throws<ArgumentException>(() => typeof(object).GetEnumMembers()); Assert.Equal("type", e.ParamName); } [Fact] public void GetEnumMembers() { var type = typeof(AttributeTargets); var members = type.GetEnumMembers(); Assert.NotNull(members); members = members.ToArray(); // materialize Assert.Equal(Enum.GetValues(type).Length, members.Count()); Assert.True(Enum.GetNames(type).SequenceEqual(from m in members select m.Key)); Assert.True(Enum.GetValues(type).Cast<object>().SequenceEqual(from m in members select m.Value)); } } }
apache-2.0
google-research/google-research
tf3d/instance_segmentation/metric_test.py
3741
# coding=utf-8 # Copyright 2022 The Google Research 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. """Tests for ...tf3d.instance_segmentation.metric.""" import tensorflow as tf from tf3d import standard_fields from tf3d.instance_segmentation import metric class MetricTest(tf.test.TestCase): def test_instance_segmentation_metric(self): label_map = {1: 'car', 2: 'bus', 3: 'sign', 9: 'pedestrian', 12: 'cyclist'} max_num_gt_objects = 10 max_num_predicted_objects = 20 max_num_voxels = 1000 num_classes = 20 num_frames = 5 inputs = [] outputs = [] for _ in range(num_frames): num_voxels = tf.random.uniform([], minval=1, maxval=max_num_voxels, dtype=tf.int32) num_gt_objects = tf.random.uniform([], minval=1, maxval=max_num_gt_objects, dtype=tf.int32) num_predicted_objects = tf.random.uniform( [], minval=1, maxval=max_num_predicted_objects, dtype=tf.int32) inputs_i = { standard_fields.InputDataFields.objects_class: tf.random.uniform([num_gt_objects, 1], minval=1, maxval=num_classes, dtype=tf.int32), standard_fields.InputDataFields.object_instance_id_voxels: tf.random.uniform([num_voxels, 1], minval=0, maxval=num_gt_objects, dtype=tf.int32), } inputs.append(inputs_i) outputs_i = { standard_fields.DetectionResultFields.objects_score: tf.random.uniform([num_predicted_objects, 1], minval=0.0, maxval=1.0, dtype=tf.float32), standard_fields.DetectionResultFields.objects_class: tf.random.uniform([num_predicted_objects, 1], minval=1, maxval=num_classes, dtype=tf.int32), standard_fields.DetectionResultFields.instance_segments_voxel_mask: tf.random.uniform([num_predicted_objects, num_voxels], minval=0.0, maxval=1.0, dtype=tf.float32), } outputs.append(outputs_i) iou_threshold = 0.5 m = metric.InstanceSegmentationMetric( iou_threshold=iou_threshold, num_classes=num_classes, label_map=label_map, eval_prefix='eval') for i in range(num_frames): m.update_state(inputs[i], outputs[i]) metrics_dict = m.get_metric_dictionary() for object_name in ['car', 'bus', 'sign', 'pedestrian', 'cyclist']: self.assertIn('eval_IOU{}_AP/{}'.format(iou_threshold, object_name), metrics_dict) self.assertIn('eval_avg/mean_AP_IOU{}'.format(iou_threshold), metrics_dict) if __name__ == '__main__': tf.test.main()
apache-2.0
vert-x3/vertx-codegen
src/test/java/io/vertx/test/codegen/testmodule/package-info.java
42
package io.vertx.test.codegen.testmodule;
apache-2.0
silho/WebBlogSite
src/com/weblog/service/impl/ArticleServiceImpl.java
4711
package com.weblog.service.impl; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Searcher; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.wltea.analyzer.lucene.IKAnalyzer; import org.wltea.analyzer.lucene.IKSimilarity; import com.weblog.base.DaoSupportImpl; import com.weblog.domain.Article; import com.weblog.service.ArticleService; import com.weblog.util.SearchBean; @Service @Transactional public class ArticleServiceImpl extends DaoSupportImpl<Article> implements ArticleService { /** 索引页面缓冲 */ private int maxBufferedDocs = 500; @SuppressWarnings("unchecked") @Override public List<Article> findAllByUsername(String username) { return getSession() .createQuery(// "FROM Article WHERE username = ?")// .setString(0, username) .list(); } @SuppressWarnings("unchecked") public Article findAllByUsernameAndDate(String username,Date date) { return (Article) getSession() .createQuery(// "FROM Article WHERE username = ?AND date=?")// .setString(0, username) .setDate(1, date) .uniqueResult(); } @SuppressWarnings("unchecked") public List<Article> findLatest() { return getSession() .createQuery(// "FROM Article order by id desc LIMIT 5")// .setMaxResults(5) .list(); } public void createIndexBean(Article article) throws Exception { SearchBean bean = new SearchBean(); System.out.println("ArticleServiceImpl.createIndexBean()"+article.getId()); bean.setId(article.getId()); bean.setTitle(article.getTitle()); String searchDir = "E:\\Test\\Index"; File indexFile = null; Directory directory = null; IndexWriter indexWriter = null; Analyzer analyzer = null; try { // indexFile = ; // if (!indexFile.exists()) { // indexFile.mkdir(); // } directory = FSDirectory.open(new File(searchDir)); analyzer = new IKAnalyzer(); /*创建lucene索引 * directory是在磁盘 还是在内存上读取一个文件 * analyzer 是分词器 * create是否创建 * maxFieldLength 对每个Field限制建立分词索引的最大数目 */ indexWriter = new IndexWriter(directory, analyzer,IndexWriter.MaxFieldLength.LIMITED); indexWriter.setMaxBufferedDocs(maxBufferedDocs); Document doc = null; doc = new Document(); /* * field对象 * 名字 * 值 * 是否存储 * 是否分词 * TermVector.NO不保存 */ Field id = new Field("id", String.valueOf(bean.getId()), Field.Store.YES, Field.Index.NOT_ANALYZED); Field title = new Field("title", bean.getTitle() == null ? "" : bean.getTitle(), Field.Store.YES, Field.Index.ANALYZED); doc.add(id); doc.add(title); indexWriter.addDocument(doc); //合并cfs文本 //indexWriter.optimize(); //设置合并因子,即满足3个cfs文本一合并 //indexWriter.setMergeFactor(3); indexWriter.close(); } catch (Exception e) { e.printStackTrace(); } } public List<SearchBean> search(String queryStr) throws Exception { Searcher searcher = null; File indexFile = null; String searchDir = "E:\\Test\\Index"; if (searcher == null) { indexFile = new File(searchDir); searcher = new IndexSearcher(FSDirectory.open(indexFile)); } searcher.setSimilarity(new IKSimilarity()); QueryParser parser = new QueryParser(Version.LUCENE_30, "title", new IKAnalyzer()); Query query = parser.parse(queryStr); //查找符合条件的全部记录 用第二个参数限定 TopDocs topDocs = searcher.search(query,searcher.maxDoc()); ScoreDoc[] scoreDocs = topDocs.scoreDocs; List<SearchBean> listBean = new ArrayList<SearchBean>(); SearchBean bean = null; for (int i = 0; i < scoreDocs.length; i++) { int docId = scoreDocs[i].doc; //根据编号去查找索引库原始记录表中的Document 对象 Document doc = searcher.doc(docId); //转换为JavaBean bean = new SearchBean(); bean.setId(Integer.parseInt(doc.get("id"))); bean.setTitle(doc.get("title")); listBean.add(bean); } return listBean; } }
apache-2.0
ajoymajumdar/genie
genie-web/src/test/java/com/netflix/genie/web/configs/ServicesConfigUnitTests.java
8833
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.configs; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.core.jobs.workflow.WorkflowTask; import com.netflix.genie.core.jpa.repositories.JpaApplicationRepository; import com.netflix.genie.core.jpa.repositories.JpaClusterRepository; import com.netflix.genie.core.jpa.repositories.JpaCommandRepository; import com.netflix.genie.core.jpa.repositories.JpaJobExecutionRepository; import com.netflix.genie.core.jpa.repositories.JpaJobMetadataRepository; import com.netflix.genie.core.jpa.repositories.JpaJobRepository; import com.netflix.genie.core.jpa.repositories.JpaJobRequestRepository; import com.netflix.genie.core.properties.JobsProperties; import com.netflix.genie.core.services.ApplicationService; import com.netflix.genie.core.services.ClusterLoadBalancer; import com.netflix.genie.core.services.ClusterService; import com.netflix.genie.core.services.CommandService; import com.netflix.genie.core.services.JobKillService; import com.netflix.genie.core.services.JobPersistenceService; import com.netflix.genie.core.services.JobSearchService; import com.netflix.genie.core.services.JobStateService; import com.netflix.genie.test.categories.UnitTest; import com.netflix.spectator.api.Registry; import org.apache.commons.exec.Executor; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.event.ApplicationEventMulticaster; import org.springframework.core.io.Resource; import org.springframework.mail.javamail.JavaMailSender; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Unit Tests for ServicesConfig class. * * @author amsharma * @since 3.0.0 */ @Category(UnitTest.class) public class ServicesConfigUnitTests { private JpaApplicationRepository applicationRepository; private JpaClusterRepository clusterRepository; private JpaCommandRepository commandRepository; private JpaJobExecutionRepository jobExecutionRepository; private JpaJobRepository jobRepository; private JpaJobRequestRepository jobRequestRepository; private JobSearchService jobSearchService; private ServicesConfig servicesConfig; /** * Setup to run before each test. */ @Before public void setUp() { this.applicationRepository = Mockito.mock(JpaApplicationRepository.class); this.clusterRepository = Mockito.mock(JpaClusterRepository.class); this.commandRepository = Mockito.mock(JpaCommandRepository.class); this.jobRepository = Mockito.mock(JpaJobRepository.class); this.jobRequestRepository = Mockito.mock(JpaJobRequestRepository.class); this.jobExecutionRepository = Mockito.mock(JpaJobExecutionRepository.class); this.jobSearchService = Mockito.mock(JobSearchService.class); this.servicesConfig = new ServicesConfig(); } /** * Confirm we can get a cluster load balancer. */ @Test public void canGetClusterLoadBalancer() { Assert.assertNotNull(this.servicesConfig.clusterLoadBalancer()); } /** * Confirm we can get a GenieFileTransfer instance. * * @throws GenieException If there is any problem. */ @Test public void canGetGenieFileTransfer() throws GenieException { Assert.assertNotNull(this.servicesConfig.genieFileTransferService(scheme -> null)); } /** * Confirm we can get a default mail service implementation. */ @Test public void canGetDefaultMailServiceImpl() { Assert.assertNotNull(this.servicesConfig.getDefaultMailServiceImpl()); } /** * Confirm we can get a mail service implementation using JavaMailSender. */ @Test public void canGetMailServiceImpl() { final JavaMailSender javaMailSender = Mockito.mock(JavaMailSender.class); Assert.assertNotNull(this.servicesConfig.getJavaMailSenderMailService(javaMailSender, "fromAddress")); } /** * Can get a bean for Application Service. */ @Test public void canGetApplicationServiceBean() { Assert.assertNotNull( this.servicesConfig.applicationService( this.applicationRepository, this.commandRepository ) ); } /** * Can get a bean for Command Service. */ @Test public void canGetCommandServiceBean() { Assert.assertNotNull( this.servicesConfig.commandService( this.commandRepository, this.applicationRepository, this.clusterRepository ) ); } /** * Can get a bean for Cluster Service. */ @Test public void canGetClusterServiceBean() { Assert.assertNotNull( this.servicesConfig.clusterService( this.clusterRepository, this.commandRepository ) ); } /** * Can get a bean for Job Search Service. */ @Test public void canGetJobSearchServiceBean() { Assert.assertNotNull( this.servicesConfig.jobSearchService( this.jobRepository, this.jobRequestRepository, this.jobExecutionRepository, Mockito.mock(JpaClusterRepository.class), Mockito.mock(JpaCommandRepository.class) ) ); } /** * Can get a bean for Job Persistence Service. */ @Test public void canGetJobPersistenceServiceBean() { Assert.assertNotNull( this.servicesConfig.jobPersistenceService( this.jobRepository, this.jobRequestRepository, Mockito.mock(JpaJobMetadataRepository.class), jobExecutionRepository, this.applicationRepository, this.clusterRepository, this.commandRepository ) ); } /** * Can get a bean for Job Submitter Service. */ @Test public void canGetJobSubmitterServiceBean() { final JobPersistenceService jobPersistenceService = Mockito.mock(JobPersistenceService.class); final ApplicationEventPublisher eventPublisher = Mockito.mock(ApplicationEventPublisher.class); final ApplicationEventMulticaster eventMulticaster = Mockito.mock(ApplicationEventMulticaster.class); final Resource resource = Mockito.mock(Resource.class); final List<WorkflowTask> workflowTasks = new ArrayList<>(); Assert.assertNotNull( this.servicesConfig.jobSubmitterService( jobPersistenceService, eventPublisher, eventMulticaster, workflowTasks, resource, Mockito.mock(Registry.class) ) ); } /** * Can get a bean for Job Coordinator Service. */ @Test public void canGetJobCoordinatorServiceBean() { Assert.assertNotNull( this.servicesConfig.jobCoordinatorService( Mockito.mock(JobPersistenceService.class), Mockito.mock(JobKillService.class), Mockito.mock(JobStateService.class), new JobsProperties(), Mockito.mock(ApplicationService.class), Mockito.mock(ClusterService.class), Mockito.mock(CommandService.class), Mockito.mock(ClusterLoadBalancer.class), Mockito.mock(Registry.class), UUID.randomUUID().toString() ) ); } /** * Can get a bean for Job Kill Service. */ @Test public void canGetJobKillServiceBean() { Assert.assertNotNull( this.servicesConfig.jobKillService( "localhost", this.jobSearchService, Mockito.mock(Executor.class), new JobsProperties(), Mockito.mock(ApplicationEventPublisher.class) ) ); } }
apache-2.0
lasalvavida/node-cesium-experimental
Modules/Renderer/lib/Texture.js
22115
'use strict'; var CesiumCore = require('cesium-core-experimental'); var Cartesian2 = CesiumCore.Cartesian2; var defaultValue = CesiumCore.defaultValue; var defined = CesiumCore.defined; var destroyObject = CesiumCore.destroyObject; var DeveloperError = CesiumCore.DeveloperError; var CesiumMath = CesiumCore.Math; var PixelFormat = CesiumCore.PixelFormat; var WebGLConstants = CesiumCore.WebGLConstants; var ContextLimits = require('./ContextLimits'); var MipmapHint = require('./MipmapHint'); var PixelDatatype = require('./PixelDatatype'); var Sampler = require('./Sampler'); var TextureMagnificationFilter = require('./TextureMagnificationFilter'); var TextureMinificationFilter = require('./TextureMinificationFilter'); function Texture(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); //>>includeStart('debug', pragmas.debug); if (!defined(options.context)) { throw new DeveloperError('options.context is required.'); } //>>includeEnd('debug'); var context = options.context; var width = options.width; var height = options.height; var source = options.source; if (defined(source)) { if (!defined(width)) { width = defaultValue(source.videoWidth, source.width); } if (!defined(height)) { height = defaultValue(source.videoHeight, source.height); } } var pixelFormat = defaultValue(options.pixelFormat, PixelFormat.RGBA); var pixelDatatype = defaultValue(options.pixelDatatype, PixelDatatype.UNSIGNED_BYTE); var internalFormat = pixelFormat; if (context.webgl2) { if (pixelFormat === PixelFormat.DEPTH_STENCIL) { internalFormat = WebGLConstants.DEPTH24_STENCIL8; } else if (pixelFormat === PixelFormat.DEPTH_COMPONENT) { if (pixelDatatype === PixelDatatype.UNSIGNED_SHORT) { internalFormat = WebGLConstants.DEPTH_COMPONENT16; } else if (pixelDatatype === PixelDatatype.UNSIGNED_INT) { internalFormat = WebGLConstants.DEPTH_COMPONENT24; } } } //>>includeStart('debug', pragmas.debug); if (!defined(width) || !defined(height)) { throw new DeveloperError('options requires a source field to create an initialized texture or width and height fields to create a blank texture.'); } if (width <= 0) { throw new DeveloperError('Width must be greater than zero.'); } if (width > ContextLimits.maximumTextureSize) { throw new DeveloperError('Width must be less than or equal to the maximum texture size (' + ContextLimits.maximumTextureSize + '). Check maximumTextureSize.'); } if (height <= 0) { throw new DeveloperError('Height must be greater than zero.'); } if (height > ContextLimits.maximumTextureSize) { throw new DeveloperError('Height must be less than or equal to the maximum texture size (' + ContextLimits.maximumTextureSize + '). Check maximumTextureSize.'); } if (!PixelFormat.validate(pixelFormat)) { throw new DeveloperError('Invalid options.pixelFormat.'); } if (!PixelDatatype.validate(pixelDatatype)) { throw new DeveloperError('Invalid options.pixelDatatype.'); } if ((pixelFormat === PixelFormat.DEPTH_COMPONENT) && ((pixelDatatype !== PixelDatatype.UNSIGNED_SHORT) && (pixelDatatype !== PixelDatatype.UNSIGNED_INT))) { throw new DeveloperError('When options.pixelFormat is DEPTH_COMPONENT, options.pixelDatatype must be UNSIGNED_SHORT or UNSIGNED_INT.'); } if ((pixelFormat === PixelFormat.DEPTH_STENCIL) && (pixelDatatype !== PixelDatatype.UNSIGNED_INT_24_8)) { throw new DeveloperError('When options.pixelFormat is DEPTH_STENCIL, options.pixelDatatype must be UNSIGNED_INT_24_8.'); } if ((pixelDatatype === PixelDatatype.FLOAT) && !context.floatingPointTexture) { throw new DeveloperError('When options.pixelDatatype is FLOAT, this WebGL implementation must support the OES_texture_float extension. Check context.floatingPointTexture.'); } if (PixelFormat.isDepthFormat(pixelFormat)) { if (defined(source)) { throw new DeveloperError('When options.pixelFormat is DEPTH_COMPONENT or DEPTH_STENCIL, source cannot be provided.'); } if (!context.depthTexture) { throw new DeveloperError('When options.pixelFormat is DEPTH_COMPONENT or DEPTH_STENCIL, this WebGL implementation must support WEBGL_depth_texture. Check context.depthTexture.'); } } //>>includeEnd('debug'); // Use premultiplied alpha for opaque textures should perform better on Chrome: // http://media.tojicode.com/webglCamp4/#20 var preMultiplyAlpha = options.preMultiplyAlpha || pixelFormat === PixelFormat.RGB || pixelFormat === PixelFormat.LUMINANCE; var flipY = defaultValue(options.flipY, true); var gl = context._gl; var textureTarget = gl.TEXTURE_2D; var texture = gl.createTexture(); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(textureTarget, texture); if (defined(source)) { // TODO: _gl.pixelStorei(_gl._UNPACK_ALIGNMENT, 4); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); if (defined(source.arrayBufferView)) { // Source: typed array gl.texImage2D(textureTarget, 0, internalFormat, width, height, 0, pixelFormat, pixelDatatype, source.arrayBufferView); } else if (defined(source.framebuffer)) { // Source: framebuffer if (source.framebuffer !== context.defaultFramebuffer) { source.framebuffer._bind(); } gl.copyTexImage2D(textureTarget, 0, internalFormat, source.xOffset, source.yOffset, width, height, 0); if (source.framebuffer !== context.defaultFramebuffer) { source.framebuffer._unBind(); } } else { // Source: ImageData, HTMLImageElement, HTMLCanvasElement, or HTMLVideoElement gl.texImage2D(textureTarget, 0, internalFormat, pixelFormat, pixelDatatype, source); } } else { gl.texImage2D(textureTarget, 0, internalFormat, width, height, 0, pixelFormat, pixelDatatype, null); } gl.bindTexture(textureTarget, null); this._context = context; this._textureFilterAnisotropic = context._textureFilterAnisotropic; this._textureTarget = textureTarget; this._texture = texture; this._pixelFormat = pixelFormat; this._pixelDatatype = pixelDatatype; this._width = width; this._height = height; this._dimensions = new Cartesian2(width, height); this._preMultiplyAlpha = preMultiplyAlpha; this._flipY = flipY; this._sampler = undefined; this.sampler = defined(options.sampler) ? options.sampler : new Sampler(); } /** * Creates a texture, and copies a subimage of the framebuffer to it. When called without arguments, * the texture is the same width and height as the framebuffer and contains its contents. * * @param {Object} options Object with the following properties: * @param {Context} options.context The context in which the Texture gets created. * @param {PixelFormat} [options.pixelFormat=PixelFormat.RGB] The texture's internal pixel format. * @param {Number} [options.framebufferXOffset=0] An offset in the x direction in the framebuffer where copying begins from. * @param {Number} [options.framebufferYOffset=0] An offset in the y direction in the framebuffer where copying begins from. * @param {Number} [options.width=canvas.clientWidth] The width of the texture in texels. * @param {Number} [options.height=canvas.clientHeight] The height of the texture in texels. * @param {Framebuffer} [options.framebuffer=defaultFramebuffer] The framebuffer from which to create the texture. If this * parameter is not specified, the default framebuffer is used. * @returns {Texture} A texture with contents from the framebuffer. * * @exception {DeveloperError} Invalid pixelFormat. * @exception {DeveloperError} pixelFormat cannot be DEPTH_COMPONENT or DEPTH_STENCIL. * @exception {DeveloperError} framebufferXOffset must be greater than or equal to zero. * @exception {DeveloperError} framebufferYOffset must be greater than or equal to zero. * @exception {DeveloperError} framebufferXOffset + width must be less than or equal to canvas.clientWidth. * @exception {DeveloperError} framebufferYOffset + height must be less than or equal to canvas.clientHeight. * * * @example * // Create a texture with the contents of the framebuffer. * var t = Texture.fromFramebuffer({ * context : context * }); * * @see Sampler * * @private */ Texture.fromFramebuffer = function(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); //>>includeStart('debug', pragmas.debug); if (!defined(options.context)) { throw new DeveloperError('options.context is required.'); } //>>includeEnd('debug'); var context = options.context; var gl = context._gl; var pixelFormat = defaultValue(options.pixelFormat, PixelFormat.RGB); var framebufferXOffset = defaultValue(options.framebufferXOffset, 0); var framebufferYOffset = defaultValue(options.framebufferYOffset, 0); var width = defaultValue(options.width, gl.drawingBufferWidth); var height = defaultValue(options.height, gl.drawingBufferHeight); var framebuffer = options.framebuffer; //>>includeStart('debug', pragmas.debug); if (!defined(options.context)) { throw new DeveloperError('context is required.'); } if (!PixelFormat.validate(pixelFormat)) { throw new DeveloperError('Invalid pixelFormat.'); } if (PixelFormat.isDepthFormat(pixelFormat)) { throw new DeveloperError('pixelFormat cannot be DEPTH_COMPONENT or DEPTH_STENCIL.'); } if (framebufferXOffset < 0) { throw new DeveloperError('framebufferXOffset must be greater than or equal to zero.'); } if (framebufferYOffset < 0) { throw new DeveloperError('framebufferYOffset must be greater than or equal to zero.'); } if (framebufferXOffset + width > gl.drawingBufferWidth) { throw new DeveloperError('framebufferXOffset + width must be less than or equal to drawingBufferWidth'); } if (framebufferYOffset + height > gl.drawingBufferHeight) { throw new DeveloperError('framebufferYOffset + height must be less than or equal to drawingBufferHeight.'); } //>>includeEnd('debug'); var texture = new Texture({ context : context, width : width, height : height, pixelFormat : pixelFormat, source : { framebuffer : defined(framebuffer) ? framebuffer : context.defaultFramebuffer, xOffset : framebufferXOffset, yOffset : framebufferYOffset, width : width, height : height } }); return texture; }; Object.defineProperties(Texture.prototype, { /** * The sampler to use when sampling this texture. * Create a sampler by calling {@link Sampler}. If this * parameter is not specified, a default sampler is used. The default sampler clamps texture * coordinates in both directions, uses linear filtering for both magnification and minifcation, * and uses a maximum anisotropy of 1.0. * @memberof Texture.prototype * @type {Object} */ sampler : { get : function() { return this._sampler; }, set : function(sampler) { var minificationFilter = sampler.minificationFilter; var magnificationFilter = sampler.magnificationFilter; var mipmap = (minificationFilter === TextureMinificationFilter.NEAREST_MIPMAP_NEAREST) || (minificationFilter === TextureMinificationFilter.NEAREST_MIPMAP_LINEAR) || (minificationFilter === TextureMinificationFilter.LINEAR_MIPMAP_NEAREST) || (minificationFilter === TextureMinificationFilter.LINEAR_MIPMAP_LINEAR); // float textures only support nearest filtering, so override the sampler's settings if (this._pixelDatatype === PixelDatatype.FLOAT) { minificationFilter = mipmap ? TextureMinificationFilter.NEAREST_MIPMAP_NEAREST : TextureMinificationFilter.NEAREST; magnificationFilter = TextureMagnificationFilter.NEAREST; } var gl = this._context._gl; var target = this._textureTarget; gl.activeTexture(gl.TEXTURE0); gl.bindTexture(target, this._texture); gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, minificationFilter); gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, magnificationFilter); gl.texParameteri(target, gl.TEXTURE_WRAP_S, sampler.wrapS); gl.texParameteri(target, gl.TEXTURE_WRAP_T, sampler.wrapT); if (defined(this._textureFilterAnisotropic)) { gl.texParameteri(target, this._textureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, sampler.maximumAnisotropy); } gl.bindTexture(target, null); this._sampler = sampler; } }, pixelFormat : { get : function() { return this._pixelFormat; } }, pixelDatatype : { get : function() { return this._pixelDatatype; } }, dimensions : { get : function() { return this._dimensions; } }, preMultiplyAlpha : { get : function() { return this._preMultiplyAlpha; } }, flipY : { get : function() { return this._flipY; } }, width : { get : function() { return this._width; } }, height : { get : function() { return this._height; } }, _target : { get : function() { return this._textureTarget; } } }); /** * Copy new image data into this texture, from a source {@link ImageData}, {@link Image}, {@link Canvas}, or {@link Video}. * or an object with width, height, and arrayBufferView properties. * * @param {Object} source The source {@link ImageData}, {@link Image}, {@link Canvas}, or {@link Video}, * or an object with width, height, and arrayBufferView properties. * @param {Number} [xOffset=0] The offset in the x direction within the texture to copy into. * @param {Number} [yOffset=0] The offset in the y direction within the texture to copy into. * * @exception {DeveloperError} Cannot call copyFrom when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL. * @exception {DeveloperError} xOffset must be greater than or equal to zero. * @exception {DeveloperError} yOffset must be greater than or equal to zero. * @exception {DeveloperError} xOffset + source.width must be less than or equal to width. * @exception {DeveloperError} yOffset + source.height must be less than or equal to height. * @exception {DeveloperError} This texture was destroyed, i.e., destroy() was called. * * @example * texture.copyFrom({ * width : 1, * height : 1, * arrayBufferView : new Uint8Array([255, 0, 0, 255]) * }); */ Texture.prototype.copyFrom = function(source, xOffset, yOffset) { xOffset = defaultValue(xOffset, 0); yOffset = defaultValue(yOffset, 0); //>>includeStart('debug', pragmas.debug); if (!defined(source)) { throw new DeveloperError('source is required.'); } if (PixelFormat.isDepthFormat(this._pixelFormat)) { throw new DeveloperError('Cannot call copyFrom when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL.'); } if (xOffset < 0) { throw new DeveloperError('xOffset must be greater than or equal to zero.'); } if (yOffset < 0) { throw new DeveloperError('yOffset must be greater than or equal to zero.'); } if (xOffset + source.width > this._width) { throw new DeveloperError('xOffset + source.width must be less than or equal to width.'); } if (yOffset + source.height > this._height) { throw new DeveloperError('yOffset + source.height must be less than or equal to height.'); } //>>includeEnd('debug'); var gl = this._context._gl; var target = this._textureTarget; // TODO: gl.pixelStorei(gl._UNPACK_ALIGNMENT, 4); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this._preMultiplyAlpha); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, this._flipY); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(target, this._texture); if (source.arrayBufferView) { gl.texSubImage2D(target, 0, xOffset, yOffset, source.width, source.height, this._pixelFormat, this._pixelDatatype, source.arrayBufferView); } else { gl.texSubImage2D(target, 0, xOffset, yOffset, this._pixelFormat, this._pixelDatatype, source); } gl.bindTexture(target, null); }; /** * @param {Number} [xOffset=0] The offset in the x direction within the texture to copy into. * @param {Number} [yOffset=0] The offset in the y direction within the texture to copy into. * @param {Number} [framebufferXOffset=0] optional * @param {Number} [framebufferYOffset=0] optional * @param {Number} [width=width] optional * @param {Number} [height=height] optional * * @exception {DeveloperError} Cannot call copyFromFramebuffer when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL. * @exception {DeveloperError} Cannot call copyFromFramebuffer when the texture pixel data type is FLOAT. * @exception {DeveloperError} This texture was destroyed, i.e., destroy() was called. * @exception {DeveloperError} xOffset must be greater than or equal to zero. * @exception {DeveloperError} yOffset must be greater than or equal to zero. * @exception {DeveloperError} framebufferXOffset must be greater than or equal to zero. * @exception {DeveloperError} framebufferYOffset must be greater than or equal to zero. * @exception {DeveloperError} xOffset + width must be less than or equal to width. * @exception {DeveloperError} yOffset + height must be less than or equal to height. */ Texture.prototype.copyFromFramebuffer = function(xOffset, yOffset, framebufferXOffset, framebufferYOffset, width, height) { xOffset = defaultValue(xOffset, 0); yOffset = defaultValue(yOffset, 0); framebufferXOffset = defaultValue(framebufferXOffset, 0); framebufferYOffset = defaultValue(framebufferYOffset, 0); width = defaultValue(width, this._width); height = defaultValue(height, this._height); //>>includeStart('debug', pragmas.debug); if (PixelFormat.isDepthFormat(this._pixelFormat)) { throw new DeveloperError('Cannot call copyFromFramebuffer when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL.'); } if (this._pixelDatatype === PixelDatatype.FLOAT) { throw new DeveloperError('Cannot call copyFromFramebuffer when the texture pixel data type is FLOAT.'); } if (xOffset < 0) { throw new DeveloperError('xOffset must be greater than or equal to zero.'); } if (yOffset < 0) { throw new DeveloperError('yOffset must be greater than or equal to zero.'); } if (framebufferXOffset < 0) { throw new DeveloperError('framebufferXOffset must be greater than or equal to zero.'); } if (framebufferYOffset < 0) { throw new DeveloperError('framebufferYOffset must be greater than or equal to zero.'); } if (xOffset + width > this._width) { throw new DeveloperError('xOffset + width must be less than or equal to width.'); } if (yOffset + height > this._height) { throw new DeveloperError('yOffset + height must be less than or equal to height.'); } //>>includeEnd('debug'); var gl = this._context._gl; var target = this._textureTarget; gl.activeTexture(gl.TEXTURE0); gl.bindTexture(target, this._texture); gl.copyTexSubImage2D(target, 0, xOffset, yOffset, framebufferXOffset, framebufferYOffset, width, height); gl.bindTexture(target, null); }; /** * @param {MipmapHint} [hint=MipmapHint.DONT_CARE] optional. * * @exception {DeveloperError} Cannot call generateMipmap when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL. * @exception {DeveloperError} hint is invalid. * @exception {DeveloperError} This texture's width must be a power of two to call generateMipmap(). * @exception {DeveloperError} This texture's height must be a power of two to call generateMipmap(). * @exception {DeveloperError} This texture was destroyed, i.e., destroy() was called. */ Texture.prototype.generateMipmap = function(hint) { hint = defaultValue(hint, MipmapHint.DONT_CARE); //>>includeStart('debug', pragmas.debug); if (PixelFormat.isDepthFormat(this._pixelFormat)) { throw new DeveloperError('Cannot call generateMipmap when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL.'); } if (this._width > 1 && !CesiumMath.isPowerOfTwo(this._width)) { throw new DeveloperError('width must be a power of two to call generateMipmap().'); } if (this._height > 1 && !CesiumMath.isPowerOfTwo(this._height)) { throw new DeveloperError('height must be a power of two to call generateMipmap().'); } if (!MipmapHint.validate(hint)) { throw new DeveloperError('hint is invalid.'); } //>>includeEnd('debug'); var gl = this._context._gl; var target = this._textureTarget; gl.hint(gl.GENERATE_MIPMAP_HINT, hint); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(target, this._texture); gl.generateMipmap(target); gl.bindTexture(target, null); }; Texture.prototype.isDestroyed = function() { return false; }; Texture.prototype.destroy = function() { this._context._gl.deleteTexture(this._texture); return destroyObject(this); }; module.exports = Texture;
apache-2.0
k000kc/java-a-to-z
Chapter_5/Lesson-5.2.1/src/test/java/ru/apetrov/Cycle/CycleTest.java
1572
package ru.apetrov.Cycle; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Created by Andrey on 17.03.2017. */ public class CycleTest { /** * Check when the cycle exists. */ @Test public void whenThereIsCycleThenResultTrue() { Node first = new Node(); Node two = new Node(); Node third = new Node(); Node four = new Node(); first.setNext(two); two.setNext(third); third.setNext(four); four.setNext(first); Cycle cycle = new Cycle(); assertThat(cycle.hasCycle(first), is(true)); } /** * Check when the cycle not exists. */ @Test public void whenThereIsNoCycleThenResultFalse() { Node first = new Node(); Node two = new Node(); Node third = new Node(); Node four = new Node(); first.setNext(two); two.setNext(third); third.setNext(four); four.setNext(null); Cycle cycle = new Cycle(); assertThat(cycle.hasCycle(first), is(false)); } /** * Check when the cycle exists. */ @Test public void whenThereIsCycleThenResultTrue2() { Node first = new Node(); Node two = new Node(); Node third = new Node(); Node four = new Node(); first.setNext(two); two.setNext(third); third.setNext(four); four.setNext(third); Cycle cycle = new Cycle(); assertThat(cycle.hasCycle2(first), is(true)); } }
apache-2.0
prowide/prowide-core
src/generated/java/com/prowidesoftware/swift/model/mt/mt0xx/MT028.java
11177
/* * Copyright 2006-2021 Prowide * * 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.prowidesoftware.swift.model.mt.mt0xx; import com.prowidesoftware.Generated; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.prowidesoftware.swift.model.*; import com.prowidesoftware.swift.model.field.*; import com.prowidesoftware.swift.model.mt.AbstractMT; import com.prowidesoftware.swift.utils.Lib; import java.io.File; import java.io.InputStream; import java.io.IOException; /** * MT 028 - FINCopy Message Status Request. * * <p> * SWIFT MT028 (ISO 15022) message structure: * <div class="scheme"><ul> <li class="field">Field 103 (M)</li> <li class="field">Field 243 (M)</li> <li class="field">Field 177 (O) (repetitive)</li> </ul></div> * * <p> * This source code is specific to release <strong>SRU 2021</strong> * <p> * For additional resources check <a href="https://www.prowidesoftware.com/resources">https://www.prowidesoftware.com/resources</a> */ @Generated public class MT028 extends AbstractMT implements Serializable { /** * Constant identifying the SRU to which this class belongs to. */ public static final int SRU = 2021; private static final long serialVersionUID = 1L; private static final transient java.util.logging.Logger log = java.util.logging.Logger.getLogger(MT028.class.getName()); /** * Constant for MT name, this is part of the classname, after MT. */ public static final String NAME = "028"; /** * Creates an MT028 initialized with the parameter SwiftMessage. * @param m swift message with the MT028 content */ public MT028(final SwiftMessage m) { super(m); sanityCheck(m); } /** * Creates an MT028 initialized with the parameter MtSwiftMessage. * @param m swift message with the MT028 content, the parameter can not be null * @see #MT028(String) */ public MT028(final MtSwiftMessage m) { this(m.message()); } /** * Creates an MT028 initialized with the parameter MtSwiftMessage. * * @param m swift message with the MT028 content * @return the created object or null if the parameter is null * @see #MT028(String) * @since 7.7 */ public static MT028 parse(final MtSwiftMessage m) { if (m == null) { return null; } return new MT028(m); } /** * Creates and initializes a new MT028 input message setting TEST BICS as sender and receiver. * All mandatory header attributes are completed with default values. * * @since 7.6 */ public MT028() { this(BIC.TEST8, BIC.TEST8); } /** * Creates and initializes a new MT028 input message from sender to receiver. * All mandatory header attributes are completed with default values. * In particular the sender and receiver addresses will be filled with proper default LT identifier * and branch codes if not provided, * * @param sender the sender address as a bic8, bic11 or full logical terminal consisting of 12 characters * @param receiver the receiver address as a bic8, bic11 or full logical terminal consisting of 12 characters * @since 7.7 */ public MT028(final String sender, final String receiver) { super(28, sender, receiver); } /** * Creates a new MT028 by parsing a String with the message content in its swift FIN format. * If the fin parameter is null or the message cannot be parsed, the internal message object * will be initialized (blocks will be created) but empty. * If the string contains multiple messages, only the first one will be parsed. * * @param fin a string with the MT message in its FIN swift format * @since 7.7 */ public MT028(final String fin) { super(); if (fin != null) { final SwiftMessage parsed = read(fin); if (parsed != null) { super.m = parsed; sanityCheck(parsed); } } } private void sanityCheck(final SwiftMessage param) { if (param.isServiceMessage()) { log.warning("Creating an MT028 object from FIN content with a Service Message. Check if the MT028 you are intended to read is prepended with and ACK."); } else if (!StringUtils.equals(param.getType(), "028")) { log.warning("Creating an MT028 object from FIN content with message type "+param.getType()); } } /** * Creates a new MT028 by parsing a String with the message content in its swift FIN format. * If the fin parameter cannot be parsed, the returned MT028 will have its internal message object * initialized (blocks will be created) but empty. * If the string contains multiple messages, only the first one will be parsed. * * @param fin a string with the MT message in its FIN swift format. <em>fin may be null in which case this method returns null</em> * @return a new instance of MT028 or null if fin is null * @since 7.7 */ public static MT028 parse(final String fin) { if (fin == null) { return null; } return new MT028(fin); } /** * Creates a new MT028 by parsing a input stream with the message content in its swift FIN format, using "UTF-8" as encoding. * If the message content is null or cannot be parsed, the internal message object * will be initialized (blocks will be created) but empty. * If the stream contains multiple messages, only the first one will be parsed. * * @param stream an input stream in UTF-8 encoding with the MT message in its FIN swift format. * @throws IOException if the stream data cannot be read * @since 7.7 */ public MT028(final InputStream stream) throws IOException { this(Lib.readStream(stream)); } /** * Creates a new MT028 by parsing a input stream with the message content in its swift FIN format, using "UTF-8" as encoding. * If the stream contains multiple messages, only the first one will be parsed. * * @param stream an input stream in UTF-8 encoding with the MT message in its FIN swift format. * @return a new instance of MT028 or null if stream is null or the message cannot be parsed * @throws IOException if the stream data cannot be read * @since 7.7 */ public static MT028 parse(final InputStream stream) throws IOException { if (stream == null) { return null; } return new MT028(stream); } /** * Creates a new MT028 by parsing a file with the message content in its swift FIN format. * If the file content is null or cannot be parsed as a message, the internal message object * will be initialized (blocks will be created) but empty. * If the file contains multiple messages, only the first one will be parsed. * * @param file a file with the MT message in its FIN swift format. * @throws IOException if the file content cannot be read * @since 7.7 */ public MT028(final File file) throws IOException { this(Lib.readFile(file)); } /** * Creates a new MT028 by parsing a file with the message content in its swift FIN format. * If the file contains multiple messages, only the first one will be parsed. * * @param file a file with the MT message in its FIN swift format. * @return a new instance of MT028 or null if; file is null, does not exist, can't be read, is not a file or the message cannot be parsed * @throws IOException if the file content cannot be read * @since 7.7 */ public static MT028 parse(final File file) throws IOException { if (file == null) { return null; } return new MT028(file); } /** * Returns this MT number. * @return the message type number of this MT * @since 6.4 */ @Override public String getMessageType() { return "028"; } /** * Add all tags from block to the end of the block4. * * @param block to append * @return this object to allow method chaining * @since 7.6 */ @Override public MT028 append(final SwiftTagListBlock block) { super.append(block); return this; } /** * Add all tags to the end of the block4. * * @param tags to append * @return this object to allow method chaining * @since 7.6 */ @Override public MT028 append(final Tag... tags) { super.append(tags); return this; } /** * Add all the fields to the end of the block4. * * @param fields to append * @return this object to allow method chaining * @since 7.6 */ @Override public MT028 append(final Field... fields) { super.append(fields); return this; } /** * Creates an MT028 messages from its JSON representation. * <p> * For generic conversion of JSON into the corresponding MT instance * see {@link AbstractMT#fromJson(String)} * * @param json a JSON representation of an MT028 message * @return a new instance of MT028 * @since 7.10.3 */ public static MT028 fromJson(final String json) { return (MT028) AbstractMT.fromJson(json); } /** * Iterates through block4 fields and return the first one whose name matches 103, * or null if none is found. * The first occurrence of field 103 at MT028 is expected to be the only one. * * @return a Field103 object or null if the field is not found * @see SwiftTagListBlock#getTagByName(String) * @throws IllegalStateException if SwiftMessage object is not initialized */ public Field103 getField103() { final Tag t = tag("103"); if (t != null) { return new Field103(t.getValue()); } else { return null; } } /** * Iterates through block4 fields and return the first one whose name matches 243, * or null if none is found. * The first occurrence of field 243 at MT028 is expected to be the only one. * * @return a Field243 object or null if the field is not found * @see SwiftTagListBlock#getTagByName(String) * @throws IllegalStateException if SwiftMessage object is not initialized */ public Field243 getField243() { final Tag t = tag("243"); if (t != null) { return new Field243(t.getValue()); } else { return null; } } /** * Iterates through block4 fields and return all occurrences of fields whose names matches 177, * or <code>Collections.emptyList()</code> if none is found. * Multiple occurrences of field 177 at MT028 are expected at one sequence or across several sequences. * * @return a List of Field177 objects or <code>Collections.emptyList()</code> if none is not found * @see SwiftTagListBlock#getTagsByName(String) * @throws IllegalStateException if SwiftMessage object is not initialized */ public List<Field177> getField177() { final List<Field177> result = new ArrayList<>(); final Tag[] tags = tags("177"); if (tags != null && tags.length > 0) { for (Tag tag : tags) { result.add(new Field177(tag.getValue())); } } return result; } }
apache-2.0
simonlaroche/akka.net
src/core/Akka.Tests/IO/UdpListenerSpec.cs
7306
//----------------------------------------------------------------------- // <copyright file="UdpListenerSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Net; using System.Net.Sockets; using System.Text; using Akka.Actor; using Akka.IO; using Akka.TestKit; using Xunit; using UdpListener = Akka.IO.UdpListener; namespace Akka.Tests.IO { public class UdpListenerSpec : AkkaSpec { public UdpListenerSpec() : base(@"akka.io.udp.max-channels = unlimited akka.io.udp.nr-of-selectors = 1 akka.io.udp.direct-buffer-pool-limit = 100 akka.io.udp.direct-buffer-size = 1024") { } [Fact] public void A_UDP_Listener_must_let_the_bind_commander_know_when_binding_is_complete() { new TestSetup(this).Run(x => { x.BindCommander.ExpectMsg<Udp.Bound>(); }); } [Fact] public void A_UDP_Listener_must_forward_incoming_packets_to_handler_actor() { const string dgram = "Fly little packet!"; new TestSetup(this).Run(x => { x.BindCommander.ExpectMsg<Udp.Bound>(); x.SendDataToLocal(Encoding.UTF8.GetBytes(dgram)); x.Handler.ExpectMsg<Udp.Received>(_ => Assert.Equal(dgram, Encoding.UTF8.GetString(_.Data.ToArray()))); x.SendDataToLocal(Encoding.UTF8.GetBytes(dgram)); x.Handler.ExpectMsg<Udp.Received>(_ => Assert.Equal(dgram, Encoding.UTF8.GetString(_.Data.ToArray()))); }); } [Fact] public void A_UDP_Listener_must_be_able_to_send_and_receive_when_server_goes_away() { new TestSetup(this).Run(x => { x.BindCommander.ExpectMsg<Udp.Bound>(); // Receive UDP messages from a sender const string requestMessage = "This is my last request!"; var notExistingEndPoint = x.SendDataToLocal(Encoding.UTF8.GetBytes(requestMessage)); x.Handler.ExpectMsg<Udp.Received>(_ => { Assert.Equal(requestMessage, Encoding.UTF8.GetString(_.Data.ToArray())); }); // Try to reply to this sender which DOES NOT EXIST any more // Important: The UDP port of the reply must match the listing UDP port! // This UDP port will also be used for ICMP error reporting. // Hint: On Linux the listener port cannot be reused. We are using the udp actor to respond. IActorRef localSender = x.Listener; const string response = "Are you still alive?"; // he is not localSender.Tell(Udp.Send.Create(ByteString.FromBytes(Encoding.UTF8.GetBytes(response)), notExistingEndPoint)); // Now an ICMP error message "port unreachable" (SocketError.ConnectionReset) is sent to our UDP server port x.Handler.ExpectNoMsg(TimeSpan.FromSeconds(1)); const string followUpMessage = "Back online!"; x.SendDataToLocal(Encoding.UTF8.GetBytes(followUpMessage)); x.Handler.ExpectMsg<Udp.Received>(_ => Assert.Equal(followUpMessage, Encoding.UTF8.GetString(_.Data.ToArray()))); }); } class TestSetup { private readonly TestKitBase _kit; private readonly TestProbe _handler; private readonly TestProbe _bindCommander; private readonly TestProbe _parent; private readonly IPEndPoint _localEndpoint; private readonly TestActorRef<ListenerParent> _parentRef; public TestSetup(TestKitBase kit) : this(kit, TestUtils.TemporaryServerAddress()) { } public TestSetup(TestKitBase kit, IPEndPoint localEndpoint) { _kit = kit; _localEndpoint = localEndpoint; _handler = kit.CreateTestProbe(); _bindCommander = kit.CreateTestProbe(); _parent = kit.CreateTestProbe(); _parentRef = new TestActorRef<ListenerParent>(kit.Sys, Props.Create(() => new ListenerParent(this))); } public void Run(Action<TestSetup> test) { test(this); } public void BindListener() { _bindCommander.ExpectMsg<Udp.Bound>(); } public IPEndPoint SendDataToLocal(byte[] buffer) { return SendDataToEndpoint(buffer, _localEndpoint); } public IPEndPoint SendDataToEndpoint(byte[] buffer, IPEndPoint receiverEndpoint) { var tempEndpoint = TestUtils.TemporaryServerAddress(); return SendDataToEndpoint(buffer, receiverEndpoint, tempEndpoint); } public IPEndPoint SendDataToEndpoint(byte[] buffer, IPEndPoint receiverEndpoint, IPEndPoint senderEndpoint) { using (var udpClient = new UdpClient(senderEndpoint.Port)) { udpClient.Connect(receiverEndpoint); udpClient.Send(buffer, buffer.Length); } return senderEndpoint; } public IActorRef Listener { get { return _parentRef.UnderlyingActor.Listener; } } public TestProbe BindCommander { get { return _bindCommander; } } public TestProbe Handler { get { return _handler; } } public IPEndPoint LocalLocalEndPoint { get { return _localEndpoint; } } class ListenerParent : ActorBase { private readonly TestSetup _test; private readonly IActorRef _listener; public ListenerParent(TestSetup test) { _test = test; _listener = Context.ActorOf(Props.Create(() => new UdpListener( Udp.Instance.Apply(Context.System), test._bindCommander.Ref, new Udp.Bind(_test._handler.Ref, test._localEndpoint, new Inet.SocketOption[]{}))) .WithDeploy(Deploy.Local)); _test._parent.Watch(_listener); } internal IActorRef Listener { get { return _listener; } } protected override bool Receive(object message) { _test._parent.Forward(message); return true; } protected override SupervisorStrategy SupervisorStrategy() { return Akka.Actor.SupervisorStrategy.StoppingStrategy; } } } } }
apache-2.0
google-research/language
language/common/inputs/char_utils_test.py
3486
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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. # coding=utf-8 """Tests for char_utils.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from language.common.inputs import char_utils from six.moves import zip import tensorflow.compat.v1 as tf class CharUtilsTest(tf.test.TestCase): def test_empty_word(self): words_to_test = [""] expected_char_ids = [[256, 257, 258, 258, 258]] self._test_words(words_to_test, expected_char_ids, 5) def test_ascii_word(self): words_to_test = [] expected_char_ids = [] words_to_test.append("pad") expected_char_ids.append([256, 112, 97, 100, 257, 258, 258]) words_to_test.append("exact") expected_char_ids.append([256, 101, 120, 97, 99, 116, 257]) words_to_test.append("truncated") expected_char_ids.append([256, 116, 114, 117, 110, 99, 257]) self._test_words(words_to_test, expected_char_ids, 7) def test_unicode_word(self): words_to_test = [] expected_char_ids = [] words_to_test.append(u"谷") expected_char_ids.append( [256, 232, 176, 183, 257, 258, 258, 258, 258, 258, 258, 258]) words_to_test.append(u"(ᵔᴥᵔ)") expected_char_ids.append( [256, 40, 225, 181, 148, 225, 180, 165, 225, 181, 148, 257]) words_to_test.append(u"¯\\_(ツ)_/¯") expected_char_ids.append( [256, 194, 175, 92, 95, 40, 227, 131, 132, 41, 95, 257]) self._test_words(words_to_test, expected_char_ids, 12) def _test_words(self, words, expected_char_ids, word_length): with tf.Graph().as_default(): char_ids = char_utils.batch_word_to_char_ids( tf.constant(words), word_length) with tf.Session() as sess: actual_char_ids = sess.run(char_ids) for a_cid, e_cid in zip(actual_char_ids, expected_char_ids): self.assertAllEqual(a_cid, e_cid) def test_token_to_char_ids_mapper(self): with tf.Graph().as_default(): dataset = tf.data.Dataset.from_tensor_slices({"s": ["a", "b"]}) dataset = dataset.map(char_utils.token_to_char_ids_mapper(["s"], 4)) self.assertDictEqual(dataset.output_types, {"s": tf.string, "s_cid": tf.int32}) self.assertDictEqual(dataset.output_shapes, {"s": [], "s_cid": [4]}) dataset = dataset.batch(2) features = dataset.make_one_shot_iterator().get_next() with tf.Session() as sess: tf_s, tf_s_cid = sess.run([features["s"], features["s_cid"]]) self.assertAllEqual(tf_s, ["a", "b"]) expected_a_emb = [char_utils.BOW_CHAR, 97, char_utils.EOW_CHAR, char_utils.PAD_CHAR] expected_b_emb = [char_utils.BOW_CHAR, 98, char_utils.EOW_CHAR, char_utils.PAD_CHAR] self.assertAllEqual(tf_s_cid, [expected_a_emb, expected_b_emb]) if __name__ == "__main__": tf.test.main()
apache-2.0
dbflute-test/dbflute-test-dbms-sqlite
src/main/java/org/docksidestage/sqlite/dbflute/readonly/bsbhv/loader/RoyLoaderOfPurchase.java
3689
package org.docksidestage.sqlite.dbflute.readonly.bsbhv.loader; import java.util.List; import org.dbflute.bhv.*; import org.docksidestage.sqlite.dbflute.readonly.exbhv.*; import org.docksidestage.sqlite.dbflute.readonly.exentity.*; /** * The referrer loader of PURCHASE as TABLE. <br> * <pre> * [primary key] * PURCHASE_ID * * [column] * PURCHASE_ID, MEMBER_ID, PRODUCT_ID, PURCHASE_DATETIME, PURCHASE_COUNT, PURCHASE_PRICE, PAYMENT_COMPLETE_FLG, PURCHASE_REGISTER_DATETIME, PURCHASE_REGISTER_USER, PURCHASE_REGISTER_PROCESS, PURCHASE_UPDATE_DATETIME, PURCHASE_UPDATE_USER, PURCHASE_UPDATE_PROCESS, VERSION_NO * * [sequence] * * * [identity] * PURCHASE_ID * * [version-no] * VERSION_NO * * [foreign table] * MEMBER, PRODUCT, SUMMARY_PRODUCT * * [referrer table] * * * [foreign property] * member, product, summaryProduct * * [referrer property] * * </pre> * @author DBFlute(AutoGenerator) */ public class RoyLoaderOfPurchase { // =================================================================================== // Attribute // ========= protected List<RoyPurchase> _selectedList; protected BehaviorSelector _selector; protected RoyPurchaseBhv _myBhv; // lazy-loaded // =================================================================================== // Ready for Loading // ================= public RoyLoaderOfPurchase ready(List<RoyPurchase> selectedList, BehaviorSelector selector) { _selectedList = selectedList; _selector = selector; return this; } protected RoyPurchaseBhv myBhv() { if (_myBhv != null) { return _myBhv; } else { _myBhv = _selector.select(RoyPurchaseBhv.class); return _myBhv; } } // =================================================================================== // Pull out Foreign // ================ protected RoyLoaderOfMember _foreignMemberLoader; public RoyLoaderOfMember pulloutMember() { if (_foreignMemberLoader == null) { _foreignMemberLoader = new RoyLoaderOfMember().ready(myBhv().pulloutMember(_selectedList), _selector); } return _foreignMemberLoader; } protected RoyLoaderOfProduct _foreignProductLoader; public RoyLoaderOfProduct pulloutProduct() { if (_foreignProductLoader == null) { _foreignProductLoader = new RoyLoaderOfProduct().ready(myBhv().pulloutProduct(_selectedList), _selector); } return _foreignProductLoader; } protected RoyLoaderOfSummaryProduct _foreignSummaryProductLoader; public RoyLoaderOfSummaryProduct pulloutSummaryProduct() { if (_foreignSummaryProductLoader == null) { _foreignSummaryProductLoader = new RoyLoaderOfSummaryProduct().ready(myBhv().pulloutSummaryProduct(_selectedList), _selector); } return _foreignSummaryProductLoader; } // =================================================================================== // Accessor // ======== public List<RoyPurchase> getSelectedList() { return _selectedList; } public BehaviorSelector getSelector() { return _selector; } }
apache-2.0
sptz45/coeus
src/test/scala/com/tzavellas/coeus/bind/converter/CurrencySymbolConverterTest.scala
716
/* - Coeus web framework ------------------------- * * Licensed under the Apache License, Version 2.0. * * Author: Spiros Tzavellas */ package com.tzavellas.coeus.bind.converter import java.util.{Currency, Locale} import org.junit.Test import org.junit.Assert._ class CurrencyConverterrTest { val locale = Locale.GERMANY val euro = Currency.getInstance("EUR") val conv = new CurrencySymbolConverter @Test def simple_test() { assertEquals(euro, conv.parse("eur", locale)) assertEquals(euro, conv.parse("EUR", locale)) assertEquals(euro, conv.parse(" EUR ", locale)) } @Test(expected=classOf[IllegalArgumentException]) def null_handling() { conv.parse(null, locale) } }
apache-2.0
idahammer/AF5129_ida_h
Ass2Uppgift1/src/House.java
541
public class House{ int minSize = 10; int maxSize = 1000; int minYear = 1800; int maxYear = 2015; private int yearBuilt; private int size; public House(int yearBuilt,int size){ if (size >= minSize && size <= maxSize){ this.size = size; } else { this.size = 0; } if (yearBuilt >= minYear && yearBuilt <= maxYear){ this.yearBuilt = yearBuilt; } else { this.yearBuilt = 0; } } public int getYearBuilt(){ return this.yearBuilt; } public int getSize(){ return this.size; } }
apache-2.0
EBISPOT/goci
goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/service/DiseaseTraitService.java
6979
package uk.ac.ebi.spot.goci.curation.service; import org.apache.commons.text.similarity.CosineDistance; import org.apache.commons.text.similarity.LevenshteinDistance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import uk.ac.ebi.spot.goci.curation.constants.EntityType; import uk.ac.ebi.spot.goci.curation.dto.AnalysisCacheDto; import uk.ac.ebi.spot.goci.curation.dto.AnalysisDTO; import uk.ac.ebi.spot.goci.curation.dto.DiseaseTraitDto; import uk.ac.ebi.spot.goci.curation.exception.DataIntegrityException; import uk.ac.ebi.spot.goci.model.DiseaseTrait; import uk.ac.ebi.spot.goci.model.Study; import uk.ac.ebi.spot.goci.repository.DiseaseTraitRepository; import uk.ac.ebi.spot.goci.repository.StudyRepository; import java.util.*; import java.util.stream.Collectors; @Service public class DiseaseTraitService { private static final Logger log = LoggerFactory.getLogger(DiseaseTraitService.class); private DiseaseTraitRepository diseaseTraitRepository; private StudyRepository studyRepository; public DiseaseTraitService(DiseaseTraitRepository diseaseTraitRepository, StudyRepository studyRepository) { this.diseaseTraitRepository = diseaseTraitRepository; this.studyRepository = studyRepository; } public Optional<DiseaseTrait> getDiseaseTrait(Long traitId) { return Optional.ofNullable(diseaseTraitRepository.findOne(traitId)); } public Page<DiseaseTrait> getDiseaseTraits(Pageable pageable) { return diseaseTraitRepository.findAll(pageable); } public DiseaseTrait createDiseaseTrait(DiseaseTrait diseaseTrait) { diseaseTraitRepository.findByTrait(diseaseTrait.getTrait()) .ifPresent(trait -> { throw new DataIntegrityException(String.format("Trait %s already exist", trait.getTrait())); }); diseaseTrait = diseaseTraitRepository.save(diseaseTrait); return diseaseTrait; } public Page<DiseaseTrait> searchByParameter(String search, Pageable pageable) { return diseaseTraitRepository.findBySearchParameter(search, pageable); } public Optional<DiseaseTrait> updateDiseaseTrait(DiseaseTraitDto diseaseTraitDTO, Long traitId) { return this.getDiseaseTrait(traitId) .map(diseaseTrait -> { diseaseTrait.setTrait(diseaseTraitDTO.getTrait()); log.info("Updating {}: {}", EntityType.DISEASE_TRAIT, diseaseTrait.getTrait()); return Optional.ofNullable(this.createDiseaseTrait(diseaseTrait)); }) .orElseGet(Optional::empty); } public Map<String, Object> deleteDiseaseTrait(Long diseaseTraitId) { log.info("Attempting to delete {}: {}", EntityType.DISEASE_TRAIT, diseaseTraitId); Map<String, Object> response = new HashMap<>(); return this.getDiseaseTrait(diseaseTraitId) .map(diseaseTrait -> { Collection<Study> diseaseTraitStudies = studyRepository.findByDiseaseTraitId(diseaseTraitId); if (diseaseTraitStudies.isEmpty()) { diseaseTraitRepository.delete(diseaseTraitId); log.info("Delete Trait: {} was successful", diseaseTraitId); response.put("status", "deleted"); } else { log.error("Trait: {} is in use, has {} studies, so cannot be deleted", diseaseTraitId, diseaseTraitStudies.size()); response.put("status", "DATA_IN_USE"); response.put("studyCount", diseaseTraitStudies.size()); } return response; }) .orElseGet(() -> { log.error("Unable to find Disease Trait: {}", diseaseTraitId); return response; }); } public List<DiseaseTrait> createDiseaseTraits(List<DiseaseTrait> diseaseTraits) { log.info("Creating {}: {}", EntityType.DISEASE_TRAIT, diseaseTraits.stream() .map(DiseaseTrait::getTrait) .collect(Collectors.toList())); diseaseTraits = diseaseTraitRepository.save(diseaseTraits); log.info("Bulk {} created", EntityType.DISEASE_TRAIT); return diseaseTraits; } @Cacheable(value = "diseaseTraitAnalysis", key = "#analysisId") public AnalysisCacheDto similaritySearch(List<AnalysisDTO> diseaseTraitAnalysisDTOS, String analysisId, double threshold) { LevenshteinDistance lv = new LevenshteinDistance(); CosineDistance cd = new CosineDistance(); List<DiseaseTrait> diseaseTraits = diseaseTraitRepository.findAll(); List<AnalysisDTO> analysisReport = new ArrayList<>(); diseaseTraitAnalysisDTOS .forEach(diseaseTraitAnalysisDTO -> diseaseTraits.forEach(diseaseTrait -> { String trait = diseaseTrait.getTrait(); String userTerm = diseaseTraitAnalysisDTO.getUserTerm(); double cosineDistance = cd.apply(userTerm, trait); double levenshteinDistance = ((double) lv.apply(userTerm, trait)) / Math.max(userTerm.length(), trait.length()); double cosineSimilarityPercent = Math.round((1 - cosineDistance) * 100); double levenshteinSimilarityPercent = Math.round((1 - levenshteinDistance) * 100); double chosen = Math.max(cosineSimilarityPercent, levenshteinSimilarityPercent); if (chosen >= threshold) { AnalysisDTO report = AnalysisDTO.builder() .userTerm(userTerm) .similarTerm(trait) .degree(chosen).build(); analysisReport.add(report); } } )); return AnalysisCacheDto.builder() .uniqueId(analysisId) .analysisResult(analysisReport).build(); } }
apache-2.0
yncxcw/PreemptYARN-2.7.1
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java
56218
/** * 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.yarn.server.nodemanager.containermanager.container; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.yarn.api.records.ContainerExitStatus; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.LocalResource; import org.apache.hadoop.yarn.api.records.LocalResourceVisibility; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.NMAuditLogger; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor.ExitCode; import org.apache.hadoop.yarn.server.nodemanager.NMAuditLogger.AuditConstants; import org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServicesEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServicesEventType; import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationContainerFinishedEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainersLauncherEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainersLauncherEventType; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.LocalResourceRequest; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationCleanupEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ContainerLocalizationRequestEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizationEventType; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.sharedcache.SharedCacheUploadEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.sharedcache.SharedCacheUploadEventType; import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerContainerFinishedEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainerStartMonitoringEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainerStopMonitoringEvent; import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics; import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService; import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService.RecoveredContainerStatus; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.state.InvalidStateTransitonException; import org.apache.hadoop.yarn.state.MultipleArcTransition; import org.apache.hadoop.yarn.state.SingleArcTransition; import org.apache.hadoop.yarn.state.StateMachine; import org.apache.hadoop.yarn.state.StateMachineFactory; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.SystemClock; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeContainerUpdate; import org.apache.hadoop.util.Shell; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Shell.ShellCommandExecutor; public class ContainerImpl implements Container { private final Lock readLock; private final Lock writeLock; private final Dispatcher dispatcher; private final NMStateStoreService stateStore; private final Credentials credentials; private final NodeManagerMetrics metrics; private final ContainerLaunchContext launchContext; private final ContainerTokenIdentifier containerTokenIdentifier; private final ContainerId containerId; private final Resource resource; private Resource currentResource; private final String user; private int exitCode = ContainerExitStatus.INVALID; private final StringBuilder diagnostics; private boolean wasLaunched; private long containerLaunchStartTime; private final Context context; private DockerCommandThread dockerUpdateThread = new DockerCommandThread(); private static Clock clock = new SystemClock(); /** The NM-wide configuration - not specific to this container */ private final Configuration daemonConf; private static final Log LOG = LogFactory.getLog(ContainerImpl.class); private final Map<LocalResourceRequest,List<String>> pendingResources = new HashMap<LocalResourceRequest,List<String>>(); private final Map<Path,List<String>> localizedResources = new HashMap<Path,List<String>>(); private final List<LocalResourceRequest> publicRsrcs = new ArrayList<LocalResourceRequest>(); private final List<LocalResourceRequest> privateRsrcs = new ArrayList<LocalResourceRequest>(); private final List<LocalResourceRequest> appRsrcs = new ArrayList<LocalResourceRequest>(); private final Map<LocalResourceRequest, Path> resourcesToBeUploaded = new ConcurrentHashMap<LocalResourceRequest, Path>(); private final Map<LocalResourceRequest, Boolean> resourcesUploadPolicies = new ConcurrentHashMap<LocalResourceRequest, Boolean>(); private final Set<Integer> cpuCores; // whether container has been recovered after a restart private RecoveredContainerStatus recoveredStatus = RecoveredContainerStatus.REQUESTED; // whether container was marked as killed after recovery private boolean recoveredAsKilled = false; public ContainerImpl(Context context,Configuration conf, Dispatcher dispatcher, NMStateStoreService stateStore, ContainerLaunchContext launchContext, Credentials creds, NodeManagerMetrics metrics, ContainerTokenIdentifier containerTokenIdentifier,Set<Integer> cpuCores) { this.daemonConf = conf; this.dispatcher = dispatcher; this.stateStore = stateStore; this.launchContext = launchContext; this.containerTokenIdentifier = containerTokenIdentifier; this.containerId = containerTokenIdentifier.getContainerID(); this.resource = containerTokenIdentifier.getResource(); this.currentResource = resource; this.diagnostics = new StringBuilder(); this.credentials = creds; this.metrics = metrics; user = containerTokenIdentifier.getApplicationSubmitter(); ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); this.readLock = readWriteLock.readLock(); this.writeLock = readWriteLock.writeLock(); this.cpuCores = cpuCores; this.context = context; stateMachine = stateMachineFactory.make(this); } // constructor for a recovered container public ContainerImpl(Context context,Configuration conf, Dispatcher dispatcher, NMStateStoreService stateStore, ContainerLaunchContext launchContext, Credentials creds, NodeManagerMetrics metrics, ContainerTokenIdentifier containerTokenIdentifier, RecoveredContainerStatus recoveredStatus, int exitCode, String diagnostics, boolean wasKilled, Set<Integer> cpuCores) { this(context,conf, dispatcher, stateStore, launchContext, creds, metrics, containerTokenIdentifier,cpuCores); this.recoveredStatus = recoveredStatus; this.exitCode = exitCode; this.recoveredAsKilled = wasKilled; this.diagnostics.append(diagnostics); } private static final ContainerDiagnosticsUpdateTransition UPDATE_DIAGNOSTICS_TRANSITION = new ContainerDiagnosticsUpdateTransition(); // State Machine for each container. private static StateMachineFactory <ContainerImpl, ContainerState, ContainerEventType, ContainerEvent> stateMachineFactory = new StateMachineFactory<ContainerImpl, ContainerState, ContainerEventType, ContainerEvent>(ContainerState.NEW) // From NEW State .addTransition(ContainerState.NEW, EnumSet.of(ContainerState.LOCALIZING, ContainerState.LOCALIZED, ContainerState.LOCALIZATION_FAILED, ContainerState.DONE), ContainerEventType.INIT_CONTAINER, new RequestResourcesTransition()) .addTransition(ContainerState.NEW, ContainerState.NEW, ContainerEventType.UPDATE_DIAGNOSTICS_MSG, UPDATE_DIAGNOSTICS_TRANSITION) .addTransition(ContainerState.NEW, ContainerState.DONE, ContainerEventType.KILL_CONTAINER, new KillOnNewTransition()) // From LOCALIZING State .addTransition(ContainerState.LOCALIZING, EnumSet.of(ContainerState.LOCALIZING, ContainerState.LOCALIZED), ContainerEventType.RESOURCE_LOCALIZED, new LocalizedTransition()) .addTransition(ContainerState.LOCALIZING, ContainerState.LOCALIZATION_FAILED, ContainerEventType.RESOURCE_FAILED, new ResourceFailedTransition()) .addTransition(ContainerState.LOCALIZING, ContainerState.LOCALIZING, ContainerEventType.UPDATE_DIAGNOSTICS_MSG, UPDATE_DIAGNOSTICS_TRANSITION) .addTransition(ContainerState.LOCALIZING, ContainerState.KILLING, ContainerEventType.KILL_CONTAINER, new KillDuringLocalizationTransition()) // From LOCALIZATION_FAILED State .addTransition(ContainerState.LOCALIZATION_FAILED, ContainerState.DONE, ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP, new LocalizationFailedToDoneTransition()) .addTransition(ContainerState.LOCALIZATION_FAILED, ContainerState.LOCALIZATION_FAILED, ContainerEventType.UPDATE_DIAGNOSTICS_MSG, UPDATE_DIAGNOSTICS_TRANSITION) // container not launched so kill is a no-op .addTransition(ContainerState.LOCALIZATION_FAILED, ContainerState.LOCALIZATION_FAILED, ContainerEventType.KILL_CONTAINER) // container cleanup triggers a release of all resources // regardless of whether they were localized or not // LocalizedResource handles release event in all states .addTransition(ContainerState.LOCALIZATION_FAILED, ContainerState.LOCALIZATION_FAILED, ContainerEventType.RESOURCE_LOCALIZED) .addTransition(ContainerState.LOCALIZATION_FAILED, ContainerState.LOCALIZATION_FAILED, ContainerEventType.RESOURCE_FAILED) // From LOCALIZED State .addTransition(ContainerState.LOCALIZED, ContainerState.RUNNING, ContainerEventType.CONTAINER_LAUNCHED, new LaunchTransition()) .addTransition(ContainerState.LOCALIZED, ContainerState.EXITED_WITH_FAILURE, ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, new ExitedWithFailureTransition(true)) .addTransition(ContainerState.LOCALIZED, ContainerState.LOCALIZED, ContainerEventType.UPDATE_DIAGNOSTICS_MSG, UPDATE_DIAGNOSTICS_TRANSITION) .addTransition(ContainerState.LOCALIZED, ContainerState.KILLING, ContainerEventType.KILL_CONTAINER, new KillTransition()) // From RUNNING State .addTransition(ContainerState.RUNNING, ContainerState.EXITED_WITH_SUCCESS, ContainerEventType.CONTAINER_EXITED_WITH_SUCCESS, new ExitedWithSuccessTransition(true)) .addTransition(ContainerState.RUNNING, ContainerState.RUNNING, ContainerEventType.RESOURCE_UPDATE, new ResourceUpdateTransition()) .addTransition(ContainerState.RUNNING, ContainerState.EXITED_WITH_FAILURE, ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, new ExitedWithFailureTransition(true)) .addTransition(ContainerState.RUNNING, ContainerState.RUNNING, ContainerEventType.UPDATE_DIAGNOSTICS_MSG, UPDATE_DIAGNOSTICS_TRANSITION) .addTransition(ContainerState.RUNNING, ContainerState.KILLING, ContainerEventType.KILL_CONTAINER, new KillTransition()) .addTransition(ContainerState.RUNNING, ContainerState.EXITED_WITH_FAILURE, ContainerEventType.CONTAINER_KILLED_ON_REQUEST, new KilledExternallyTransition()) // From CONTAINER_EXITED_WITH_SUCCESS State .addTransition(ContainerState.EXITED_WITH_SUCCESS, ContainerState.DONE, ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP, new ExitedWithSuccessToDoneTransition()) .addTransition(ContainerState.EXITED_WITH_SUCCESS, ContainerState.EXITED_WITH_SUCCESS, ContainerEventType.UPDATE_DIAGNOSTICS_MSG, UPDATE_DIAGNOSTICS_TRANSITION) .addTransition(ContainerState.EXITED_WITH_SUCCESS, ContainerState.EXITED_WITH_SUCCESS, ContainerEventType.KILL_CONTAINER) // From EXITED_WITH_FAILURE State .addTransition(ContainerState.EXITED_WITH_FAILURE, ContainerState.DONE, ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP, new ExitedWithFailureToDoneTransition()) .addTransition(ContainerState.EXITED_WITH_FAILURE, ContainerState.EXITED_WITH_FAILURE, ContainerEventType.UPDATE_DIAGNOSTICS_MSG, UPDATE_DIAGNOSTICS_TRANSITION) .addTransition(ContainerState.EXITED_WITH_FAILURE, ContainerState.EXITED_WITH_FAILURE, ContainerEventType.KILL_CONTAINER) // From KILLING State. .addTransition(ContainerState.KILLING, ContainerState.CONTAINER_CLEANEDUP_AFTER_KILL, ContainerEventType.CONTAINER_KILLED_ON_REQUEST, new ContainerKilledTransition()) .addTransition(ContainerState.KILLING, ContainerState.KILLING, ContainerEventType.RESOURCE_LOCALIZED, new LocalizedResourceDuringKillTransition()) .addTransition(ContainerState.KILLING, ContainerState.KILLING, ContainerEventType.RESOURCE_FAILED) .addTransition(ContainerState.KILLING, ContainerState.KILLING, ContainerEventType.UPDATE_DIAGNOSTICS_MSG, UPDATE_DIAGNOSTICS_TRANSITION) .addTransition(ContainerState.KILLING, ContainerState.KILLING, ContainerEventType.KILL_CONTAINER) .addTransition(ContainerState.KILLING, ContainerState.EXITED_WITH_SUCCESS, ContainerEventType.CONTAINER_EXITED_WITH_SUCCESS, new ExitedWithSuccessTransition(false)) .addTransition(ContainerState.KILLING, ContainerState.EXITED_WITH_FAILURE, ContainerEventType.CONTAINER_EXITED_WITH_FAILURE, new ExitedWithFailureTransition(false)) .addTransition(ContainerState.KILLING, ContainerState.DONE, ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP, new KillingToDoneTransition()) // Handle a launched container during killing stage is a no-op // as cleanup container is always handled after launch container event // in the container launcher .addTransition(ContainerState.KILLING, ContainerState.KILLING, ContainerEventType.CONTAINER_LAUNCHED) // From CONTAINER_CLEANEDUP_AFTER_KILL State. .addTransition(ContainerState.CONTAINER_CLEANEDUP_AFTER_KILL, ContainerState.DONE, ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP, new ContainerCleanedupAfterKillToDoneTransition()) .addTransition(ContainerState.CONTAINER_CLEANEDUP_AFTER_KILL, ContainerState.CONTAINER_CLEANEDUP_AFTER_KILL, ContainerEventType.UPDATE_DIAGNOSTICS_MSG, UPDATE_DIAGNOSTICS_TRANSITION) .addTransition(ContainerState.CONTAINER_CLEANEDUP_AFTER_KILL, ContainerState.CONTAINER_CLEANEDUP_AFTER_KILL, EnumSet.of(ContainerEventType.KILL_CONTAINER, ContainerEventType.CONTAINER_EXITED_WITH_SUCCESS, ContainerEventType.CONTAINER_EXITED_WITH_FAILURE)) // From DONE .addTransition(ContainerState.DONE, ContainerState.DONE, ContainerEventType.KILL_CONTAINER) .addTransition(ContainerState.DONE, ContainerState.DONE, ContainerEventType.INIT_CONTAINER) .addTransition(ContainerState.DONE, ContainerState.DONE, ContainerEventType.UPDATE_DIAGNOSTICS_MSG, UPDATE_DIAGNOSTICS_TRANSITION) // This transition may result when // we notify container of failed localization if localizer thread (for // that container) fails for some reason .addTransition(ContainerState.DONE, ContainerState.DONE, EnumSet.of(ContainerEventType.RESOURCE_FAILED, ContainerEventType.CONTAINER_EXITED_WITH_SUCCESS, ContainerEventType.CONTAINER_EXITED_WITH_FAILURE)) // create the topology tables .installTopology(); private final StateMachine<ContainerState, ContainerEventType, ContainerEvent> stateMachine; public org.apache.hadoop.yarn.api.records.ContainerState getCurrentState() { switch (stateMachine.getCurrentState()) { case NEW: case LOCALIZING: case LOCALIZATION_FAILED: case LOCALIZED: case RUNNING: case EXITED_WITH_SUCCESS: case EXITED_WITH_FAILURE: case KILLING: case CONTAINER_CLEANEDUP_AFTER_KILL: case CONTAINER_RESOURCES_CLEANINGUP: return org.apache.hadoop.yarn.api.records.ContainerState.RUNNING; case DONE: default: return org.apache.hadoop.yarn.api.records.ContainerState.COMPLETE; } } @Override public String getUser() { this.readLock.lock(); try { return this.user; } finally { this.readLock.unlock(); } } @Override public Map<Path,List<String>> getLocalizedResources() { this.readLock.lock(); try { if (ContainerState.LOCALIZED == getContainerState()) { return localizedResources; } else { return null; } } finally { this.readLock.unlock(); } } @Override public Credentials getCredentials() { this.readLock.lock(); try { return credentials; } finally { this.readLock.unlock(); } } @Override public ContainerState getContainerState() { this.readLock.lock(); try { return stateMachine.getCurrentState(); } finally { this.readLock.unlock(); } } @Override public ContainerLaunchContext getLaunchContext() { this.readLock.lock(); try { return launchContext; } finally { this.readLock.unlock(); } } @Override public ContainerStatus cloneAndGetContainerStatus() { this.readLock.lock(); try { ContainerStatus containerStatus = BuilderUtils.newContainerStatus(this.containerId, getCurrentState(), diagnostics.toString(), exitCode); containerStatus.setCpuCores(cpuCores); return containerStatus; } finally { this.readLock.unlock(); } } @Override public NMContainerStatus getNMContainerStatus() { this.readLock.lock(); try { return NMContainerStatus.newInstance(this.containerId, getCurrentState(), getResource(), diagnostics.toString(), exitCode, containerTokenIdentifier.getPriority(), containerTokenIdentifier.getCreationTime()); } finally { this.readLock.unlock(); } } @Override public ContainerId getContainerId() { return this.containerId; } @Override public Resource getResource() { return this.resource; } @Override public ContainerTokenIdentifier getContainerTokenIdentifier() { this.readLock.lock(); try { return this.containerTokenIdentifier; } finally { this.readLock.unlock(); } } @SuppressWarnings("unchecked") private void sendFinishedEvents() { // Inform the application @SuppressWarnings("rawtypes") EventHandler eventHandler = dispatcher.getEventHandler(); eventHandler.handle(new ApplicationContainerFinishedEvent(containerId)); // Remove the container from the resource-monitor eventHandler.handle(new ContainerStopMonitoringEvent(containerId)); // Tell the logService too eventHandler.handle(new LogHandlerContainerFinishedEvent( containerId, exitCode)); } @SuppressWarnings("unchecked") // dispatcher not typed private void sendLaunchEvent() { ContainersLauncherEventType launcherEvent = ContainersLauncherEventType.LAUNCH_CONTAINER; if (recoveredStatus == RecoveredContainerStatus.LAUNCHED) { // try to recover a container that was previously launched launcherEvent = ContainersLauncherEventType.RECOVER_CONTAINER; } containerLaunchStartTime = clock.getTime(); dispatcher.getEventHandler().handle( new ContainersLauncherEvent(this, launcherEvent)); } // Inform the ContainersMonitor to start monitoring the container's // resource usage. @SuppressWarnings("unchecked") // dispatcher not typed private void sendContainerMonitorStartEvent() { long pmemBytes = getResource().getMemory() * 1024 * 1024L; float pmemRatio = daemonConf.getFloat( YarnConfiguration.NM_VMEM_PMEM_RATIO, YarnConfiguration.DEFAULT_NM_VMEM_PMEM_RATIO); long vmemBytes = (long) (pmemRatio * pmemBytes); int cpuVcores = getResource().getVirtualCores(); dispatcher.getEventHandler().handle( new ContainerStartMonitoringEvent(containerId, vmemBytes, pmemBytes, cpuVcores)); } private void addDiagnostics(String... diags) { for (String s : diags) { this.diagnostics.append(s); } try { stateStore.storeContainerDiagnostics(containerId, diagnostics); } catch (IOException e) { LOG.warn("Unable to update diagnostics in state store for " + containerId, e); } } @SuppressWarnings("unchecked") // dispatcher not typed public void cleanup() { Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrc = new HashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>(); if (!publicRsrcs.isEmpty()) { rsrc.put(LocalResourceVisibility.PUBLIC, publicRsrcs); } if (!privateRsrcs.isEmpty()) { rsrc.put(LocalResourceVisibility.PRIVATE, privateRsrcs); } if (!appRsrcs.isEmpty()) { rsrc.put(LocalResourceVisibility.APPLICATION, appRsrcs); } dispatcher.getEventHandler().handle( new ContainerLocalizationCleanupEvent(this, rsrc)); } static class ContainerTransition implements SingleArcTransition<ContainerImpl, ContainerEvent> { @Override public void transition(ContainerImpl container, ContainerEvent event) { // Just drain the event and change the state. } } /** * State transition when a NEW container receives the INIT_CONTAINER * message. * * If there are resources to localize, sends a * ContainerLocalizationRequest (INIT_CONTAINER_RESOURCES) * to the ResourceLocalizationManager and enters LOCALIZING state. * * If there are no resources to localize, sends LAUNCH_CONTAINER event * and enters LOCALIZED state directly. * * If there are any invalid resources specified, enters LOCALIZATION_FAILED * directly. */ @SuppressWarnings("unchecked") // dispatcher not typed static class RequestResourcesTransition implements MultipleArcTransition<ContainerImpl,ContainerEvent,ContainerState> { @Override public ContainerState transition(ContainerImpl container, ContainerEvent event) { if (container.recoveredStatus == RecoveredContainerStatus.COMPLETED) { container.sendFinishedEvents(); return ContainerState.DONE; } else if (container.recoveredAsKilled && container.recoveredStatus == RecoveredContainerStatus.REQUESTED) { // container was killed but never launched container.metrics.killedContainer(); NMAuditLogger.logSuccess(container.user, AuditConstants.FINISH_KILLED_CONTAINER, "ContainerImpl", container.containerId.getApplicationAttemptId().getApplicationId(), container.containerId); container.metrics.releaseContainer(container.resource); container.sendFinishedEvents(); return ContainerState.DONE; } final ContainerLaunchContext ctxt = container.launchContext; container.metrics.initingContainer(); container.dispatcher.getEventHandler().handle(new AuxServicesEvent (AuxServicesEventType.CONTAINER_INIT, container)); // Inform the AuxServices about the opaque serviceData Map<String,ByteBuffer> csd = ctxt.getServiceData(); if (csd != null) { // This can happen more than once per Application as each container may // have distinct service data for (Map.Entry<String,ByteBuffer> service : csd.entrySet()) { container.dispatcher.getEventHandler().handle( new AuxServicesEvent(AuxServicesEventType.APPLICATION_INIT, container.user, container.containerId .getApplicationAttemptId().getApplicationId(), service.getKey().toString(), service.getValue())); } } // Send requests for public, private resources Map<String,LocalResource> cntrRsrc = ctxt.getLocalResources(); if (!cntrRsrc.isEmpty()) { try { for (Map.Entry<String,LocalResource> rsrc : cntrRsrc.entrySet()) { try { LocalResourceRequest req = new LocalResourceRequest(rsrc.getValue()); List<String> links = container.pendingResources.get(req); if (links == null) { links = new ArrayList<String>(); container.pendingResources.put(req, links); } links.add(rsrc.getKey()); storeSharedCacheUploadPolicy(container, req, rsrc.getValue() .getShouldBeUploadedToSharedCache()); switch (rsrc.getValue().getVisibility()) { case PUBLIC: container.publicRsrcs.add(req); break; case PRIVATE: container.privateRsrcs.add(req); break; case APPLICATION: container.appRsrcs.add(req); break; } } catch (URISyntaxException e) { LOG.info("Got exception parsing " + rsrc.getKey() + " and value " + rsrc.getValue()); throw e; } } } catch (URISyntaxException e) { // malformed resource; abort container launch LOG.warn("Failed to parse resource-request", e); container.cleanup(); container.metrics.endInitingContainer(); return ContainerState.LOCALIZATION_FAILED; } Map<LocalResourceVisibility, Collection<LocalResourceRequest>> req = new LinkedHashMap<LocalResourceVisibility, Collection<LocalResourceRequest>>(); if (!container.publicRsrcs.isEmpty()) { req.put(LocalResourceVisibility.PUBLIC, container.publicRsrcs); } if (!container.privateRsrcs.isEmpty()) { req.put(LocalResourceVisibility.PRIVATE, container.privateRsrcs); } if (!container.appRsrcs.isEmpty()) { req.put(LocalResourceVisibility.APPLICATION, container.appRsrcs); } container.dispatcher.getEventHandler().handle( new ContainerLocalizationRequestEvent(container, req)); return ContainerState.LOCALIZING; } else { container.sendLaunchEvent(); container.metrics.endInitingContainer(); return ContainerState.LOCALIZED; } } } /** * Store the resource's shared cache upload policies * Given LocalResourceRequest can be shared across containers in * LocalResourcesTrackerImpl, we preserve the upload policies here. * In addition, it is possible for the application to create several * "identical" LocalResources as part of * ContainerLaunchContext.setLocalResources with different symlinks. * There is a corner case where these "identical" local resources have * different upload policies. For that scenario, upload policy will be set to * true as long as there is at least one LocalResource entry with * upload policy set to true. */ private static void storeSharedCacheUploadPolicy(ContainerImpl container, LocalResourceRequest resourceRequest, Boolean uploadPolicy) { Boolean storedUploadPolicy = container.resourcesUploadPolicies.get(resourceRequest); if (storedUploadPolicy == null || (!storedUploadPolicy && uploadPolicy)) { container.resourcesUploadPolicies.put(resourceRequest, uploadPolicy); } } /** * Transition when one of the requested resources for this container * has been successfully localized. */ static class LocalizedTransition implements MultipleArcTransition<ContainerImpl,ContainerEvent,ContainerState> { @SuppressWarnings("unchecked") @Override public ContainerState transition(ContainerImpl container, ContainerEvent event) { ContainerResourceLocalizedEvent rsrcEvent = (ContainerResourceLocalizedEvent) event; LocalResourceRequest resourceRequest = rsrcEvent.getResource(); Path location = rsrcEvent.getLocation(); List<String> syms = container.pendingResources.remove(resourceRequest); if (null == syms) { LOG.warn("Localized unknown resource " + resourceRequest + " for container " + container.containerId); assert false; // fail container? return ContainerState.LOCALIZING; } container.localizedResources.put(location, syms); // check to see if this resource should be uploaded to the shared cache // as well if (shouldBeUploadedToSharedCache(container, resourceRequest)) { container.resourcesToBeUploaded.put(resourceRequest, location); } if (!container.pendingResources.isEmpty()) { return ContainerState.LOCALIZING; } container.dispatcher.getEventHandler().handle( new ContainerLocalizationEvent(LocalizationEventType. CONTAINER_RESOURCES_LOCALIZED, container)); container.sendLaunchEvent(); container.metrics.endInitingContainer(); // If this is a recovered container that has already launched, skip // uploading resources to the shared cache. We do this to avoid uploading // the same resources multiple times. The tradeoff is that in the case of // a recovered container, there is a chance that resources don't get // uploaded into the shared cache. This is OK because resources are not // acknowledged by the SCM until they have been uploaded by the node // manager. if (container.recoveredStatus != RecoveredContainerStatus.LAUNCHED && container.recoveredStatus != RecoveredContainerStatus.COMPLETED) { // kick off uploads to the shared cache container.dispatcher.getEventHandler().handle( new SharedCacheUploadEvent(container.resourcesToBeUploaded, container .getLaunchContext(), container.getUser(), SharedCacheUploadEventType.UPLOAD)); } return ContainerState.LOCALIZED; } } /** * Transition from LOCALIZED state to RUNNING state upon receiving * a CONTAINER_LAUNCHED event */ static class LaunchTransition extends ContainerTransition { @SuppressWarnings("unchecked") @Override public void transition(ContainerImpl container, ContainerEvent event) { container.sendContainerMonitorStartEvent(); container.metrics.runningContainer(); container.wasLaunched = true; long duration = clock.getTime() - container.containerLaunchStartTime; container.metrics.addContainerLaunchDuration(duration); //we start docker container update thread here container.dockerUpdateThread.start(); if (container.recoveredAsKilled) { LOG.info("Killing " + container.containerId + " due to recovered as killed"); container.addDiagnostics("Container recovered as killed.\n"); container.dispatcher.getEventHandler().handle( new ContainersLauncherEvent(container, ContainersLauncherEventType.CLEANUP_CONTAINER)); } } } /** * Transition from RUNNINH state to RUNNING state upon receiving a * RESOURCE_UPDATE */ static class ResourceUpdateTransition extends ContainerTransition { @SuppressWarnings("unchecked") @Override public void transition(ContainerImpl container, ContainerEvent event) { ContainerResourceUpdate updateEvent = (ContainerResourceUpdate) event; LOG.info("container"+event.getContainerID()+"receive resource update event" +"memory"+updateEvent.getNodeContainerUpdate().getMemory() +"cores"+updateEvent.getNodeContainerUpdate().getCores() +"suspend"+updateEvent.getNodeContainerUpdate().getSuspend() +"resume"+updateEvent.getNodeContainerUpdate().getResume()); container.ProcessResourceUpdate(updateEvent.getNodeContainerUpdate()); } } /** * TO launch thread to process contaienr udpate event * @param nodeContainerUpdate */ private class DockerCommandThread extends Thread{ Queue<Integer> memoryUpdateActorList = new LinkedList<Integer>(); Queue<Integer> quotaUpdateActorList = new LinkedList<Integer>(); Queue<Set<Integer>> cpuUpdateActorList = new LinkedList<Set<Integer>>(); public DockerCommandThread(){ } private void DockerCommandCpuQuota(Integer quota){ List<String> commandPrefix = new ArrayList<String>(); commandPrefix.add("docker"); commandPrefix.add("update"); List<String> commandQuota = new ArrayList<String>(); commandQuota.addAll(commandPrefix); commandQuota.add("--cpu-quota"); commandQuota.add(quota.toString()); commandQuota.add(containerId.toString()); String[] commandArrayQuota = commandQuota.toArray(new String[commandQuota.size()]); this.runDockerUpdateCommand(commandArrayQuota); } private void DockerCommandCpuSet(Set<Integer> cores){ List<String> commandPrefix = new ArrayList<String>(); commandPrefix.add("docker"); commandPrefix.add("update"); List<String> commandCores = new ArrayList<String>(); commandCores.addAll(commandPrefix); commandCores.add("--cpuset-cpus"); int index = 0; String coresStr=new String(); for(Integer core : cores){ coresStr=coresStr+core.toString(); index++; if(index < cores.size()){ coresStr=coresStr+","; } } commandCores.add(coresStr); commandCores.add(containerId.toString()); String[] commandArrayCores = commandCores.toArray(new String[commandCores.size()]); this.runDockerUpdateCommand(commandArrayCores); } private void DockerCommandMeory(Integer memory){ List<String> commandPrefix = new ArrayList<String>(); commandPrefix.add("docker"); commandPrefix.add("update"); List<String> commandMemory = new ArrayList<String>(); commandMemory.addAll(commandPrefix); commandMemory.add("--memory"); commandMemory.add(memory.toString()+"m"); commandMemory.add(containerId.toString()); String[] commandArrayMemory = commandMemory.toArray(new String[commandMemory.size()]); this.runDockerUpdateCommand(commandArrayMemory); } private int runDockerUpdateCommand(String[] command){ String commandString=new String(); for(String c : command){ commandString += c; commandString += " "; } LOG.info("run docker commands:"+commandString); ShellCommandExecutor shExec = null; int count = 10; while(count > 0){ //we try 10 times if fails due to device busy try { shExec = new ShellCommandExecutor(command); shExec.execute(); } catch (IOException e) { if (null == shExec) { return -1; } int exitCode = shExec.getExitCode(); if (exitCode != ExitCode.FORCE_KILLED.getExitCode() && exitCode != ExitCode.TERMINATED.getExitCode()) { LOG.warn("Exception from Docker update with container ID: " + containerId + " and exit code: " + exitCode, e); } count--; continue; } finally { if (shExec != null) { shExec.close(); } } LOG.info("command execution successfully"); break; } if(count > 0){ LOG.info("command execution successfully and commands updates for"+count+" times"); }else{ LOG.info("command execution fails"); } return 0; } @Override public void run(){ LOG.info("thread entered for container "+getContainerId()+" current state is "+stateMachine.getCurrentState()); while(stateMachine.getCurrentState() == ContainerState.RUNNING){ //LOG.info("thread loop for container "+getContainerId()+" memorysize "+memoryUpdateActorList.size() // +" cpusize "+cpuUpdateActorList.size()); synchronized(quotaUpdateActorList){ //first check the quota list if it is empty if(quotaUpdateActorList.size() > 0){ LOG.info("quota size "+quotaUpdateActorList.size()); int quota = quotaUpdateActorList.poll(); DockerCommandCpuQuota(quota); continue; } } synchronized(cpuUpdateActorList){ //then update cpuset if(cpuUpdateActorList.size( )> 0){ LOG.info("cpu size "+cpuUpdateActorList.size()); Set<Integer> cpuSet = cpuUpdateActorList.poll(); DockerCommandCpuSet(cpuSet); continue; } } synchronized(memoryUpdateActorList){ //finally we update memory if(memoryUpdateActorList.size() > 0){ LOG.info("memory size "+memoryUpdateActorList.size()); int memory = memoryUpdateActorList.poll(); DockerCommandMeory(memory); continue; } } //if we come here it means we need to sleep for 3s try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } LOG.info("thread ended for container "+getContainerId()+" the final state is "+stateMachine.getCurrentState()); } public void ProcessNodeContainerUpdate(NodeContainerUpdate nodeContainerUpdate) { //if this is a resumed container boolean resumed = nodeContainerUpdate.getResume(); boolean quotaFreeze = false; //we fisrt update cpu cores Integer targetCores = nodeContainerUpdate.getCores(); //then we update resource requirement, first we update cpu set Set<Integer> cores = context.getCoresManager().resetCores(containerId,targetCores); LOG.info("node container update cores"+cores); //all cores are preempted if(cores.size() == 0){ //in this case, we run the docker on core 0 cores.add(0); //we will not resume its all capacity quotaFreeze = true; } synchronized(cpuUpdateActorList){ //then update cpuset if(cpuUpdateActorList.size( )> 0){ cpuUpdateActorList.clear(); } cpuUpdateActorList.add(cores); } //we then update cpuset, we only free container when all the resource has been deprived if(quotaFreeze){ synchronized(quotaUpdateActorList){ //first check the quota list if it is empty if(quotaUpdateActorList.size() > 0){ quotaUpdateActorList.clear(); } quotaUpdateActorList.add(1000); } }else if(resumed){ synchronized(quotaUpdateActorList){ //first check the quota list if it is empty if(quotaUpdateActorList.size() > 0){ quotaUpdateActorList.clear(); } quotaUpdateActorList.add(-1); } } //we then update memory usage List<Integer> toAdded = new ArrayList<Integer>(); Integer currentMemory = currentResource.getMemory(); Integer targetMemory = nodeContainerUpdate.getMemory(); //the minimum memory for a container if(targetMemory < 128){ targetMemory = 128; } if(targetMemory < currentMemory){ while(currentMemory > targetMemory){ if(currentMemory > 1024){ currentMemory -= 1024; }else{ currentMemory /=2; } toAdded.add(currentMemory); } toAdded.add(targetMemory); LOG.info("node container update memory"+targetMemory); }else{ toAdded.add(targetMemory); LOG.info("node container update memory"+targetMemory); } synchronized(memoryUpdateActorList){ //finally we update memory if(memoryUpdateActorList.size() > 0){ memoryUpdateActorList.clear(); } memoryUpdateActorList.addAll(toAdded); } } } private void ProcessResourceUpdate(NodeContainerUpdate nodeContainerUpdate){ LOG.info("process resource update: container "+getContainerId()+" cores "+nodeContainerUpdate.getCores() +" memory "+nodeContainerUpdate.getMemory()); dockerUpdateThread.ProcessNodeContainerUpdate(nodeContainerUpdate);; } /** * Transition from RUNNING or KILLING state to EXITED_WITH_SUCCESS state * upon EXITED_WITH_SUCCESS message. */ @SuppressWarnings("unchecked") // dispatcher not typed static class ExitedWithSuccessTransition extends ContainerTransition { boolean clCleanupRequired; public ExitedWithSuccessTransition(boolean clCleanupRequired) { this.clCleanupRequired = clCleanupRequired; } @Override public void transition(ContainerImpl container, ContainerEvent event) { // Set exit code to 0 on success container.exitCode = 0; // TODO: Add containerWorkDir to the deletion service. if (clCleanupRequired) { container.dispatcher.getEventHandler().handle( new ContainersLauncherEvent(container, ContainersLauncherEventType.CLEANUP_CONTAINER)); } container.cleanup(); } } /** * Transition to EXITED_WITH_FAILURE state upon * CONTAINER_EXITED_WITH_FAILURE state. **/ @SuppressWarnings("unchecked") // dispatcher not typed static class ExitedWithFailureTransition extends ContainerTransition { boolean clCleanupRequired; public ExitedWithFailureTransition(boolean clCleanupRequired) { this.clCleanupRequired = clCleanupRequired; } @Override public void transition(ContainerImpl container, ContainerEvent event) { ContainerExitEvent exitEvent = (ContainerExitEvent) event; container.exitCode = exitEvent.getExitCode(); if (exitEvent.getDiagnosticInfo() != null) { container.addDiagnostics(exitEvent.getDiagnosticInfo(), "\n"); } // TODO: Add containerWorkDir to the deletion service. // TODO: Add containerOuputDir to the deletion service. if (clCleanupRequired) { container.dispatcher.getEventHandler().handle( new ContainersLauncherEvent(container, ContainersLauncherEventType.CLEANUP_CONTAINER)); } container.cleanup(); } } /** * Transition to EXITED_WITH_FAILURE upon receiving KILLED_ON_REQUEST */ static class KilledExternallyTransition extends ExitedWithFailureTransition { KilledExternallyTransition() { super(true); } @Override public void transition(ContainerImpl container, ContainerEvent event) { super.transition(container, event); container.addDiagnostics("Killed by external signal\n"); } } /** * Transition from LOCALIZING to LOCALIZATION_FAILED upon receiving * RESOURCE_FAILED event. */ static class ResourceFailedTransition implements SingleArcTransition<ContainerImpl, ContainerEvent> { @Override public void transition(ContainerImpl container, ContainerEvent event) { ContainerResourceFailedEvent rsrcFailedEvent = (ContainerResourceFailedEvent) event; container.addDiagnostics(rsrcFailedEvent.getDiagnosticMessage(), "\n"); // Inform the localizer to decrement reference counts and cleanup // resources. container.cleanup(); container.metrics.endInitingContainer(); } } /** * Transition from LOCALIZING to KILLING upon receiving * KILL_CONTAINER event. */ static class KillDuringLocalizationTransition implements SingleArcTransition<ContainerImpl, ContainerEvent> { @Override public void transition(ContainerImpl container, ContainerEvent event) { // Inform the localizer to decrement reference counts and cleanup // resources. container.cleanup(); container.metrics.endInitingContainer(); ContainerKillEvent killEvent = (ContainerKillEvent) event; container.exitCode = killEvent.getContainerExitStatus(); container.addDiagnostics(killEvent.getDiagnostic(), "\n"); container.addDiagnostics("Container is killed before being launched.\n"); } } /** * Remain in KILLING state when receiving a RESOURCE_LOCALIZED request * while in the process of killing. */ static class LocalizedResourceDuringKillTransition implements SingleArcTransition<ContainerImpl, ContainerEvent> { @Override public void transition(ContainerImpl container, ContainerEvent event) { ContainerResourceLocalizedEvent rsrcEvent = (ContainerResourceLocalizedEvent) event; List<String> syms = container.pendingResources.remove(rsrcEvent.getResource()); if (null == syms) { LOG.warn("Localized unknown resource " + rsrcEvent.getResource() + " for container " + container.containerId); assert false; // fail container? return; } container.localizedResources.put(rsrcEvent.getLocation(), syms); } } /** * Transitions upon receiving KILL_CONTAINER: * - LOCALIZED -> KILLING * - RUNNING -> KILLING */ @SuppressWarnings("unchecked") // dispatcher not typed static class KillTransition implements SingleArcTransition<ContainerImpl, ContainerEvent> { @Override public void transition(ContainerImpl container, ContainerEvent event) { // Kill the process/process-grp container.dispatcher.getEventHandler().handle( new ContainersLauncherEvent(container, ContainersLauncherEventType.CLEANUP_CONTAINER)); ContainerKillEvent killEvent = (ContainerKillEvent) event; container.addDiagnostics(killEvent.getDiagnostic(), "\n"); container.exitCode = killEvent.getContainerExitStatus(); } } /** * Transition from KILLING to CONTAINER_CLEANEDUP_AFTER_KILL * upon receiving CONTAINER_KILLED_ON_REQUEST. */ static class ContainerKilledTransition implements SingleArcTransition<ContainerImpl, ContainerEvent> { @Override public void transition(ContainerImpl container, ContainerEvent event) { ContainerExitEvent exitEvent = (ContainerExitEvent) event; if (container.hasDefaultExitCode()) { container.exitCode = exitEvent.getExitCode(); } if (exitEvent.getDiagnosticInfo() != null) { container.addDiagnostics(exitEvent.getDiagnosticInfo(), "\n"); } // The process/process-grp is killed. Decrement reference counts and // cleanup resources container.cleanup(); } } /** * Handle the following transitions: * - {LOCALIZATION_FAILED, EXITED_WITH_SUCCESS, EXITED_WITH_FAILURE, * KILLING, CONTAINER_CLEANEDUP_AFTER_KILL} * -> DONE upon CONTAINER_RESOURCES_CLEANEDUP */ static class ContainerDoneTransition implements SingleArcTransition<ContainerImpl, ContainerEvent> { @Override @SuppressWarnings("unchecked") public void transition(ContainerImpl container, ContainerEvent event) { container.metrics.releaseContainer(container.resource); container.sendFinishedEvents(); //if the current state is NEW it means the CONTAINER_INIT was never // sent for the event, thus no need to send the CONTAINER_STOP if (container.getCurrentState() != org.apache.hadoop.yarn.api.records.ContainerState.NEW) { container.dispatcher.getEventHandler().handle(new AuxServicesEvent (AuxServicesEventType.CONTAINER_STOP, container)); } } } /** * Handle the following transition: * - NEW -> DONE upon KILL_CONTAINER */ static class KillOnNewTransition extends ContainerDoneTransition { @Override public void transition(ContainerImpl container, ContainerEvent event) { ContainerKillEvent killEvent = (ContainerKillEvent) event; container.exitCode = killEvent.getContainerExitStatus(); container.addDiagnostics(killEvent.getDiagnostic(), "\n"); container.addDiagnostics("Container is killed before being launched.\n"); container.metrics.killedContainer(); NMAuditLogger.logSuccess(container.user, AuditConstants.FINISH_KILLED_CONTAINER, "ContainerImpl", container.containerId.getApplicationAttemptId().getApplicationId(), container.containerId); super.transition(container, event); } } /** * Handle the following transition: * - LOCALIZATION_FAILED -> DONE upon CONTAINER_RESOURCES_CLEANEDUP */ static class LocalizationFailedToDoneTransition extends ContainerDoneTransition { @Override public void transition(ContainerImpl container, ContainerEvent event) { container.metrics.failedContainer(); NMAuditLogger.logFailure(container.user, AuditConstants.FINISH_FAILED_CONTAINER, "ContainerImpl", "Container failed with state: " + container.getContainerState(), container.containerId.getApplicationAttemptId().getApplicationId(), container.containerId); super.transition(container, event); } } /** * Handle the following transition: * - EXITED_WITH_SUCCESS -> DONE upon CONTAINER_RESOURCES_CLEANEDUP */ static class ExitedWithSuccessToDoneTransition extends ContainerDoneTransition { @Override public void transition(ContainerImpl container, ContainerEvent event) { container.metrics.endRunningContainer(); container.metrics.completedContainer(); NMAuditLogger.logSuccess(container.user, AuditConstants.FINISH_SUCCESS_CONTAINER, "ContainerImpl", container.containerId.getApplicationAttemptId().getApplicationId(), container.containerId); super.transition(container, event); } } /** * Handle the following transition: * - EXITED_WITH_FAILURE -> DONE upon CONTAINER_RESOURCES_CLEANEDUP */ static class ExitedWithFailureToDoneTransition extends ContainerDoneTransition { @Override public void transition(ContainerImpl container, ContainerEvent event) { if (container.wasLaunched) { container.metrics.endRunningContainer(); } container.metrics.failedContainer(); NMAuditLogger.logFailure(container.user, AuditConstants.FINISH_FAILED_CONTAINER, "ContainerImpl", "Container failed with state: " + container.getContainerState(), container.containerId.getApplicationAttemptId().getApplicationId(), container.containerId); super.transition(container, event); } } /** * Handle the following transition: * - KILLING -> DONE upon CONTAINER_RESOURCES_CLEANEDUP */ static class KillingToDoneTransition extends ContainerDoneTransition { @Override public void transition(ContainerImpl container, ContainerEvent event) { container.metrics.killedContainer(); NMAuditLogger.logSuccess(container.user, AuditConstants.FINISH_KILLED_CONTAINER, "ContainerImpl", container.containerId.getApplicationAttemptId().getApplicationId(), container.containerId); super.transition(container, event); } } /** * Handle the following transition: * CONTAINER_CLEANEDUP_AFTER_KILL -> DONE upon CONTAINER_RESOURCES_CLEANEDUP */ static class ContainerCleanedupAfterKillToDoneTransition extends ContainerDoneTransition { @Override public void transition(ContainerImpl container, ContainerEvent event) { if (container.wasLaunched) { container.metrics.endRunningContainer(); } container.metrics.killedContainer(); NMAuditLogger.logSuccess(container.user, AuditConstants.FINISH_KILLED_CONTAINER, "ContainerImpl", container.containerId.getApplicationAttemptId().getApplicationId(), container.containerId); super.transition(container, event); } } /** * Update diagnostics, staying in the same state. */ static class ContainerDiagnosticsUpdateTransition implements SingleArcTransition<ContainerImpl, ContainerEvent> { @Override public void transition(ContainerImpl container, ContainerEvent event) { ContainerDiagnosticsUpdateEvent updateEvent = (ContainerDiagnosticsUpdateEvent) event; container.addDiagnostics(updateEvent.getDiagnosticsUpdate(), "\n"); try { container.stateStore.storeContainerDiagnostics(container.containerId, container.diagnostics); } catch (IOException e) { LOG.warn("Unable to update state store diagnostics for " + container.containerId, e); } } } @Override public void handle(ContainerEvent event) { try { this.writeLock.lock(); ContainerId containerID = event.getContainerID(); LOG.debug("Processing " + containerID + " of type " + event.getType()); ContainerState oldState = stateMachine.getCurrentState(); ContainerState newState = null; try { newState = stateMachine.doTransition(event.getType(), event); } catch (InvalidStateTransitonException e) { LOG.warn("Can't handle this event at current state: Current: [" + oldState + "], eventType: [" + event.getType() + "]", e); } if (oldState != newState) { LOG.info("Container " + containerID + " transitioned from " + oldState + " to " + newState); } } finally { this.writeLock.unlock(); } } @Override public String toString() { this.readLock.lock(); try { return ConverterUtils.toString(this.containerId); } finally { this.readLock.unlock(); } } private boolean hasDefaultExitCode() { return (this.exitCode == ContainerExitStatus.INVALID); } /** * Returns whether the specific resource should be uploaded to the shared * cache. */ private static boolean shouldBeUploadedToSharedCache(ContainerImpl container, LocalResourceRequest resource) { return container.resourcesUploadPolicies.get(resource); } @Override public Set<Integer> getCpuCores() { // TODO Auto-generated method stub return this.cpuCores; } }
apache-2.0
liying2008/neu-ipgw
app/src/main/java/com/liying/ipgw/activity/SplashActivity.java
2750
package com.liying.ipgw.activity; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.widget.Toast; import com.liying.ipgw.R; import com.liying.ipgw.application.AccountApp; import com.liying.ipgw.task.SplashLoadDataTask; import com.liying.ipgw.utils.Constants; import com.umeng.analytics.MobclickAgent; import cc.duduhuo.applicationtoast.AppToast; /** * 启动界面 */ public class SplashActivity extends BaseActivity implements SplashLoadDataTask.LoadDataCallback { private static PackageInfo packageInfo = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); /** 设置是否对日志信息进行加密, 默认false(不加密). */ MobclickAgent.enableEncrypt(true); try { packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } // 启动加载应用数据任务类 startTask(); } /** * 启动加载应用数据任务类 */ private void startTask() { SplashLoadDataTask task = new SplashLoadDataTask(this); task.execute(); } /** * 跳转界面 */ private void jump() { int currentVersion = packageInfo.versionCode; int version = AccountApp.getInstance().prefs.getInt(Constants.VERSION, 0); if (version == 0) { // 首次使用 startActivity(new Intent(this, InitAccountActivity.class)); finish(); //将当前版本写入preference中,则下次启动的时候,据此判断,不再为首次启动 AccountApp.getInstance().editor.putInt(Constants.VERSION, currentVersion).apply(); } else { // 该版本不是首次启动,跳转到MainActivity startActivity(new Intent(this, MainActivity.class)); finish(); } } @Override public void loaded() { new Handler().postDelayed(new Runnable() { @Override public void run() { jump();// 界面跳转 } }, 500); // 停留时间500ms } @Override public void error() { AppToast.showToast("应用启动过程中出现错误,请重新启动。", Toast.LENGTH_LONG); finish(); } @Override public void onBackPressed() { // Splash界面不允许使用back键 } }
apache-2.0
lassehe/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/GVRDirectLight.java
6409
/* Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gearvrf; import static org.gearvrf.utility.Assert.*; import org.gearvrf.GVRMaterial.GVRShaderType; import org.gearvrf.utility.TextFile; /** * Illuminates object in the scene with a directional light source. * * The direction of the light is the forward orientation of the scene object * the light is attached to. Light is emitted in that direction * from infinitely far away. * * The intensity of the light remains constant and does not fall * off with distance from the light. * * Point light uniforms: * {@literal * world_direction direction of light in world coordinates * derived from scene object orientation * ambient_intensity intensity of ambient light emitted * diffuse_intensity intensity of diffuse light emitted * specular_intensity intensity of specular light emitted * } * @see GVRPointLight * @see GVRSpotLight * @see GVRLightBase */ public class GVRDirectLight extends GVRLightBase { protected static String mPhongLightShaderSource = null; public GVRDirectLight(GVRContext gvrContext) { this(gvrContext, null); } public GVRDirectLight(GVRContext gvrContext, GVRSceneObject parent) { super(gvrContext, parent); uniformDescriptor += " float4 diffuse_intensity" + " float4 ambient_intensity" + " float4 specular_intensity"; if (mPhongLightShaderSource == null) { mPhongLightShaderSource = TextFile.readTextFile(gvrContext.getContext(), R.raw.directlight); } setAmbientIntensity(0.0f, 0.0f, 0.0f, 1.0f); setDiffuseIntensity(1.0f, 1.0f, 1.0f, 1.0f); setSpecularIntensity(1.0f, 1.0f, 1.0f, 1.0f); setShaderSource(mPhongLightShaderSource); } /** * Get the ambient light intensity. * * This designates the color of the ambient reflection. * It is multiplied by the material ambient color to derive * the hue of the ambient reflection for that material. * The built-in phong shader {@link GVRPhongSurface} uses a {@code vec4} uniform named * {@code ambient_intensity} to control the intensity of ambient light reflected. * * @return The current {@code vec4 ambient_intensity} as a four-element array */ public float[] getAmbientIntensity() { return getVec4("ambient_intensity"); } /** * Set the ambient light intensity. * * This designates the color of the ambient reflection. * It is multiplied by the material ambient color to derive * the hue of the ambient reflection for that material. * The built-in phong shader {@link GVRPhongSurface} uses a {@code vec4} uniform named * {@code ambient_intensity} to control the intensity of ambient light reflected. * * @param r red component (0 to 1) * @param g green component (0 to 1) * @param b blue component (0 to 1) * @param a alpha component (0 to 1) */ public void setAmbientIntensity(float r, float g, float b, float a) { setVec4("ambient_intensity", r, g, b, a); } /** * Get the diffuse light intensity. * * This designates the color of the diffuse reflection. * It is multiplied by the material diffuse color to derive * the hue of the diffuse reflection for that material. * The built-in phong shader {@link GVRPhongSurface} uses a {@code vec4} uniform named * {@code diffuse_intensity} to control the intensity of diffuse light reflected. * * @return The current {@code vec4 diffuse_intensity} as a four-element * array */ public float[] getDiffuseIntensity() { return getVec4("diffuse_intensity"); } /** * Set the diffuse light intensity. * * This designates the color of the diffuse reflection. * It is multiplied by the material diffuse color to derive * the hue of the diffuse reflection for that material. * The built-in phong shader {@link GVRPhongSurface} uses a {@code vec4} uniform named * {@code diffuse_intensity} to control the intensity of diffuse light reflected. * * @param r red component (0 to 1) * @param g green component (0 to 1) * @param b blue component (0 to 1) * @param a alpha component (0 to 1) */ public void setDiffuseIntensity(float r, float g, float b, float a) { setVec4("diffuse_intensity", r, g, b, a); } /** * Get the specular intensity of the light. * * This designates the color of the specular reflection. * It is multiplied by the material specular color to derive * the hue of the specular reflection for that material. * The built-in phong shader {@link GVRPhongSurface} uses a {@code vec4} uniform named * {@code specular_intensity} to control the specular intensity. * * @return The current {@code vec4 specular_intensity} as a four-element array */ public float[] getSpecularIntensity() { return getVec4("specular_intensity"); } /** * Set the specular intensity of the light. * * This designates the color of the specular reflection. * It is multiplied by the material specular color to derive * the hue of the specular reflection for that material. * The built-in phong shader {@link GVRPhongSurface} uses a {@code vec4} uniform named * {@code specular_intensity} to control the specular intensity. * * @param r red component (0 to 1) * @param g green component (0 to 1) * @param b blue component (0 to 1) * @param a alpha component (0 to 1) */ public void setSpecularIntensity(float r, float g, float b, float a) { setVec4("specular_intensity", r, g, b, a); } }
apache-2.0
getflint/flint-cloud
office365/customer/user-accounts/get_all_user_roles.rb
1605
require 'json' @log.trace("Started execution'flint-o365:microsoft-cloud:user_account:get_all_user_role.rb' flintbit...") begin # Flintbit Input Parameters @connector_name = @input.get('connector-name') # Name of the Connector @microsoft_id = @input.get('customer-id') # id of the Microsoft Account @action = 'get-all-user-roles' # @input.get("action") @log.info("Flintbit input parameters are, connector name :: #{@connector_name} | MICROSOFT ID :: #{@microsoft_id}") response = @call.connector(@connector_name) .set('action', @action) .set('microsoft-id', @microsoft_id) .sync response_exitcode = response.exitcode # Exit status code response_message = response.message # Execution status message response_body = response.get('body') if response_exitcode == 0 @log.info("Success in executing #{@connector_name} Connector, where exitcode :: #{response_exitcode} | message :: #{response_message}") @log.info("RESPONSE :: #{response_body}") @output.setraw('result', response_body.to_json) else @log.error("ERROR in executing #{@connector_name} where, exitcode :: #{response_exitcode} | message :: #{response_message}") @output.exit(1, response_message) end rescue Exception => e @log.error(e.message) @output.set('exit-code', 1).set('message', e.message) end @log.trace("Finished execution 'flint-o365:microsoft-cloud:user_account:get_all_user_role.rb' flintbit...")
apache-2.0
adamors/google-api-php-client
src/Google/Utils/URITemplate.php
9479
<?php /* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Implementation of levels 1-3 of the URI Template spec. * @see http://tools.ietf.org/html/rfc6570 */ class Google_Utils_URITemplate { const TYPE_MAP = "1"; const TYPE_LIST = "2"; const TYPE_SCALAR = "4"; /** * @var $operators array * These are valid at the start of a template block to * modify the way in which the variables inside are * processed. */ protected $operators = array( "+" => "reserved", "/" => "segments", "." => "dotprefix", "#" => "fragment", ";" => "semicolon", "?" => "form", "&" => "continuation" ); /** * @var reserved array * These are the characters which should not be URL encoded in reserved * strings. */ protected $reserved = array( "=", ",", "!", "@", "|", ":", "/", "?", "#", "[", "]",'$', "&", "'", "(", ")", "*", "+", ";" ); protected $reservedEncoded = array( "%3D", "%2C", "%21", "%40", "%7C", "%3A", "%2F", "%3F", "%23", "%5B", "%5D", "%24", "%26", "%27", "%28", "%29", "%2A", "%2B", "%3B" ); public function parse($string, array $parameters) { return $this->resolveNextSection($string, $parameters); } /** * This function finds the first matching {...} block and * executes the replacement. It then calls itself to find * subsequent blocks, if any. */ private function resolveNextSection($string, $parameters) { $start = strpos($string, "{"); if ($start === false) { return $string; } $end = strpos($string, "}"); if ($end === false) { return $string; } $string = $this->replace($string, $start, $end, $parameters); return $this->resolveNextSection($string, $parameters); } private function replace($string, $start, $end, $parameters) { // We know a data block will have {} round it, so we can strip that. $data = substr($string, $start + 1, $end - $start - 1); // If the first character is one of the reserved operators, it effects // the processing of the stream. if (isset($this->operators[$data[0]])) { $op = $this->operators[$data[0]]; $data = substr($data, 1); $prefix = ""; $prefix_on_missing = false; switch ($op) { case "reserved": // Reserved means certain characters should not be URL encoded $data = $this->replaceVars($data, $parameters, ",", null, true); break; case "fragment": // Comma separated with fragment prefix. Bare values only. $prefix = "#"; $prefix_on_missing = true; $data = $this->replaceVars($data, $parameters, ",", null, true); break; case "segments": // Slash separated data. Bare values only. $prefix = "/"; $data =$this->replaceVars($data, $parameters, "/"); break; case "dotprefix": // Dot separated data. Bare values only. $prefix = "."; $prefix_on_missing = true; $data = $this->replaceVars($data, $parameters, "."); break; case "semicolon": // Semicolon prefixed and separated. Uses the key name $prefix = ";"; $data = $this->replaceVars($data, $parameters, ";", "=", false, true, false); break; case "form": // Standard URL format. Uses the key name $prefix = "?"; $data = $this->replaceVars($data, $parameters, "&", "="); break; case "continuation": // Standard URL, but with leading ampersand. Uses key name. $prefix = "&"; $data = $this->replaceVars($data, $parameters, "&", "="); break; } // Add the initial prefix character if data is valid. if ($data || ($data !== false && $prefix_on_missing)) { $data = $prefix . $data; } } else { // If no operator we replace with the defaults. $data = $this->replaceVars($data, $parameters); } // This is chops out the {...} and replaces with the new section. return substr($string, 0, $start) . $data . substr($string, $end + 1); } private function replaceVars( $section, $parameters, $sep = ",", $combine = null, $reserved = false, $tag_empty = false, $combine_on_empty = true ) { if (strpos($section, ",") === false) { // If we only have a single value, we can immediately process. return $this->combine( $section, $parameters, $sep, $combine, $reserved, $tag_empty, $combine_on_empty ); } else { // If we have multiple values, we need to split and loop over them. // Each is treated individually, then glued together with the // separator character. $vars = explode(",", $section); return $this->combineList( $vars, $sep, $parameters, $combine, $reserved, false, // Never emit empty strings in multi-param replacements $combine_on_empty ); } } public function combine( $key, $parameters, $sep, $combine, $reserved, $tag_empty, $combine_on_empty ) { $length = false; $explode = false; $skip_final_combine = false; $value = false; // Check for length restriction. if (strpos($key, ":") !== false) { list($key, $length) = explode(":", $key); } // Check for explode parameter. if ($key[strlen($key) - 1] == "*") { $explode = true; $key = substr($key, 0, -1); $skip_final_combine = true; } // Define the list separator. $list_sep = $explode ? $sep : ","; if (isset($parameters[$key])) { $data_type = $this->getDataType($parameters[$key]); switch ($data_type) { case self::TYPE_SCALAR: $value = $this->getValue($parameters[$key], $length); break; case self::TYPE_LIST: $values = array(); foreach ($parameters[$key] as $pkey => $pvalue) { $pvalue = $this->getValue($pvalue, $length); if ($combine && $explode) { $values[$pkey] = $key . $combine . $pvalue; } else { $values[$pkey] = $pvalue; } } $value = implode($list_sep, $values); if ($value == '') { return ''; } break; case self::TYPE_MAP: $values = array(); foreach ($parameters[$key] as $pkey => $pvalue) { $pvalue = $this->getValue($pvalue, $length); if ($explode) { $pkey = $this->getValue($pkey, $length); $values[] = $pkey . "=" . $pvalue; // Explode triggers = combine. } else { $values[] = $pkey; $values[] = $pvalue; } } $value = implode($list_sep, $values); if ($value == '') { return false; } break; } } else if ($tag_empty) { // If we are just indicating empty values with their key name, return that. return $key; } else { // Otherwise we can skip this variable due to not being defined. return false; } if ($reserved) { $value = str_replace($this->reservedEncoded, $this->reserved, $value); } // If we do not need to include the key name, we just return the raw // value. if (!$combine || $skip_final_combine) { return $value; } // Else we combine the key name: foo=bar, if value is not the empty string. return $key . ($value != '' || $combine_on_empty ? $combine . $value : ''); } /** * Return the type of a passed in value */ private function getDataType($data) { if (is_array($data)) { reset($data); if (key($data) !== 0) { return self::TYPE_MAP; } return self::TYPE_LIST; } return self::TYPE_SCALAR; } /** * Utility function that merges multiple combine calls * for multi-key templates. */ private function combineList( $vars, $sep, $parameters, $combine, $reserved, $tag_empty, $combine_on_empty ) { $ret = array(); foreach ($vars as $var) { $response = $this->combine( $var, $parameters, $sep, $combine, $reserved, $tag_empty, $combine_on_empty ); if ($response === false) { continue; } $ret[] = $response; } return implode($sep, $ret); } /** * Utility function to encode and trim values */ private function getValue($value, $length) { if ($length) { $value = substr($value, 0, $length); } $value = rawurlencode($value); return $value; } }
apache-2.0
lschuetze/gueryframework
guery-adapter-jung/src/test/java/nz/ac/massey/cs/guery/suite1/ColouredVertex.java
1058
/* * Copyright 2015 Jens Dietrich * * 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 nz.ac.massey.cs.guery.suite1; import nz.ac.massey.cs.guery.adapters.jungalt.Vertex; @SuppressWarnings("serial") public class ColouredVertex extends Vertex<ColouredEdge> { public ColouredVertex() { super(); } private String colour = null; public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } @Override public String toString() { return "vertex["+this.getId()+"]"; } }
apache-2.0
artembilan/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration.java
11124
/* * Copyright 2012-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 org.springframework.boot.autoconfigure.jackson; import java.lang.reflect.Field; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.jackson.JsonComponentModule; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Scope; import org.springframework.core.Ordered; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; /** * Auto configuration for Jackson. The following auto-configuration will get applied: * <ul> * <li>an {@link ObjectMapper} in case none is already configured.</li> * <li>a {@link Jackson2ObjectMapperBuilder} in case none is already configured.</li> * <li>auto-registration for all {@link Module} beans with all {@link ObjectMapper} beans * (including the defaulted ones).</li> * </ul> * * @author Oliver Gierke * @author Andy Wilkinson * @author Marcel Overdijk * @author Sebastien Deleuze * @author Johannes Edmeier * @author Phillip Webb * @author Eddú Meléndez * @since 1.1.0 */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ObjectMapper.class) public class JacksonAutoConfiguration { private static final Map<?, Boolean> FEATURE_DEFAULTS; static { Map<Object, Boolean> featureDefaults = new HashMap<>(); featureDefaults.put(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); featureDefaults.put(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false); FEATURE_DEFAULTS = Collections.unmodifiableMap(featureDefaults); } @Bean public JsonComponentModule jsonComponentModule() { return new JsonComponentModule(); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Jackson2ObjectMapperBuilder.class) static class JacksonObjectMapperConfiguration { @Bean @Primary @ConditionalOnMissingBean ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { return builder.createXmlMapper(false).build(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(ParameterNamesModule.class) static class ParameterNamesModuleConfiguration { @Bean @ConditionalOnMissingBean ParameterNamesModule parameterNamesModule() { return new ParameterNamesModule(JsonCreator.Mode.DEFAULT); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Jackson2ObjectMapperBuilder.class) static class JacksonObjectMapperBuilderConfiguration { @Bean @Scope("prototype") @ConditionalOnMissingBean Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder(ApplicationContext applicationContext, List<Jackson2ObjectMapperBuilderCustomizer> customizers) { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); builder.applicationContext(applicationContext); customize(builder, customizers); return builder; } private void customize(Jackson2ObjectMapperBuilder builder, List<Jackson2ObjectMapperBuilderCustomizer> customizers) { for (Jackson2ObjectMapperBuilderCustomizer customizer : customizers) { customizer.customize(builder); } } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Jackson2ObjectMapperBuilder.class) @EnableConfigurationProperties(JacksonProperties.class) static class Jackson2ObjectMapperBuilderCustomizerConfiguration { @Bean StandardJackson2ObjectMapperBuilderCustomizer standardJacksonObjectMapperBuilderCustomizer( ApplicationContext applicationContext, JacksonProperties jacksonProperties) { return new StandardJackson2ObjectMapperBuilderCustomizer(applicationContext, jacksonProperties); } static final class StandardJackson2ObjectMapperBuilderCustomizer implements Jackson2ObjectMapperBuilderCustomizer, Ordered { private final ApplicationContext applicationContext; private final JacksonProperties jacksonProperties; StandardJackson2ObjectMapperBuilderCustomizer(ApplicationContext applicationContext, JacksonProperties jacksonProperties) { this.applicationContext = applicationContext; this.jacksonProperties = jacksonProperties; } @Override public int getOrder() { return 0; } @Override public void customize(Jackson2ObjectMapperBuilder builder) { if (this.jacksonProperties.getDefaultPropertyInclusion() != null) { builder.serializationInclusion(this.jacksonProperties.getDefaultPropertyInclusion()); } if (this.jacksonProperties.getTimeZone() != null) { builder.timeZone(this.jacksonProperties.getTimeZone()); } configureFeatures(builder, FEATURE_DEFAULTS); configureVisibility(builder, this.jacksonProperties.getVisibility()); configureFeatures(builder, this.jacksonProperties.getDeserialization()); configureFeatures(builder, this.jacksonProperties.getSerialization()); configureFeatures(builder, this.jacksonProperties.getMapper()); configureFeatures(builder, this.jacksonProperties.getParser()); configureFeatures(builder, this.jacksonProperties.getGenerator()); configureDateFormat(builder); configurePropertyNamingStrategy(builder); configureModules(builder); configureLocale(builder); } private void configureFeatures(Jackson2ObjectMapperBuilder builder, Map<?, Boolean> features) { features.forEach((feature, value) -> { if (value != null) { if (value) { builder.featuresToEnable(feature); } else { builder.featuresToDisable(feature); } } }); } private void configureVisibility(Jackson2ObjectMapperBuilder builder, Map<PropertyAccessor, JsonAutoDetect.Visibility> visibilities) { visibilities.forEach(builder::visibility); } private void configureDateFormat(Jackson2ObjectMapperBuilder builder) { // We support a fully qualified class name extending DateFormat or a date // pattern string value String dateFormat = this.jacksonProperties.getDateFormat(); if (dateFormat != null) { try { Class<?> dateFormatClass = ClassUtils.forName(dateFormat, null); builder.dateFormat((DateFormat) BeanUtils.instantiateClass(dateFormatClass)); } catch (ClassNotFoundException ex) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); // Since Jackson 2.6.3 we always need to set a TimeZone (see // gh-4170). If none in our properties fallback to the Jackson's // default TimeZone timeZone = this.jacksonProperties.getTimeZone(); if (timeZone == null) { timeZone = new ObjectMapper().getSerializationConfig().getTimeZone(); } simpleDateFormat.setTimeZone(timeZone); builder.dateFormat(simpleDateFormat); } } } private void configurePropertyNamingStrategy(Jackson2ObjectMapperBuilder builder) { // We support a fully qualified class name extending Jackson's // PropertyNamingStrategy or a string value corresponding to the constant // names in PropertyNamingStrategy which hold default provided // implementations String strategy = this.jacksonProperties.getPropertyNamingStrategy(); if (strategy != null) { try { configurePropertyNamingStrategyClass(builder, ClassUtils.forName(strategy, null)); } catch (ClassNotFoundException ex) { configurePropertyNamingStrategyField(builder, strategy); } } } private void configurePropertyNamingStrategyClass(Jackson2ObjectMapperBuilder builder, Class<?> propertyNamingStrategyClass) { builder.propertyNamingStrategy( (PropertyNamingStrategy) BeanUtils.instantiateClass(propertyNamingStrategyClass)); } private void configurePropertyNamingStrategyField(Jackson2ObjectMapperBuilder builder, String fieldName) { // Find the field (this way we automatically support new constants // that may be added by Jackson in the future) Field field = findPropertyNamingStrategyField(fieldName); Assert.notNull(field, () -> "Constant named '" + fieldName + "' not found"); try { builder.propertyNamingStrategy((PropertyNamingStrategy) field.get(null)); } catch (Exception ex) { throw new IllegalStateException(ex); } } private Field findPropertyNamingStrategyField(String fieldName) { try { return ReflectionUtils.findField(com.fasterxml.jackson.databind.PropertyNamingStrategies.class, fieldName, PropertyNamingStrategy.class); } catch (NoClassDefFoundError ex) { // Fallback pre Jackson 2.12 return ReflectionUtils.findField(PropertyNamingStrategy.class, fieldName, PropertyNamingStrategy.class); } } private void configureModules(Jackson2ObjectMapperBuilder builder) { Collection<Module> moduleBeans = getBeans(this.applicationContext, Module.class); builder.modulesToInstall(moduleBeans.toArray(new Module[0])); } private void configureLocale(Jackson2ObjectMapperBuilder builder) { Locale locale = this.jacksonProperties.getLocale(); if (locale != null) { builder.locale(locale); } } private static <T> Collection<T> getBeans(ListableBeanFactory beanFactory, Class<T> type) { return BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, type).values(); } } } }
apache-2.0
bcgov/MyGovBC-MSP
src/app/modules/enrolment/pages/child-info/child-info.component.spec.ts
1749
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SharedCoreModule } from 'moh-common-lib'; import { FormsModule } from '@angular/forms'; import { LocalStorageModule } from 'angular-2-local-storage'; import { RouterTestingModule } from '@angular/router/testing'; import { ChildInfoComponent } from './child-info.component'; import { MspCoreModule } from '../../../msp-core/msp-core.module'; import { PageStateService } from '../../../../services/page-state.service'; import { EnrolDataService } from '../../services/enrol-data.service'; import { EnrolApplication } from '../../models/enrol-application'; describe('ChildInfoComponent', () => { let component: ChildInfoComponent; let fixture: ComponentFixture<ChildInfoComponent>; const pageStateServiceStub = () => ({ setPageIncomplete: (str, arr) => ({}) }); const enrolDataServiceStub = () => ({ application: new EnrolApplication() }); beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ChildInfoComponent ], imports: [ SharedCoreModule, FormsModule, MspCoreModule, LocalStorageModule.withConfig({ prefix: 'ca.bc.gov.msp', storageType: 'sessionStorage' }), RouterTestingModule ], providers: [ { provide: PageStateService, useFactory: pageStateServiceStub }, { provide: EnrolDataService, useFactory: enrolDataServiceStub } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ChildInfoComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
apache-2.0
LQJJ/demo
126-go-common-master/app/service/main/vip/service/coupon_test.go
3143
package service import ( "fmt" "testing" col "go-common/app/service/main/coupon/model" v1 "go-common/app/service/main/vip/api" "go-common/app/service/main/vip/model" . "github.com/smartystreets/goconvey/convey" ) // go test -test.v -test.run TestServiceCouponBySuitID func TestServiceCouponBySuitID(t *testing.T) { Convey(" TestServiceCouponBySuitID ", t, func() { var ( mid = int64(1) sid = int64(3) res *col.CouponAllowancePanelInfo ) res, err := s.CouponBySuitID(c, &model.ArgCouponPanel{Mid: mid, Sid: sid}) t.Logf("data(%+v)", res) So(err, ShouldBeNil) }) } func TestServiceCouponsForPanel(t *testing.T) { Convey(" TestServiceCouponsForPanel ", t, func() { var ( mid = int64(1) sid = int64(3) res *col.CouponAllowancePanelResp ) res, err := s.CouponsForPanel(c, &model.ArgCouponPanel{Mid: mid, Sid: sid}) t.Logf("data(+%v)", res) So(err, ShouldBeNil) }) } // go test -test.v -test.run TestServiceCancelUseCoupon func TestServiceCancelUseCoupon(t *testing.T) { Convey(" TestServiceCancelUseCoupon ", t, func() { var ( mid = int64(1) token = "772991379820180716121343" ) err := s.CancelUseCoupon(c, mid, token, "127.0.0.1") So(err, ShouldBeNil) }) } // go test -test.v -test.run TestServiceVipUserPanelV4 func TestServiceVipUserPanelV4(t *testing.T) { Convey(" TestServiceVipUserPanelV4 ", t, func() { var ( mid = int64(1) res *model.VipPirceResp ) res, err := s.VipUserPanelV4(c, &model.ArgPanel{ Mid: mid, Platform: "android", SortTp: model.PanelMonthDESC, }) So(res, ShouldNotBeNil) for _, v := range res.Vps { t.Logf("panel info(%+v)", v) } t.Logf("coupon info(%+v)", res.CouponInfo) t.Logf("data(+%v)", res) So(err, ShouldBeNil) }) } // go test -test.v -test.run TestServiceVipPrice func TestServiceVipPrice(t *testing.T) { Convey(" TestServiceVipPrice ", t, func() { var ( mid = int64(1) plat = int64(3) subType int8 month = int16(12) token = "992628254320180713122015" res *model.VipPirce ) res, err := s.VipPrice(c, mid, month, plat, subType, token, "pc", 0) So(res, ShouldNotBeNil) t.Logf("coupon info(%+v)", res.Coupon) t.Logf("price info(%+v)", res.Panel) t.Logf("data(+%v)", res) So(err, ShouldBeNil) }) } // go test -test.v -test.run TestServiceCancelUseCoupon2 func TestServiceCancelUseCoupon2(t *testing.T) { Convey(" TestServiceCancelUseCoupon2 ", t, func() { var ( mid = int64(1) token = "992628254320180713122015" ) err := s.CancelUseCoupon(c, mid, token, "127.0.0.1") So(err, ShouldBeNil) }) } func TestServiceFormatRate(t *testing.T) { Convey("test formatRate", t, func() { config := new(model.VipPriceConfig) config.OPrice = 233 config.DPrice = 148 t.Logf(config.FormatRate()) }) } func TestServiceCouponBySuitIDV2(t *testing.T) { Convey("TestServiceCouponBySuitIDV2 ", t, func() { res, err := s.CouponBySuitIDV2(c, &v1.CouponBySuitIDReq{ Sid: 158, Mid: 1, Platform: "pc", PanelType: "normal", }) fmt.Println("res", res.CouponTip, res.CouponInfo) So(err, ShouldBeNil) }) }
apache-2.0
TheCoder4eu/BootsFacesWeb
src/main/java/net/bootsfaces/demo/FullCalendarBean.java
504
package net.bootsfaces.demo; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; @ManagedBean @ViewScoped public class FullCalendarBean implements Serializable { private static final long serialVersionUID = 1L; private String language = "en"; public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public void updateLanguage() { } }
apache-2.0
xgqfrms/JavaWeb
DesignPattern_Homework/src/state_2/TaxState6.java
693
package state_2; /*========================================*/ /* A concrete state in the state pattern */ /*========================================*/ public class TaxState6 extends TaxState{ private final static double TAXRATE = 0.3; private double taxAmount = 0.0; String SINGLE = "Single"; String FAMILY = "Family"; public TaxState6(TaxContext context){ super(context); state = STATE6; } public double calculateTax(String kind,double amount){ if(kind.equals(SINGLE)) taxAmount = TAXRATE*amount-3375; else if (kind.equals(FAMILY)) taxAmount = 0.9*(TAXRATE*amount-3375); context.saveTaxInfoToDB(taxAmount); return taxAmount; } }
apache-2.0
klaasnotfound/LocationAssistant
app/src/main/java/com/klaasnotfound/locationassistant/LocationAssistant.java
33218
// https://github.com/klaasnotfound/LocationAssistant /* * Copyright 2017 Klaas Klasing (klaas [at] klaasnotfound.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.klaasnotfound.locationassistant; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationAvailability; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStatusCodes; /** * A helper class that monitors the available location info on behalf of a requesting activity or application. */ public class LocationAssistant implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { /** * Delivers relevant events required to obtain (valid) location info. */ public interface Listener { /** * Called when the user needs to grant the app location permission at run time. * This is only necessary on newer Android systems (API level >= 23). * If you want to show some explanation up front, do that, then call {@link #requestLocationPermission()}. * Alternatively, you can call {@link #requestAndPossiblyExplainLocationPermission()}, which will request the * location permission right away and invoke {@link #onExplainLocationPermission()} only if the user declines. * Both methods will bring up the system permission dialog. */ void onNeedLocationPermission(); /** * Called when the user has declined the location permission and might need a better explanation as to why * your app really depends on it. * You can show some sort of dialog or info window here and then - if the user is willing - ask again for * permission with {@link #requestLocationPermission()}. */ void onExplainLocationPermission(); /** * Called when the user has declined the location permission at least twice or has declined once and checked * "Don't ask again" (which will cause the system to permanently decline it). * You can show some sort of message that explains that the user will need to go to the app settings * to enable the permission. You may use the preconfigured OnClickListeners to send the user to the app * settings page. * * @param fromView OnClickListener to use with a view (e.g. a button), jumps to the app settings * @param fromDialog OnClickListener to use with a dialog, jumps to the app settings */ void onLocationPermissionPermanentlyDeclined(View.OnClickListener fromView, DialogInterface.OnClickListener fromDialog); /** * Called when a change of the location provider settings is necessary. * You can optionally show some informative dialog and then request the settings change with * {@link #changeLocationSettings()}. */ void onNeedLocationSettingsChange(); /** * In certain cases where the user has switched off location providers, changing the location settings from * within the app may not work. The LocationAssistant will attempt to detect these cases and offer a redirect to * the system location settings, where the user may manually enable on location providers before returning to * the app. * You can prompt the user with an appropriate message (in a view or a dialog) and use one of the provided * OnClickListeners to jump to the settings. * * @param fromView OnClickListener to use with a view (e.g. a button), jumps to the location settings * @param fromDialog OnClickListener to use with a dialog, jumps to the location settings */ void onFallBackToSystemSettings(View.OnClickListener fromView, DialogInterface.OnClickListener fromDialog); /** * Called when a new and valid location is available. * If you chose to reject mock locations, this method will only be called when a real location is available. * * @param location the current user location */ void onNewLocationAvailable(Location location); /** * Called when the presence of mock locations was detected and {@link #allowMockLocations} is {@code false}. * You can use this callback to scold the user or do whatever. The user can usually disable mock locations by * either switching off a running mock location app (on newer Android systems) or by disabling mock location * apps altogether. The latter can be done in the phone's development settings. You may show an appropriate * message and then use one of the provided OnClickListeners to jump to those settings. * * @param fromView OnClickListener to use with a view (e.g. a button), jumps to the development settings * @param fromDialog OnClickListener to use with a dialog, jumps to the development settings */ void onMockLocationsDetected(View.OnClickListener fromView, DialogInterface.OnClickListener fromDialog); /** * Called when an error has occurred. * * @param type the type of error that occurred * @param message a plain-text message with optional details */ void onError(ErrorType type, String message); } /** * Possible values for the desired location accuracy. */ public enum Accuracy { /** * Highest possible accuracy, typically within 30m */ HIGH, /** * Medium accuracy, typically within a city block / roughly 100m */ MEDIUM, /** * City-level accuracy, typically within 10km */ LOW, /** * Variable accuracy, purely dependent on updates requested by other apps */ PASSIVE } public enum ErrorType { /** * An error with the user's location settings */ SETTINGS, /** * An error with the retrieval of location info */ RETRIEVAL } private final int REQUEST_CHECK_SETTINGS = 0; private final int REQUEST_LOCATION_PERMISSION = 1; // Parameters protected Context context; private Activity activity; private Listener listener; private int priority; private long updateInterval; private boolean allowMockLocations; private boolean verbose; private boolean quiet; // Internal state private boolean permissionGranted; private boolean locationRequested; private boolean locationStatusOk; private boolean changeSettings; private boolean updatesRequested; protected Location bestLocation; private GoogleApiClient googleApiClient; private LocationRequest locationRequest; private Status locationStatus; private boolean mockLocationsEnabled; private int numTimesPermissionDeclined; // Mock location rejection private Location lastMockLocation; private int numGoodReadings; /** * Constructs a LocationAssistant instance that will listen for valid location updates. * * @param context the context of the application or activity that wants to receive location updates * @param listener a listener that will receive location-related events * @param accuracy the desired accuracy of the loation updates * @param updateInterval the interval (in milliseconds) at which the activity can process updates * @param allowMockLocations whether or not mock locations are acceptable */ public LocationAssistant(final Context context, Listener listener, Accuracy accuracy, long updateInterval, boolean allowMockLocations) { this.context = context; if (context instanceof Activity) this.activity = (Activity) context; this.listener = listener; switch (accuracy) { case HIGH: priority = LocationRequest.PRIORITY_HIGH_ACCURACY; break; case MEDIUM: priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY; break; case LOW: priority = LocationRequest.PRIORITY_LOW_POWER; break; case PASSIVE: default: priority = LocationRequest.PRIORITY_NO_POWER; } this.updateInterval = updateInterval; this.allowMockLocations = allowMockLocations; // Set up the Google API client if (googleApiClient == null) { googleApiClient = new GoogleApiClient.Builder(context) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } } /** * Makes the LocationAssistant print info log messages. * * @param verbose whether or not the LocationAssistant should print verbose log messages. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Mutes/unmutes all log output. * You may want to mute the LocationAssistant in production. * * @param quiet whether or not to disable all log output (including errors). */ public void setQuiet(boolean quiet) { this.quiet = quiet; } /** * Starts the LocationAssistant and makes it subscribe to valid location updates. * Call this method when your application or activity becomes awake. */ public void start() { checkMockLocations(); googleApiClient.connect(); } /** * Updates the active Activity for which the LocationAssistant manages location updates. * When you want the LocationAssistant to start and stop with your overall application, but service different * activities, call this method at the end of your {@link Activity#onResume()} implementation. * * @param activity the activity that wants to receive location updates * @param listener a listener that will receive location-related events */ public void register(Activity activity, Listener listener) { this.activity = activity; this.listener = listener; checkInitialLocation(); acquireLocation(); } /** * Stops the LocationAssistant and makes it unsubscribe from any location updates. * Call this method right before your application or activity goes to sleep. */ public void stop() { if (googleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this); googleApiClient.disconnect(); } permissionGranted = false; locationRequested = false; locationStatusOk = false; updatesRequested = false; } /** * Clears the active Activity and its listener. * Until you register a new activity and listener, the LocationAssistant will silently produce error messages. * When you want the LocationAssistant to start and stop with your overall application, but service different * activities, call this method at the beginning of your {@link Activity#onPause()} implementation. */ public void unregister() { this.activity = null; this.listener = null; } /** * In rare cases (e.g. after losing connectivity) you may want to reset the LocationAssistant and have it start * from scratch. Use this method to do so. */ public void reset() { permissionGranted = false; locationRequested = false; locationStatusOk = false; updatesRequested = false; acquireLocation(); } /** * Returns the best valid location currently available. * Usually, this will be the last valid location that was received. * * @return the best valid location */ public Location getBestLocation() { return bestLocation; } /** * The first time you call this method, it brings up a system dialog asking the user to give location permission to * the app. On subsequent calls, if the user has previously declined permission, this method invokes * {@link Listener#onExplainLocationPermission()}. */ public void requestAndPossiblyExplainLocationPermission() { if (permissionGranted) return; if (activity == null) { if (!quiet) Log.e(getClass().getSimpleName(), "Need location permission, but no activity is registered! " + "Specify a valid activity when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); return; } if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION) && listener != null) listener.onExplainLocationPermission(); else requestLocationPermission(); } /** * Brings up a system dialog asking the user to give location permission to the app. */ public void requestLocationPermission() { if (activity == null) { if (!quiet) Log.e(getClass().getSimpleName(), "Need location permission, but no activity is registered! " + "Specify a valid activity when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); return; } ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION); } /** * Call this method at the end of your {@link Activity#onRequestPermissionsResult} implementation to notify the * LocationAssistant of an update in permissions. * * @param requestCode the request code returned to the activity (simply pass it on) * @param grantResults the results array returned to the activity (simply pass it on) * @return {@code true} if the location permission was granted, {@code false} otherwise */ public boolean onPermissionsUpdated(int requestCode, int[] grantResults) { if (requestCode != REQUEST_LOCATION_PERMISSION) return false; if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { acquireLocation(); return true; } else { numTimesPermissionDeclined++; if (!quiet) Log.i(getClass().getSimpleName(), "Location permission request denied."); if (numTimesPermissionDeclined >= 2 && listener != null) listener.onLocationPermissionPermanentlyDeclined(onGoToAppSettingsFromView, onGoToAppSettingsFromDialog); return false; } } /** * Call this method at the end of your {@link Activity#onActivityResult} implementation to notify the * LocationAssistant of a change in location provider settings. * * @param requestCode the request code returned to the activity (simply pass it on) * @param resultCode the result code returned to the activity (simply pass it on) */ public void onActivityResult(int requestCode, int resultCode) { if (requestCode != REQUEST_CHECK_SETTINGS) return; if (resultCode == Activity.RESULT_OK) { changeSettings = false; locationStatusOk = true; } acquireLocation(); } /** * Brings up an in-app system dialog that requests a change in location provider settings. * The settings change may involve switching on GPS and/or network providers and depends on the accuracy and * update interval that was requested when constructing the LocationAssistant. * Call this method only from within {@link Listener#onNeedLocationSettingsChange()}. */ public void changeLocationSettings() { if (locationStatus == null) return; if (activity == null) { if (!quiet) Log.e(getClass().getSimpleName(), "Need to resolve location status issues, but no activity is " + "registered! Specify a valid activity when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); return; } try { locationStatus.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { if (!quiet) Log.e(getClass().getSimpleName(), "Error while attempting to resolve location status issues:\n" + e.toString()); if (listener != null) listener.onError(ErrorType.SETTINGS, "Could not resolve location settings issue:\n" + e.getMessage()); changeSettings = false; acquireLocation(); } } protected void acquireLocation() { if (!permissionGranted) checkLocationPermission(); if (!permissionGranted) { if (numTimesPermissionDeclined >= 2) return; if (listener != null) listener.onNeedLocationPermission(); else if (!quiet) Log.e(getClass().getSimpleName(), "Need location permission, but no listener is registered! " + "Specify a valid listener when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); return; } if (!locationRequested) { requestLocation(); return; } if (!locationStatusOk) { if (changeSettings) { if (listener != null) listener.onNeedLocationSettingsChange(); else if (!quiet) Log.e(getClass().getSimpleName(), "Need location settings change, but no listener is " + "registered! Specify a valid listener when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); } else checkProviders(); return; } if (!updatesRequested) { requestLocationUpdates(); // Check back in a few new Handler().postDelayed(new Runnable() { @Override public void run() { acquireLocation(); } }, 10000); return; } if (!checkLocationAvailability()) { // Something is wrong - probably the providers are disabled. checkProviders(); } } protected void checkInitialLocation() { if (!googleApiClient.isConnected() || !permissionGranted || !locationRequested || !locationStatusOk) return; try { Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); onLocationChanged(location); } catch (SecurityException e) { if (!quiet) Log.e(getClass().getSimpleName(), "Error while requesting last location:\n " + e.toString()); if (listener != null) listener.onError(ErrorType.RETRIEVAL, "Could not retrieve initial location:\n" + e.getMessage()); } } private void checkMockLocations() { // Starting with API level >= 18 we can (partially) rely on .isFromMockProvider() // (http://developer.android.com/reference/android/location/Location.html#isFromMockProvider%28%29) // For API level < 18 we have to check the Settings.Secure flag if (Build.VERSION.SDK_INT < 18 && !android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings .Secure.ALLOW_MOCK_LOCATION).equals("0")) { mockLocationsEnabled = true; if (listener != null) listener.onMockLocationsDetected(onGoToDevSettingsFromView, onGoToDevSettingsFromDialog); } else mockLocationsEnabled = false; } private void checkLocationPermission() { permissionGranted = Build.VERSION.SDK_INT < 23 || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; } private void requestLocation() { if (!googleApiClient.isConnected() || !permissionGranted) return; locationRequest = LocationRequest.create(); locationRequest.setPriority(priority); locationRequest.setInterval(updateInterval); locationRequest.setFastestInterval(updateInterval); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); builder.setAlwaysShow(true); LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()) .setResultCallback(onLocationSettingsReceived); } private boolean checkLocationAvailability() { if (!googleApiClient.isConnected() || !permissionGranted) return false; try { LocationAvailability la = LocationServices.FusedLocationApi.getLocationAvailability(googleApiClient); return (la != null && la.isLocationAvailable()); } catch (SecurityException e) { if (!quiet) Log.e(getClass().getSimpleName(), "Error while checking location availability:\n " + e.toString()); if (listener != null) listener.onError(ErrorType.RETRIEVAL, "Could not check location availability:\n" + e.getMessage()); return false; } } private void checkProviders() { // Do it the old fashioned way LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (gps || network) return; if (listener != null) listener.onFallBackToSystemSettings(onGoToLocationSettingsFromView, onGoToLocationSettingsFromDialog); else if (!quiet) Log.e(getClass().getSimpleName(), "Location providers need to be enabled, but no listener is " + "registered! Specify a valid listener when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); } private void requestLocationUpdates() { if (!googleApiClient.isConnected() || !permissionGranted || !locationRequested) return; try { LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); updatesRequested = true; } catch (SecurityException e) { if (!quiet) Log.e(getClass().getSimpleName(), "Error while requesting location updates:\n " + e.toString()); if (listener != null) listener.onError(ErrorType.RETRIEVAL, "Could not request location updates:\n" + e.getMessage()); } } private DialogInterface.OnClickListener onGoToLocationSettingsFromDialog = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (activity != null) { Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); activity.startActivity(intent); } else if (!quiet) Log.e(getClass().getSimpleName(), "Need to launch an intent, but no activity is registered! " + "Specify a valid activity when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); } }; private View.OnClickListener onGoToLocationSettingsFromView = new View.OnClickListener() { @Override public void onClick(View v) { if (activity != null) { Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); activity.startActivity(intent); } else if (!quiet) Log.e(getClass().getSimpleName(), "Need to launch an intent, but no activity is registered! " + "Specify a valid activity when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); } }; private DialogInterface.OnClickListener onGoToDevSettingsFromDialog = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (activity != null) { Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS); activity.startActivity(intent); } else if (!quiet) Log.e(getClass().getSimpleName(), "Need to launch an intent, but no activity is registered! " + "Specify a valid activity when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); } }; private View.OnClickListener onGoToDevSettingsFromView = new View.OnClickListener() { @Override public void onClick(View v) { if (activity != null) { Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS); activity.startActivity(intent); } else if (!quiet) Log.e(getClass().getSimpleName(), "Need to launch an intent, but no activity is registered! " + "Specify a valid activity when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); } }; private DialogInterface.OnClickListener onGoToAppSettingsFromDialog = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (activity != null) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", activity.getPackageName(), null); intent.setData(uri); activity.startActivity(intent); } else if (!quiet) Log.e(getClass().getSimpleName(), "Need to launch an intent, but no activity is registered! " + "Specify a valid activity when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); } }; private View.OnClickListener onGoToAppSettingsFromView = new View.OnClickListener() { @Override public void onClick(View v) { if (activity != null) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", activity.getPackageName(), null); intent.setData(uri); activity.startActivity(intent); } else if (!quiet) Log.e(getClass().getSimpleName(), "Need to launch an intent, but no activity is registered! " + "Specify a valid activity when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); } }; private boolean isLocationPlausible(Location location) { if (location == null) return false; boolean isMock = mockLocationsEnabled || (Build.VERSION.SDK_INT >= 18 && location.isFromMockProvider()); if (isMock) { lastMockLocation = location; numGoodReadings = 0; } else numGoodReadings = Math.min(numGoodReadings + 1, 1000000); // Prevent overflow // We only clear that incident record after a significant show of good behavior if (numGoodReadings >= 20) lastMockLocation = null; // If there's nothing to compare against, we have to trust it if (lastMockLocation == null) return true; // And finally, if it's more than 1km away from the last known mock, we'll trust it double d = location.distanceTo(lastMockLocation); return (d > 1000); } @Override public void onConnected(@Nullable Bundle bundle) { acquireLocation(); } @Override public void onConnectionSuspended(int i) { } @Override public void onLocationChanged(Location location) { if (location == null) return; boolean plausible = isLocationPlausible(location); if (verbose && !quiet) Log.i(getClass().getSimpleName(), location.toString() + (plausible ? " -> plausible" : " -> not plausible")); if (!allowMockLocations && !plausible) { if (listener != null) listener.onMockLocationsDetected(onGoToDevSettingsFromView, onGoToDevSettingsFromDialog); return; } bestLocation = location; if (listener != null) listener.onNewLocationAvailable(location); else if (!quiet) Log.w(getClass().getSimpleName(), "New location is available, but no listener is registered!\n" + "Specify a valid listener when constructing " + getClass().getSimpleName() + " or register it explicitly with register()."); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { if (!quiet) Log.e(getClass().getSimpleName(), "Error while trying to connect to Google API:\n" + connectionResult.getErrorMessage()); if (listener != null) listener.onError(ErrorType.RETRIEVAL, "Could not connect to Google API:\n" + connectionResult.getErrorMessage()); } ResultCallback<LocationSettingsResult> onLocationSettingsReceived = new ResultCallback<LocationSettingsResult>() { @Override public void onResult(@NonNull LocationSettingsResult result) { locationRequested = true; locationStatus = result.getStatus(); switch (locationStatus.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: locationStatusOk = true; checkInitialLocation(); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: locationStatusOk = false; changeSettings = true; break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: locationStatusOk = false; break; } acquireLocation(); } }; }
apache-2.0
leangen/GraphQL-SPQR
src/main/java/io/leangen/graphql/metadata/strategy/query/DefaultOperationInfoGenerator.java
1396
package io.leangen.graphql.metadata.strategy.query; import io.leangen.graphql.metadata.exceptions.TypeMappingException; import io.leangen.graphql.util.Utils; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Member; /** * Created by bojan.tomic on 3/11/16. */ public class DefaultOperationInfoGenerator implements OperationInfoGenerator { private OperationInfoGenerator delegate = new PropertyOperationInfoGenerator(); @Override public String name(OperationInfoGeneratorParams params) { AnnotatedElement element = params.getElement().getElements().get(0); if (!(element instanceof Member)) { throw new TypeMappingException("Only fields and methods can be mapped to GraphQL operations. " + "Encountered: " + element.getClass().getName()); } return Utils.coalesce(delegate.name(params), ((Member) element).getName()); } @Override public String description(OperationInfoGeneratorParams params) { return delegate.description(params); } @Override public String deprecationReason(OperationInfoGeneratorParams params) { return delegate.deprecationReason(params); } @SuppressWarnings("WeakerAccess") public DefaultOperationInfoGenerator withDelegate(OperationInfoGenerator delegate) { this.delegate = delegate; return this; } }
apache-2.0
SURFnet/conext-operations-support
src/Surfnet/Conext/OperationsSupportBundle/Reporter/CliReporter.php
3453
<?php /** * Copyright 2015 SURFnet B.V. * * 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. */ namespace Surfnet\Conext\OperationsSupportBundle\Reporter; use Surfnet\Conext\EntityVerificationFramework\Api\VerificationReporter; use Surfnet\Conext\EntityVerificationFramework\Api\VerificationSuiteResult; use Surfnet\Conext\EntityVerificationFramework\Api\VerificationTestResult; use Surfnet\Conext\EntityVerificationFramework\Value\Entity; use Surfnet\Conext\OperationsSupportBundle\Exception\LogicException; use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\Output; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\Question; final class CliReporter implements VerificationReporter { const REPORT = <<<REPORT <comment>%8s</comment> <info>%s</info> failed for entity <info>%s</info> Reason: %s %s REPORT; /** * @var InputInterface */ private $input; /** * @var OutputInterface */ private $output; public function __construct(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; } public function reportFailedVerificationFor(Entity $entity, VerificationSuiteResult $result) { if (!$result->hasTestFailed()) { throw new LogicException('Cannot report test that has not failed'); } $severityName = $this->getSeverityName($result->getSeverity()); $failedTestName = $result->getFailedTestName(); $reason = $result->getReason(); // Indent explanation $explanation = preg_replace('~^~m', ' ', $result->getExplanation()); $this->output->writeln(sprintf(self::REPORT, $severityName, $failedTestName, $entity, $reason, $explanation)); if ($this->output instanceof Output && $this->output->isDebug()) { $questionHelper = new QuestionHelper(); $questionHelper->ask($this->input, $this->output, new Question('Press RETURN to continue...')); } } /** * @param int $severity * @return string */ private function getSeverityName($severity) { switch ($severity) { case VerificationTestResult::SEVERITY_CRITICAL: return 'CRITICAL'; case VerificationTestResult::SEVERITY_HIGH: return 'HIGH'; case VerificationTestResult::SEVERITY_MEDIUM: return 'MEDIUM'; case VerificationTestResult::SEVERITY_LOW: return 'LOW'; case VerificationTestResult::SEVERITY_TRIVIAL: return 'TRIVIAL'; default: throw new LogicException( sprintf('Cannot determine string representation of unknown severity %d', $severity) ); } } }
apache-2.0
ivanceras/svgbobrus
svgbob/src/buffer/fragment_buffer/fragment_tree.rs
8170
use crate::{buffer::Settings, Fragment}; use sauron::{html::attributes::*, Node}; /// A tree of fragments where a fragment can contain other fragments /// when those fragments are inside in this fragment /// The main purpose of this struct is for tagging fragments /// such as rect and circles to have a CellText fragment inside that are special /// text commands such as css classes, which the user can style the containing fragment #[derive(Debug, Clone, PartialEq)] pub struct FragmentTree { fragment: Fragment, css_tag: Vec<String>, enclosing: Vec<FragmentTree>, } impl FragmentTree { pub(crate) fn new(fragment: Fragment) -> Self { FragmentTree { fragment, css_tag: vec![], enclosing: vec![], } } fn can_fit(&self, other: &Self) -> bool { self.fragment.can_fit(&other.fragment) } /// check if this fragment can fit to this fragment tree. /// this also check if any of the children of this tree can fit /// the fragment fn enclose(&mut self, other: &Self) -> bool { if self.can_fit(other) { self.enclosing.push(other.clone()); return true; } else { for child in &mut self.enclosing { if child.enclose(other) { return true; } } false } } /// Try to put the other fragment somwhere in the tree, but traversing the depth first. /// This is needed for accurately tagging which shapes by putting the right cell_text into /// it's direct parent instead of just checking whether the text is bounded by some shapes. fn enclose_deep_first(&mut self, other: &Self) -> bool { for child in &mut self.enclosing { if child.enclose_deep_first(other) { return true; } } if self.can_fit(other) { let css_tags = other.fragment.as_css_tag(); if !css_tags.is_empty() { self.css_tag.extend(css_tags); } else { self.enclosing.push(other.clone()); } true } else { false } } pub(crate) fn enclose_fragments(fragments: Vec<Fragment>) -> Vec<Self> { let fragment_trees: Vec<Self> = fragments .into_iter() .map(|frag| FragmentTree::new(frag)) .collect(); Self::enclose_recursive(fragment_trees) } pub(crate) fn enclose_recursive(fragment_trees: Vec<Self>) -> Vec<Self> { let original_len = fragment_trees.len(); let merged = Self::second_pass_enclose(fragment_trees); if merged.len() < original_len { Self::enclose_recursive(merged) } else { merged } } /// make all the fragments a fragment tree and try to fit each other fn second_pass_enclose(fragment_trees: Vec<Self>) -> Vec<Self> { let mut new_trees: Vec<Self> = vec![]; for frag_tree in fragment_trees { let is_enclosed = new_trees .iter_mut() .rev() .any(|new_tree| new_tree.enclose_deep_first(&frag_tree)); if !is_enclosed { new_trees.push(frag_tree); } } new_trees } /// convert back into fragments fn into_nodes<MSG>(self) -> Vec<Node<MSG>> { let mut nodes = vec![]; let mut fragment_node: Node<MSG> = self.fragment.into(); fragment_node = fragment_node.add_attributes(vec![classes(self.css_tag)]); nodes.push(fragment_node); for child in self.enclosing { nodes.extend(child.into_nodes()) } nodes } /// convert fragments to node, where cell_text and text may become /// css class of the contain fragment pub(crate) fn fragments_to_node<MSG>(fragments: Vec<Fragment>) -> Vec<Node<MSG>> { let fragment_trees: Vec<FragmentTree> = Self::enclose_fragments(fragments); fragment_trees .into_iter() .flat_map(|frag_tree| frag_tree.into_nodes()) .collect() } } #[cfg(test)] mod tests { use super::*; extern crate test; use crate::{ buffer::Cell, fragment::{rect, CellText}, Point, }; #[test] fn test_enclose() { let mut rect1 = FragmentTree::new(rect( Point::new(0.0, 0.0), Point::new(10.0, 10.0), false, false, )); let rect2 = FragmentTree::new(rect( Point::new(1.0, 1.0), Point::new(9.0, 9.0), false, false, )); let text1 = FragmentTree::new(Fragment::CellText(CellText::new( Cell::new(2, 2), "{doc}".to_string(), ))); let text2 = FragmentTree::new(Fragment::CellText(CellText::new( Cell::new(2, 2), "This is a hello world!".to_string(), ))); assert!(rect1.enclose(&rect2)); assert!(rect1.enclose(&text1)); assert!(!rect1.enclose(&text2)); dbg!(rect1); } #[test] fn test_enclose_recursive() { let mut rect1 = rect(Point::new(0.0, 0.0), Point::new(10.0, 10.0), false, false); let rect2 = rect(Point::new(1.0, 1.0), Point::new(9.0, 9.0), false, false); let text1 = Fragment::CellText(CellText::new(Cell::new(2, 2), "{doc}".to_string())); let text2 = Fragment::CellText(CellText::new( Cell::new(2, 2), "This is a hello world!".to_string(), )); let fragments = vec![rect1, rect2, text1, text2]; let fragment_trees = FragmentTree::enclose_fragments(fragments); dbg!(&fragment_trees); assert_eq!( fragment_trees, vec![ FragmentTree { fragment: rect(Point::new(0.0, 0.0), Point::new(10.0, 10.0), false, false), css_tag: vec![], enclosing: vec![FragmentTree { fragment: rect(Point::new(1.0, 1.0), Point::new(9.0, 9.0), false, false), css_tag: vec!["doc".to_string()], enclosing: vec![], },], }, FragmentTree { fragment: Fragment::CellText(CellText::new( Cell::new(2, 2), "This is a hello world!".to_string(), )), css_tag: vec![], enclosing: vec![], }, ] ); } #[test] fn test_enclose_recursive_different_order() { let mut rect1 = rect(Point::new(0.0, 0.0), Point::new(10.0, 10.0), false, false); let rect2 = rect(Point::new(1.0, 1.0), Point::new(9.0, 9.0), false, false); let text1 = Fragment::CellText(CellText::new(Cell::new(2, 2), "{doc}".to_string())); let text2 = Fragment::CellText(CellText::new( Cell::new(2, 2), "This is a hello world!".to_string(), )); let fragments = vec![rect1, rect2, text1, text2]; let fragment_trees = FragmentTree::enclose_fragments(fragments); dbg!(&fragment_trees); assert_eq!( fragment_trees, vec![ FragmentTree { fragment: rect(Point::new(0.0, 0.0), Point::new(10.0, 10.0), false, false), css_tag: vec![], enclosing: vec![FragmentTree { fragment: rect(Point::new(1.0, 1.0), Point::new(9.0, 9.0), false, false), css_tag: vec!["doc".to_string()], enclosing: vec![], },], }, FragmentTree { fragment: Fragment::CellText(CellText::new( Cell::new(2, 2), "This is a hello world!".to_string(), )), css_tag: vec![], enclosing: vec![], }, ] ); } }
apache-2.0
vorburger/HoTea
ch.vorburger.hotea.minecraft.example/src/main/java/ch/vorburger/minecraft/hot/HotSpongePlugin.java
1438
package ch.vorburger.minecraft.hot; import java.util.Optional; import javax.inject.Inject; import org.slf4j.Logger; import org.spongepowered.api.Game; import org.spongepowered.api.command.CommandMapping; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GameStartingServerEvent; import org.spongepowered.api.event.game.state.GameStoppingServerEvent; import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.plugin.PluginContainer; import org.spongepowered.api.text.Text; @Plugin(id = "ch.vorburger.minecraft.hot.example", name = "HOT Sponge Plug-In", version = "1.0") public class HotSpongePlugin { @Inject Game game; @Inject PluginContainer plugin; @Inject Logger logger; Optional<CommandMapping> commandMapping = Optional.empty(); @Listener public void onPluginLoaded(GameStartingServerEvent event) { logger.info("I'm loaded! ;)"); CommandSpec myCommandSpec = CommandSpec.builder() .description(Text.of("Hello World Command")) .executor(new HelloWorldCommand()) .build(); commandMapping = game.getCommandManager().register(plugin, myCommandSpec, "hello"); } @Listener public void onPluginUnloading(GameStoppingServerEvent event) { logger.info("I'm unloading.. :("); if (commandMapping.isPresent()) { game.getCommandManager().removeMapping(commandMapping.get()); } } }
apache-2.0
JayZhuCoding/Client_Middleware
src/com/jz/uploadimage/Const.java
325
package com.jz.uploadimage; /** * Created by Jay. */ public class Const { // url for uploading public static final String UPLOAD_URL="http://192.168.2.1:8080/uploadImage/UploadServlet"; // url for downloading public static final String DOWNLOAD_URL="http://192.168.2.1:8080/uploadImage/UploadServlet"; }
apache-2.0
westfruit/wshop
src/main/java/com/wshop/web/dto/ProductDTO.java
9529
/* */ package com.wshop.web.dto; /* */ /* */ import com.fasterxml.jackson.annotation.JsonProperty; /* */ import java.io.Serializable; /* */ import java.math.BigDecimal; /* */ import java.util.ArrayList; /* */ import java.util.Arrays; /* */ import java.util.Collection; /* */ import java.util.Date; /* */ import java.util.List; /* */ /* */ public class ProductDTO /* */ implements Serializable /* */ { /* */ private static final long serialVersionUID = -3264773012421841094L; /* */ @JsonProperty("ProductId") /* 30 */ private Integer productid = Integer.valueOf(0); /* */ @JsonProperty("Title") /* 33 */ private String title = ""; /* */ @JsonProperty("SearchTitle") /* 37 */ private String searchtitle = ""; /* */ @JsonProperty("Summery") /* 41 */ private String summery = ""; /* */ @JsonProperty("CateId") /* 46 */ private Integer cateid = Integer.valueOf(0); /* */ @JsonProperty("CateName") /* 49 */ private String catename = ""; /* */ @JsonProperty("BrandName") /* 53 */ private String brandname = ""; /* */ @JsonProperty("ProductImg") /* 57 */ private String productimg = ""; /* */ @JsonProperty("SellPrice") /* 61 */ private BigDecimal sellprice = new BigDecimal(0); /* */ @JsonProperty("ProductAlbum") /* 65 */ private String productalbum = ""; /* */ @JsonProperty("VerifyStatus") /* 70 */ private Integer verifystatus = Integer.valueOf(0); /* */ @JsonProperty("ShelveStatus") /* 74 */ private Integer shelvestatus = Integer.valueOf(0); /* */ @JsonProperty("UpdateTime") /* 77 */ private Date updatetime = new Date(); /* */ @JsonProperty("SkuList") /* 80 */ private List<ProductSkuDTO> skuList = new ArrayList() {}; /* */ @JsonProperty("AttributeList") /* 83 */ private Collection<ProductAttributeDTO> attributelist = new ArrayList() {}; /* */ @JsonProperty("AttributeMapList") /* 86 */ private List<ProductAttributeDTO> attributeMaplist = new ArrayList() {}; /* */ @JsonProperty("DynamicList") /* 89 */ private List<DynamicDTO> dynamiclist = new ArrayList() {}; /* */ @JsonProperty("DynamicMapList") /* 92 */ private List<DynamicProductMapDTO> dynamicmaplist = new ArrayList() {}; /* */ @JsonProperty("Album") /* 95 */ private List<String> album = new ArrayList(); /* */ @JsonProperty("Content") /* 98 */ private String content = ""; /* */ @JsonProperty("ServiceInfo") /* 101 */ private String serviceinfo = ""; /* */ @JsonProperty("ProductRelatedList") /* 104 */ private List<ProductRelatedMapDTO> productrelatedlist = new ArrayList() {}; /* */ @JsonProperty("ProductGiftList") /* 107 */ private List<ProductGiftMapDTO> productgiftlist = new ArrayList() {}; /* */ /* */ public List<String> getAlbum() /* */ { /* 116 */ if ((null != this.productalbum) && (this.productalbum.length() > 0)) { /* 117 */ return Arrays.asList(this.productalbum.trim().split(",")); /* */ } /* 119 */ return this.album; /* */ } /* */ /* */ public void setAlbum(List<String> list) /* */ { /* 128 */ this.album = list; /* */ } /* */ /* */ public Collection<ProductAttributeDTO> getAttributelist() /* */ { /* 136 */ return this.attributelist; /* */ } /* */ /* */ public void setAttributelist(Collection<ProductAttributeDTO> list) /* */ { /* 145 */ this.attributelist = list; /* */ } /* */ /* */ public List<ProductAttributeDTO> getAttributemapList() /* */ { /* 154 */ return this.attributeMaplist; /* */ } /* */ /* */ public void setAttributemapList(List<ProductAttributeDTO> attributeMaplist) /* */ { /* 163 */ this.attributeMaplist = attributeMaplist; /* */ } /* */ /* */ public List<ProductSkuDTO> getSkuList() /* */ { /* 172 */ return this.skuList; /* */ } /* */ /* */ public void setSkuList(List<ProductSkuDTO> list) /* */ { /* 181 */ this.skuList = list; /* */ } /* */ /* */ public Integer getProductid() /* */ { /* 190 */ return this.productid; /* */ } /* */ /* */ public void setProductid(Integer productid) /* */ { /* 199 */ this.productid = productid; /* */ } /* */ /* */ public String getTitle() /* */ { /* 208 */ return this.title; /* */ } /* */ /* */ public void setTitle(String title) /* */ { /* 217 */ this.title = title; /* */ } /* */ /* */ public String getSearchtitle() /* */ { /* 226 */ return this.searchtitle; /* */ } /* */ /* */ public void setSearchtitle(String searchtitle) /* */ { /* 235 */ this.searchtitle = searchtitle; /* */ } /* */ /* */ public String getSummery() /* */ { /* 244 */ return this.summery; /* */ } /* */ /* */ public void setSummery(String summery) /* */ { /* 253 */ this.summery = summery; /* */ } /* */ /* */ public Integer getCateid() /* */ { /* 262 */ return this.cateid; /* */ } /* */ /* */ public void setCateid(Integer cateid) /* */ { /* 271 */ this.cateid = cateid; /* */ } /* */ /* */ public String getCatename() /* */ { /* 280 */ return this.catename; /* */ } /* */ /* */ public void setCatename(String catename) /* */ { /* 289 */ this.catename = catename; /* */ } /* */ /* */ public String getBrandname() /* */ { /* 298 */ return this.brandname; /* */ } /* */ /* */ public void setBrandname(String brandname) /* */ { /* 307 */ this.brandname = brandname; /* */ } /* */ /* */ public String getProductimg() /* */ { /* 316 */ return this.productimg; /* */ } /* */ /* */ public void setProductimg(String productimg) /* */ { /* 325 */ this.productimg = productimg; /* */ } /* */ /* */ public String getProductalbum() /* */ { /* 334 */ return this.productalbum; /* */ } /* */ /* */ public void setProductalbum(String productalbum) /* */ { /* 343 */ this.productalbum = productalbum; /* */ } /* */ /* */ public Integer getVerifystatus() /* */ { /* 352 */ return this.verifystatus; /* */ } /* */ /* */ public void setVerifystatus(Integer verifystatus) /* */ { /* 361 */ this.verifystatus = verifystatus; /* */ } /* */ /* */ public Integer getShelvestatus() /* */ { /* 370 */ return this.shelvestatus; /* */ } /* */ /* */ public void setShelvestatus(Integer shelvestatus) /* */ { /* 379 */ this.shelvestatus = shelvestatus; /* */ } /* */ /* */ public Date getUpdatetime() /* */ { /* 388 */ return this.updatetime; /* */ } /* */ /* */ public void setUpdatetime(Date updatetime) /* */ { /* 397 */ this.updatetime = updatetime; /* */ } /* */ /* */ public String getContent() /* */ { /* 412 */ return this.content; /* */ } /* */ /* */ public void setContent(String content) /* */ { /* 421 */ this.content = content; /* */ } /* */ /* */ public String getServiceinfo() /* */ { /* 431 */ return this.serviceinfo; /* */ } /* */ /* */ public void setServiceinfo(String serviceinfo) /* */ { /* 440 */ this.serviceinfo = serviceinfo; /* */ } /* */ /* */ public List<ProductRelatedMapDTO> getProductrelatedlist() /* */ { /* 444 */ return this.productrelatedlist; /* */ } /* */ /* */ public void setProductrelatedlist(List<ProductRelatedMapDTO> productrelatedlist) /* */ { /* 448 */ this.productrelatedlist = productrelatedlist; /* */ } /* */ /* */ public List<ProductGiftMapDTO> getProductgiftlist() /* */ { /* 452 */ return this.productgiftlist; /* */ } /* */ /* */ public void setProductgiftlist(List<ProductGiftMapDTO> productgiftlist) /* */ { /* 456 */ this.productgiftlist = productgiftlist; /* */ } /* */ /* */ public List<DynamicDTO> getDynamiclist() /* */ { /* 460 */ return this.dynamiclist; /* */ } /* */ /* */ public void setDynamiclist(List<DynamicDTO> dynamiclist) /* */ { /* 464 */ this.dynamiclist = dynamiclist; /* */ } /* */ /* */ public List<DynamicProductMapDTO> getDynamicmaplist() /* */ { /* 468 */ return this.dynamicmaplist; /* */ } /* */ /* */ public void setDynamicmaplist(List<DynamicProductMapDTO> dynamicmaplist) /* */ { /* 472 */ this.dynamicmaplist = dynamicmaplist; /* */ } /* */ /* */ public BigDecimal getSellprice() /* */ { /* 476 */ return this.sellprice; /* */ } /* */ /* */ public void setSellprice(BigDecimal sellprice) /* */ { /* 480 */ this.sellprice = sellprice; /* */ } /* */ } /* Location: H:\Java\SpringBoot\wshop-0.0.1-SNAPSHOT\BOOT-INF\classes\ * Qualified Name: com.wshop.web.dto.ProductDTO * JD-Core Version: 0.7.0.1 */
apache-2.0
mahkoh/rust
src/liballoc/heap.rs
13363
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // FIXME: #13996: mark the `allocate` and `reallocate` return value as `noalias` /// Return a pointer to `size` bytes of memory aligned to `align`. /// /// On failure, return a null pointer. /// /// Behavior is undefined if the requested size is 0 or the alignment is not a /// power of 2. The alignment must be no larger than the largest supported page /// size on the platform. #[inline] pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 { imp::allocate(size, align) } /// Resize the allocation referenced by `ptr` to `size` bytes. /// /// On failure, return a null pointer and leave the original allocation intact. /// /// Behavior is undefined if the requested size is 0 or the alignment is not a /// power of 2. The alignment must be no larger than the largest supported page /// size on the platform. /// /// The `old_size` and `align` parameters are the parameters that were used to /// create the allocation referenced by `ptr`. The `old_size` parameter may be /// any value in range_inclusive(requested_size, usable_size). #[inline] pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 { imp::reallocate(ptr, old_size, size, align) } /// Resize the allocation referenced by `ptr` to `size` bytes. /// /// If the operation succeeds, it returns `usable_size(size, align)` and if it /// fails (or is a no-op) it returns `usable_size(old_size, align)`. /// /// Behavior is undefined if the requested size is 0 or the alignment is not a /// power of 2. The alignment must be no larger than the largest supported page /// size on the platform. /// /// The `old_size` and `align` parameters are the parameters that were used to /// create the allocation referenced by `ptr`. The `old_size` parameter may be /// any value in range_inclusive(requested_size, usable_size). #[inline] pub unsafe fn reallocate_inplace(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> usize { imp::reallocate_inplace(ptr, old_size, size, align) } /// Deallocates the memory referenced by `ptr`. /// /// The `ptr` parameter must not be null. /// /// The `old_size` and `align` parameters are the parameters that were used to /// create the allocation referenced by `ptr`. The `old_size` parameter may be /// any value in range_inclusive(requested_size, usable_size). #[inline] pub unsafe fn deallocate(ptr: *mut u8, old_size: usize, align: usize) { imp::deallocate(ptr, old_size, align) } /// Returns the usable size of an allocation created with the specified the /// `size` and `align`. #[inline] pub fn usable_size(size: usize, align: usize) -> usize { imp::usable_size(size, align) } /// Prints implementation-defined allocator statistics. /// /// These statistics may be inconsistent if other threads use the allocator /// during the call. #[unstable(feature = "alloc")] pub fn stats_print() { imp::stats_print(); } /// An arbitrary non-null address to represent zero-size allocations. /// /// This preserves the non-null invariant for types like `Box<T>`. The address may overlap with /// non-zero-size memory allocations. pub const EMPTY: *mut () = 0x1 as *mut (); /// The allocator for unique pointers. #[cfg(not(test))] #[lang="exchange_malloc"] #[inline] unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 { if size == 0 { EMPTY as *mut u8 } else { let ptr = allocate(size, align); if ptr.is_null() { ::oom() } ptr } } #[cfg(not(test))] #[lang="exchange_free"] #[inline] unsafe fn exchange_free(ptr: *mut u8, old_size: usize, align: usize) { deallocate(ptr, old_size, align); } // The minimum alignment guaranteed by the architecture. This value is used to // add fast paths for low alignment values. In practice, the alignment is a // constant at the call site and the branch will be optimized out. #[cfg(all(not(feature = "external_funcs"), not(feature = "external_crate"), any(target_arch = "arm", target_arch = "mips", target_arch = "mipsel", target_arch = "powerpc")))] const MIN_ALIGN: usize = 8; #[cfg(all(not(feature = "external_funcs"), not(feature = "external_crate"), any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))] const MIN_ALIGN: usize = 16; #[cfg(feature = "external_funcs")] mod imp { extern { fn rust_allocate(size: usize, align: usize) -> *mut u8; fn rust_deallocate(ptr: *mut u8, old_size: usize, align: usize); fn rust_reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8; fn rust_reallocate_inplace(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> usize; fn rust_usable_size(size: usize, align: usize) -> usize; fn rust_stats_print(); } #[inline] pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 { rust_allocate(size, align) } #[inline] pub unsafe fn deallocate(ptr: *mut u8, old_size: usize, align: usize) { rust_deallocate(ptr, old_size, align) } #[inline] pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 { rust_reallocate(ptr, old_size, size, align) } #[inline] pub unsafe fn reallocate_inplace(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> usize { rust_reallocate_inplace(ptr, old_size, size, align) } #[inline] pub fn usable_size(size: usize, align: usize) -> usize { unsafe { rust_usable_size(size, align) } } #[inline] pub fn stats_print() { unsafe { rust_stats_print() } } } #[cfg(feature = "external_crate")] mod imp { extern crate external; pub use self::external::{allocate, deallocate, reallocate_inplace, reallocate}; pub use self::external::{usable_size, stats_print}; } #[cfg(all(not(feature = "external_funcs"), not(feature = "external_crate"), jemalloc))] mod imp { use core::option::Option; use core::option::Option::None; use core::ptr::{null_mut, null}; use core::num::Int; use libc::{c_char, c_int, c_void, size_t}; use super::MIN_ALIGN; #[link(name = "jemalloc", kind = "static")] #[cfg(not(test))] extern {} extern { #[allocator] fn je_mallocx(size: size_t, flags: c_int) -> *mut c_void; fn je_rallocx(ptr: *mut c_void, size: size_t, flags: c_int) -> *mut c_void; fn je_xallocx(ptr: *mut c_void, size: size_t, extra: size_t, flags: c_int) -> size_t; fn je_sdallocx(ptr: *mut c_void, size: size_t, flags: c_int); fn je_nallocx(size: size_t, flags: c_int) -> size_t; fn je_malloc_stats_print(write_cb: Option<extern "C" fn(cbopaque: *mut c_void, *const c_char)>, cbopaque: *mut c_void, opts: *const c_char); } // -lpthread needs to occur after -ljemalloc, the earlier argument isn't enough #[cfg(all(not(windows), not(target_os = "android")))] #[link(name = "pthread")] extern {} // MALLOCX_ALIGN(a) macro #[inline(always)] fn mallocx_align(a: usize) -> c_int { a.trailing_zeros() as c_int } #[inline(always)] fn align_to_flags(align: usize) -> c_int { if align <= MIN_ALIGN { 0 } else { mallocx_align(align) } } #[inline] pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 { let flags = align_to_flags(align); je_mallocx(size as size_t, flags) as *mut u8 } #[inline] pub unsafe fn reallocate(ptr: *mut u8, _old_size: usize, size: usize, align: usize) -> *mut u8 { let flags = align_to_flags(align); je_rallocx(ptr as *mut c_void, size as size_t, flags) as *mut u8 } #[inline] pub unsafe fn reallocate_inplace(ptr: *mut u8, _old_size: usize, size: usize, align: usize) -> usize { let flags = align_to_flags(align); je_xallocx(ptr as *mut c_void, size as size_t, 0, flags) as usize } #[inline] pub unsafe fn deallocate(ptr: *mut u8, old_size: usize, align: usize) { let flags = align_to_flags(align); je_sdallocx(ptr as *mut c_void, old_size as size_t, flags) } #[inline] pub fn usable_size(size: usize, align: usize) -> usize { let flags = align_to_flags(align); unsafe { je_nallocx(size as size_t, flags) as usize } } pub fn stats_print() { unsafe { je_malloc_stats_print(None, null_mut(), null()) } } } #[cfg(all(not(feature = "external_funcs"), not(feature = "external_crate"), not(jemalloc), unix))] mod imp { use core::cmp; use core::ptr; use libc; use super::MIN_ALIGN; extern { fn posix_memalign(memptr: *mut *mut libc::c_void, align: libc::size_t, size: libc::size_t) -> libc::c_int; } #[inline] pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 { if align <= MIN_ALIGN { libc::malloc(size as libc::size_t) as *mut u8 } else { let mut out = ptr::null_mut(); let ret = posix_memalign(&mut out, align as libc::size_t, size as libc::size_t); if ret != 0 { ptr::null_mut() } else { out as *mut u8 } } } #[inline] pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 { if align <= MIN_ALIGN { libc::realloc(ptr as *mut libc::c_void, size as libc::size_t) as *mut u8 } else { let new_ptr = allocate(size, align); ptr::copy(new_ptr, ptr, cmp::min(size, old_size)); deallocate(ptr, old_size, align); new_ptr } } #[inline] pub unsafe fn reallocate_inplace(_ptr: *mut u8, old_size: usize, _size: usize, _align: usize) -> usize { old_size } #[inline] pub unsafe fn deallocate(ptr: *mut u8, _old_size: usize, _align: usize) { libc::free(ptr as *mut libc::c_void) } #[inline] pub fn usable_size(size: usize, _align: usize) -> usize { size } pub fn stats_print() {} } #[cfg(all(not(feature = "external_funcs"), not(feature = "external_crate"), not(jemalloc), windows))] mod imp { use libc::{c_void, size_t}; use libc; use super::MIN_ALIGN; extern { fn _aligned_malloc(size: size_t, align: size_t) -> *mut c_void; fn _aligned_realloc(block: *mut c_void, size: size_t, align: size_t) -> *mut c_void; fn _aligned_free(ptr: *mut c_void); } #[inline] pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 { if align <= MIN_ALIGN { libc::malloc(size as size_t) as *mut u8 } else { _aligned_malloc(size as size_t, align as size_t) as *mut u8 } } #[inline] pub unsafe fn reallocate(ptr: *mut u8, _old_size: usize, size: usize, align: usize) -> *mut u8 { if align <= MIN_ALIGN { libc::realloc(ptr as *mut c_void, size as size_t) as *mut u8 } else { _aligned_realloc(ptr as *mut c_void, size as size_t, align as size_t) as *mut u8 } } #[inline] pub unsafe fn reallocate_inplace(_ptr: *mut u8, old_size: usize, _size: usize, _align: usize) -> usize { old_size } #[inline] pub unsafe fn deallocate(ptr: *mut u8, _old_size: usize, align: usize) { if align <= MIN_ALIGN { libc::free(ptr as *mut libc::c_void) } else { _aligned_free(ptr as *mut c_void) } } #[inline] pub fn usable_size(size: usize, _align: usize) -> usize { size } pub fn stats_print() {} } #[cfg(test)] mod test { extern crate test; use self::test::Bencher; use boxed::Box; use heap; #[test] fn basic_reallocate_inplace_noop() { unsafe { let size = 4000; let ptr = heap::allocate(size, 8); if ptr.is_null() { ::oom() } let ret = heap::reallocate_inplace(ptr, size, size, 8); heap::deallocate(ptr, size, 8); assert_eq!(ret, heap::usable_size(size, 8)); } } #[bench] fn alloc_owned_small(b: &mut Bencher) { b.iter(|| { let _: Box<_> = box 10; }) } }
apache-2.0
Gagarinwjj/Cpdaily
app/src/main/java/com/wisedu/cpdaily/model/Wrapper.java
580
package com.wisedu.cpdaily.model; /** * 实体类包裹 * Created by wjj on 2017/4/7 14:47. */ public class Wrapper<T> { int errCode; String errMsg; T data; public int getErrCode() { return errCode; } public void setErrCode(int errCode) { this.errCode = errCode; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
apache-2.0
TechBossIceWobs/Info-PEAK-
Week 6/perfect_loop.rb
394
#The main formula for finding perfect numbers (as a formula): 2**(p−1)*((2**p)−1) #The above will be made into a seperate file for the purposes of the rest of this code. #This is the beginning of problem 3 for Week 6. Part 1 - repetition. #This is perfectly functional code. load ("pnum.rb") def perfect_loop(p) s = 0 for i in 2..p-1 if p % i != 0 j = s + pnum(p) end end j end
apache-2.0
CenturyLinkCloud/clc-node-sdk
test/compute-services/balancers/pools/modify-pool-test.js
2411
var _ = require('underscore'); var Promise = require('bluebird').Promise; var vcr = require('nock-vcr-recorder-mocha'); var Sdk = require('./../../../../lib/clc-sdk.js'); var compute = new Sdk('cloud_user', 'cloud_user_password').computeServices(); var assert = require('assert'); vcr.describe('Modify Load Balancer Pool Operation [UNIT]', function () { var timeout = 10 * 1000; var pools = compute.balancers().pools(); var DataCenter = compute.DataCenter; vcr.it('Should modify pool', function (done) { this.timeout(timeout); Promise.resolve() .then(_.partial(createPool, {})) .then(_.partial(modifyPool, {method: 'roundRobin', persistence: 'sticky'})) .then(assertThatPoolRefIsCorrect) .then(assertThatMethodIs('roundRobin')) .then(assertThatPersistenceIs('sticky')) .then(deletePool(done)); }); function assertPool (callback) { return function (pool) { return pools .findSingle(pool) .then(function (metadata) { return callback(metadata) || pool; }); }; } function createPool (config) { return pools .create(_.defaults(config, { balancer: { dataCenter: DataCenter.DE_FRANKFURT, name: 'Balancer', ip: '66.155.94.20' }, port: compute.Server.Port.HTTP, method: 'leastConnection', persistence: 'standard' })) .then(assertThatPoolRefIsCorrect); } function assertThatMethodIs (method) { return assertPool(function (metadata) { assert.equal(metadata.method, method); }); } function assertThatPersistenceIs(expectedPersistence) { return assertPool(function (metadata) { assert.equal(metadata.persistence, expectedPersistence); }); } function modifyPool(config, pool) { return pools.modify(pool, config); } function assertThatPoolRefIsCorrect (ref) { assert(!_.isUndefined(ref.id || ref[0].id)); return ref; } function deletePool (done) { return function (poolCriteria) { return pools.delete(poolCriteria).then(_.partial(done, undefined)); }; } });
apache-2.0
SanSYS/MassTransit
src/MassTransit.Azure.ServiceBus.Core/Transport/QueueSendClient.cs
2143
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit.Azure.ServiceBus.Core.Transport { using System; using System.Threading.Tasks; using GreenPipes; using Microsoft.Azure.ServiceBus; using Policies; public class QueueSendClient : ISendClient { readonly QueueClient _queueClient; readonly IRetryPolicy _retryPolicy; public QueueSendClient(QueueClient queueClient, IRetryPolicy retryPolicy) { _queueClient = queueClient; _retryPolicy = retryPolicy; } public string Path => _queueClient.Path; public async Task Send(Message message) { try { await _retryPolicy.Retry(() => _queueClient.SendAsync(message)).ConfigureAwait(false); } catch (InvalidOperationException exception) when (exception.Message.Contains("been consumed")) { // this is okay, it means we timed out and upon retry the message was accepted } } public Task Close() { return _queueClient.CloseAsync(); } public Task<long> ScheduleSend(Message message, DateTime scheduleEnqueueTimeUtc) { return _retryPolicy.Retry(() => _queueClient.ScheduleMessageAsync(message, scheduleEnqueueTimeUtc)); } public Task CancelScheduledSend(long sequenceNumber) { return _queueClient.CancelScheduledMessageAsync(sequenceNumber); } } }
apache-2.0
kiddinn/plaso
tests/preprocessors/windows.py
19970
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Windows preprocess plug-ins.""" import unittest from dfvfs.helpers import fake_file_system_builder from dfvfs.lib import definitions as dfvfs_definitions from dfvfs.path import factory as path_spec_factory from plaso.containers import artifacts from plaso.engine import knowledge_base from plaso.preprocessors import mediator from plaso.preprocessors import windows from tests.preprocessors import test_lib class WindowsAllUsersAppDataKnowledgeBasePluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the allusersdata knowledge base value plugin.""" def testCollect(self): """Tests the Collect function.""" plugin = windows.WindowsAllUsersAppDataKnowledgeBasePlugin() storage_writer = self._CreateTestStorageWriter() test_knowledge_base = knowledge_base.KnowledgeBase() test_mediator = mediator.PreprocessMediator( storage_writer, test_knowledge_base) plugin.Collect(test_mediator) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'allusersappdata') self.assertIsNone(environment_variable) def testCollectWithAllUsersProfile(self): """Tests the Collect function with the %AllUsersProfile% variable.""" plugin = windows.WindowsAllUsersAppDataKnowledgeBasePlugin() storage_writer = self._CreateTestStorageWriter() test_knowledge_base = knowledge_base.KnowledgeBase() test_mediator = mediator.PreprocessMediator( storage_writer, test_knowledge_base) environment_variable = artifacts.EnvironmentVariableArtifact( case_sensitive=False, name='allusersprofile', value='C:\\Documents and Settings\\All Users') test_mediator.knowledge_base.AddEnvironmentVariable(environment_variable) plugin.Collect(test_mediator) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'allusersappdata') self.assertIsNotNone(environment_variable) self.assertEqual( environment_variable.value, 'C:\\Documents and Settings\\All Users\\Application Data') def testCollectWithProgramData(self): """Tests the Collect function with the %ProgramData% variable.""" plugin = windows.WindowsAllUsersAppDataKnowledgeBasePlugin() storage_writer = self._CreateTestStorageWriter() test_knowledge_base = knowledge_base.KnowledgeBase() test_mediator = mediator.PreprocessMediator( storage_writer, test_knowledge_base) environment_variable = artifacts.EnvironmentVariableArtifact( case_sensitive=False, name='programdata', value='%SystemDrive%\\ProgramData') test_mediator.knowledge_base.AddEnvironmentVariable(environment_variable) plugin.Collect(test_mediator) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'allusersappdata') self.assertIsNotNone(environment_variable) self.assertEqual(environment_variable.value, '%SystemDrive%\\ProgramData') class WindowsAllUsersProfileEnvironmentVariablePluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the %AllUsersProfile% environment variable plugin.""" def testParseValueData(self): """Tests the _ParseValueData function.""" test_file_path = self._GetTestFilePath(['SOFTWARE']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsAllUsersProfileEnvironmentVariablePlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSoftware( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'AllUsersProfile') self.assertIsNone(environment_variable) class WindowsAllUsersAppProfileKnowledgeBasePluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the allusersprofile knowledge base value plugin.""" def testCollect(self): """Tests the Collect function.""" plugin = windows.WindowsAllUsersAppProfileKnowledgeBasePlugin() storage_writer = self._CreateTestStorageWriter() test_knowledge_base = knowledge_base.KnowledgeBase() test_mediator = mediator.PreprocessMediator( storage_writer, test_knowledge_base) plugin.Collect(test_mediator) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'allusersprofile') self.assertIsNone(environment_variable) def testCollectWithAllUsersProfile(self): """Tests the Collect function with the %AllUsersProfile% variable.""" plugin = windows.WindowsAllUsersAppProfileKnowledgeBasePlugin() storage_writer = self._CreateTestStorageWriter() test_knowledge_base = knowledge_base.KnowledgeBase() test_mediator = mediator.PreprocessMediator( storage_writer, test_knowledge_base) environment_variable = artifacts.EnvironmentVariableArtifact( case_sensitive=False, name='allusersprofile', value='C:\\Documents and Settings\\All Users') test_mediator.knowledge_base.AddEnvironmentVariable(environment_variable) plugin.Collect(test_mediator) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'allusersprofile') self.assertIsNotNone(environment_variable) self.assertEqual( environment_variable.value, 'C:\\Documents and Settings\\All Users') def testCollectWithProgramData(self): """Tests the Collect function with the %ProgramData% variable.""" plugin = windows.WindowsAllUsersAppProfileKnowledgeBasePlugin() storage_writer = self._CreateTestStorageWriter() test_knowledge_base = knowledge_base.KnowledgeBase() test_mediator = mediator.PreprocessMediator( storage_writer, test_knowledge_base) environment_variable = artifacts.EnvironmentVariableArtifact( case_sensitive=False, name='programdata', value='%SystemDrive%\\ProgramData') test_mediator.knowledge_base.AddEnvironmentVariable(environment_variable) plugin.Collect(test_mediator) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'allusersprofile') self.assertIsNotNone(environment_variable) self.assertEqual(environment_variable.value, '%SystemDrive%\\ProgramData') class WindowsAvailableTimeZonesPluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the Windows available time zones plugin.""" def testParseKey(self): """Tests the _ParseKey function.""" test_file_path = self._GetTestFilePath(['SOFTWARE']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsAvailableTimeZonesPlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSoftware( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) available_time_zones = sorted( test_mediator.knowledge_base.available_time_zones, key=lambda time_zone: time_zone.name) self.assertIsNotNone(available_time_zones) self.assertEqual(len(available_time_zones), 101) self.assertEqual(available_time_zones[0].name, 'AUS Central Standard Time') class WindowsCodepagePlugin(test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the Windows codepage plugin.""" def testParseValueData(self): """Tests the _ParseValueData function.""" test_file_path = self._GetTestFilePath(['SYSTEM']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsCodepagePlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSystem( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) self.assertEqual(test_mediator.knowledge_base.codepage, 'cp1252') class WindowsHostnamePluginTest(test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the Windows hostname plugin.""" # pylint: disable=protected-access def testParseValueData(self): """Tests the _ParseValueData function.""" test_file_path = self._GetTestFilePath(['SYSTEM']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsHostnamePlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSystem( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) self.assertEqual(test_mediator.knowledge_base.hostname, 'WKS-WIN732BITA') value_data = ['MyHost', ''] plugin._ParseValueData(test_mediator, value_data) class WindowsProgramDataEnvironmentVariablePluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the %ProgramData% environment variable plugin.""" def testParseValueData(self): """Tests the _ParseValueData function.""" test_file_path = self._GetTestFilePath(['SOFTWARE']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsProgramDataEnvironmentVariablePlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSoftware( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'ProgramData') self.assertIsNotNone(environment_variable) self.assertEqual(environment_variable.value, '%SystemDrive%\\ProgramData') class WindowsProgramDataKnowledgeBasePluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the programdata knowledge base value plugin.""" def testCollect(self): """Tests the Collect function.""" plugin = windows.WindowsProgramDataKnowledgeBasePlugin() storage_writer = self._CreateTestStorageWriter() test_knowledge_base = knowledge_base.KnowledgeBase() test_mediator = mediator.PreprocessMediator( storage_writer, test_knowledge_base) plugin.Collect(test_mediator) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'programdata') self.assertIsNone(environment_variable) def testCollectWithAllUsersProfile(self): """Tests the Collect function with the %AllUsersProfile% variable.""" plugin = windows.WindowsProgramDataKnowledgeBasePlugin() storage_writer = self._CreateTestStorageWriter() test_knowledge_base = knowledge_base.KnowledgeBase() test_mediator = mediator.PreprocessMediator( storage_writer, test_knowledge_base) environment_variable = artifacts.EnvironmentVariableArtifact( case_sensitive=False, name='allusersprofile', value='C:\\Documents and Settings\\All Users') test_mediator.knowledge_base.AddEnvironmentVariable(environment_variable) plugin.Collect(test_mediator) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'programdata') self.assertIsNotNone(environment_variable) self.assertEqual( environment_variable.value, 'C:\\Documents and Settings\\All Users') def testCollectWithProgramData(self): """Tests the Collect function with the %ProgramData% variable.""" plugin = windows.WindowsProgramDataKnowledgeBasePlugin() storage_writer = self._CreateTestStorageWriter() test_knowledge_base = knowledge_base.KnowledgeBase() test_mediator = mediator.PreprocessMediator( storage_writer, test_knowledge_base) environment_variable = artifacts.EnvironmentVariableArtifact( case_sensitive=False, name='programdata', value='%SystemDrive%\\ProgramData') test_mediator.knowledge_base.AddEnvironmentVariable(environment_variable) plugin.Collect(test_mediator) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'programdata') self.assertIsNotNone(environment_variable) self.assertEqual(environment_variable.value, '%SystemDrive%\\ProgramData') class WindowsProgramFilesEnvironmentVariablePluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the %ProgramFiles% environment variable plugin.""" def testParseValueData(self): """Tests the _ParseValueData function.""" test_file_path = self._GetTestFilePath(['SOFTWARE']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsProgramFilesEnvironmentVariablePlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSoftware( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'ProgramFiles') self.assertIsNotNone(environment_variable) self.assertEqual(environment_variable.value, 'C:\\Program Files') class WindowsProgramFilesX86EnvironmentVariablePluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the %ProgramFilesX86% environment variable plugin.""" def testParseValueData(self): """Tests the _ParseValueData function.""" test_file_path = self._GetTestFilePath(['SOFTWARE']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsProgramFilesX86EnvironmentVariablePlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSoftware( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'ProgramFilesX86') # The test SOFTWARE Registry file does not contain a value for # the Program Files X86 path. self.assertIsNone(environment_variable) class WindowsSystemRootEnvironmentVariablePluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the %SystemRoot% environment variable plugin.""" _FILE_DATA = b'regf' def testParsePathSpecification(self): """Tests the _ParsePathSpecification function.""" file_system_builder = fake_file_system_builder.FakeFileSystemBuilder() file_system_builder.AddFile( '/Windows/System32/config/SYSTEM', self._FILE_DATA) mount_point = path_spec_factory.Factory.NewPathSpec( dfvfs_definitions.TYPE_INDICATOR_FAKE, location='/') plugin = windows.WindowsSystemRootEnvironmentVariablePlugin() test_mediator = self._RunPreprocessorPluginOnFileSystem( file_system_builder.file_system, mount_point, None, plugin) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'SystemRoot') self.assertIsNotNone(environment_variable) self.assertEqual(environment_variable.value, '\\Windows') class WindowsSystemProductPluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the system product information plugin.""" def testParseValueData(self): """Tests the _ParseValueData function.""" test_file_path = self._GetTestFilePath(['SOFTWARE']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsSystemProductPlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSoftware( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) system_product = test_mediator.knowledge_base.GetValue( 'operating_system_product') self.assertEqual(system_product, 'Windows 7 Ultimate') class WindowsSystemVersionPluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the system version information plugin.""" def testParseValueData(self): """Tests the _ParseValueData function.""" test_file_path = self._GetTestFilePath(['SOFTWARE']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsSystemVersionPlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSoftware( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) system_version = test_mediator.knowledge_base.GetValue( 'operating_system_version') self.assertEqual(system_version, '6.1') class WindowsTimeZonePluginTest(test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the time zone plugin.""" def testParseValueData(self): """Tests the _ParseValueData function.""" test_file_path = self._GetTestFilePath(['SYSTEM']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsTimeZonePlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSystem( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) self.assertEqual(test_mediator.knowledge_base.timezone.zone, 'EST5EDT') class WindowsUserAccountsPluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the Windows user accounts artifacts mapping.""" # pylint: disable=protected-access def testParseKey(self): """Tests the _ParseKey function.""" test_file_path = self._GetTestFilePath(['SOFTWARE']) self._SkipIfPathNotExists(test_file_path) storage_writer = self._CreateTestStorageWriter() plugin = windows.WindowsUserAccountsPlugin() test_mediator = self._RunPreprocessorPluginOnWindowsRegistryValueSoftware( storage_writer, plugin) self.assertEqual(storage_writer.number_of_preprocessing_warnings, 0) user_accounts = sorted( test_mediator.knowledge_base.user_accounts, key=lambda user_account: user_account.identifier) self.assertIsNotNone(user_accounts) self.assertEqual(len(user_accounts), 11) user_account = user_accounts[9] expected_sid = 'S-1-5-21-2036804247-3058324640-2116585241-1114' self.assertEqual(user_account.identifier, expected_sid) self.assertEqual(user_account.username, 'rsydow') self.assertEqual(user_account.user_directory, 'C:\\Users\\rsydow') class WindowsWinDirEnvironmentVariablePluginTest( test_lib.ArtifactPreprocessorPluginTestCase): """Tests for the %WinDir% environment variable plugin.""" _FILE_DATA = b'regf' def testParsePathSpecification(self): """Tests the _ParsePathSpecification function.""" file_system_builder = fake_file_system_builder.FakeFileSystemBuilder() file_system_builder.AddFile( '/Windows/System32/config/SYSTEM', self._FILE_DATA) mount_point = path_spec_factory.Factory.NewPathSpec( dfvfs_definitions.TYPE_INDICATOR_FAKE, location='/') plugin = windows.WindowsWinDirEnvironmentVariablePlugin() test_mediator = self._RunPreprocessorPluginOnFileSystem( file_system_builder.file_system, mount_point, None, plugin) environment_variable = test_mediator.knowledge_base.GetEnvironmentVariable( 'WinDir') self.assertIsNotNone(environment_variable) self.assertEqual(environment_variable.value, '\\Windows') if __name__ == '__main__': unittest.main()
apache-2.0
28harishkumar/node-notifications
public/javascripts/socket.js
1479
function socketio(url,username, callback){ var socket = io.connect(url); socket.on('connection', function (msg) { socket.emit('auth',{user:username}) }); socket.on('listner',function(session){ socket.on(session['sessionID'], function(data){ callback(data.data); }); }); } function notifyMe(user,message) { // Let's check if the browser supports notifications if (!("Notification" in window)) { alert("This browser does not support desktop notification"); } // Let's check if the user is okay to get some notification else if (Notification.permission === "granted") { // If it's okay let's create a notification var options = { body: message, dir : "ltr" }; var notification = new Notification(user + " Posted a comment",options); } // Otherwise, we need to ask the user for permission // Note, Chrome does not implement the permission static property // So we have to check for NOT 'denied' instead of 'default' else if (Notification.permission !== 'denied') { Notification.requestPermission(function (permission) { // Whatever the user answers, we make sure we store the information if (!('permission' in Notification)) { Notification.permission = permission; } // If the user is okay, let's create a notification if (permission === "granted") { var options = { body: message, dir : "ltr" }; var notification = new Notification(user + " Posted a comment",options); } }); } }
apache-2.0
oboehm/gdv.xport
deprecated/src/main/java/gdv/xport/satz/feld/sparte30/Feld230.java
6557
/* * Copyright (c) 2011, 2012 by aosd.de * * 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 orimplied. * See the License for the specific language governing permissions and * limitations under the License. * * (c)reated 14.04.11 by oliver */ package gdv.xport.satz.feld.sparte30; import gdv.xport.annotation.*; import gdv.xport.feld.*; import gdv.xport.satz.feld.common.Feld1bis7; /** * Diese Enum-Klasse repraesentiert die Felder fuer Satzart 230, Sparte 30. * "Unfall Leistungsarten" (Satzart 0230) * * @author Ralf * @since 20.02.2013 * @deprecated Enums mit Annotationen werden ab v6 nicht mehr unterstuetzt */ @Deprecated public enum Feld230 { // /// Teildatensatz 1 ///////////////////////////////////////////////// /** Feld 1 - 7 sind fuer jeden (Teil-)Datensatz identisch. */ @FelderInfo( sparte = 30, teildatensatz = 1, type = Feld1bis7.class) INTRO2, /** * Laufende Nummer der versicherten Person (VP) / Personengruppe. */ @FeldInfo( teildatensatz = 1, nr = 8, type = NumFeld.class, anzahlBytes = 6, byteAdresse = 43) LFD_NUMMER_VP_PERSONENGRUPPE, /** * Art der Leistung. * siehe Anlage 80 */ @FeldInfo( teildatensatz = 1, nr = 9, type = NumFeld.class, anzahlBytes = 3, byteAdresse = 49) ART_DER_LEISTUNG, /** * Bezeichnung der Leistung. * Text zur Art der Leistung */ @FeldInfo( teildatensatz = 1, nr = 10, type = AlphaNumFeld.class, anzahlBytes = 30, byteAdresse = 52) BEZEICHNUNG_DER_LEISTUNG, /** * Laufende Nummer zur Art der Leistung. * Laufende Nummer zur Art der Leistung, * beginnend mit 001 innerhalb der lfd. Nummer der Person / Personengruppen */ @FeldInfo( teildatensatz = 1, nr = 11, type = NumFeld.class, anzahlBytes = 3, byteAdresse = 82) LFD_NUMMER_ZUR_ART_DER_LEISTUNG, /** * Art der Auszahlung. * 01 = Kapital * 02 = Rente * 03 = Sachleistung * 04 = Prämienfreistellung */ @FeldInfo( teildatensatz = 1, nr = 12, type = NumFeld.class, anzahlBytes = 2, byteAdresse = 85) ART_DER_AUSZAHLUNG, /** * Leistungszahlungsweise. * Es handelt sich hier um die Zahlweise bei Eintritt einer Leistung! 1 = * jährlich * 2 = halbjährlich * 3 = täglich * 4 = vierteljährlich * 5 = Sonstiges * 6 = Einmalzahlung * 7 = noch zu bestimmen * 8 = monatlich */ @FeldInfo( teildatensatz = 1, nr = 13, type = Zeichen.class, anzahlBytes = 1, byteAdresse = 87) LEISTUNGSZAHLUNGSWEISE, /** * Beginn der Zahlung ab Tag. */ @FeldInfo( teildatensatz = 1, nr = 14, type = NumFeld.class, anzahlBytes = 3, byteAdresse = 88) BEGINN_DER_ZAHLUNG_AB_TAG, /** * Leistung in WE. * (12,2 Stellen) */ @FeldInfo( teildatensatz = 1, nr = 15, type = Betrag.class, anzahlBytes = 14, byteAdresse = 91) LEISTUNG_IN_WE, /** * Beitragssatz. * (3,4 Stellen) */ @FeldInfo( teildatensatz = 1, nr = 16, type = NumFeld.class, nachkommaStellen = 4, anzahlBytes = 7, byteAdresse = 105) BEITRAGSSATZ, /** * Art des Beitragssatzes. * 01 = von Tausend (Promille) * 02 = von Hundert (Prozent) * 03 = Faktor * 04 = Fester Beitrag */ @FeldInfo( teildatensatz = 1, nr = 17, type = AlphaNumFeld.class, anzahlBytes = 2, byteAdresse = 112) ART_DES_BEITRAGSSATZES, /** * Beitrag in WE. * (10,2 Stellen) */ @FeldInfo( teildatensatz = 1, nr = 18, type = Betrag.class, anzahlBytes = 12, byteAdresse = 114) BEITRAG, /** * Prozentsatz progressive Invalidität / Mehrleistung bei Invalidität. * (10,2 Stellen) */ @FeldInfo( teildatensatz = 1, nr = 19, type = Betrag.class, nachkommaStellen = 2, anzahlBytes = 6, byteAdresse = 126) PROZENTSATZ_PROGRESSIVE_INVALIDITAET_MEHRLEISTUNG_BEI_INVALIDITAET, /** * Leistung ab Invaliditätsgrad in Prozent. * (3,4 Stellen) */ @FeldInfo( teildatensatz = 1, nr = 20, type = NumFeld.class, nachkommaStellen = 4, anzahlBytes = 7, byteAdresse = 132) LEISTUNG_AB_INVALIDITAETSGRAD_IN_PROZENT, /** * Referenznummer. */ @FeldInfo( teildatensatz = 1, nr = 21, type = AlphaNumFeld.class, anzahlBytes = 7, byteAdresse = 139) REFERENZNUMMER, /** * Dauer der Leistung in Monaten. */ @FeldInfo( teildatensatz = 1, nr = 22, type = NumFeld.class, anzahlBytes = 3, byteAdresse = 146) DAUER_DER_LEISTUNG_IN_MONATEN, /** * Ende der Leistungszahlung. */ @FeldInfo( teildatensatz = 1, nr = 23, type = NumFeld.class, anzahlBytes = 8, byteAdresse = 149) ENDE_DER_LEISTUNGSZAHLUNG, /** * Leerstellen. */ @FeldInfo( teildatensatz = 1, nr = 24, type = AlphaNumFeld.class, anzahlBytes = 99, byteAdresse = 157) LEERSTELLEN, /** * Satznummer. */ @FeldInfo( teildatensatz = 1, nr = 22, type = NumFeld.class, anzahlBytes = 1, byteAdresse = 256) SATZNUMMER1; }
apache-2.0
centreon/centreon-broker
bam/src/factory.cc
2992
/* ** Copyright 2014-2016, 2021 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #include "com/centreon/broker/bam/factory.hh" #include <cstring> #include <memory> #include "com/centreon/broker/bam/connector.hh" #include "com/centreon/broker/config/parser.hh" #include "com/centreon/broker/database_config.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::bam; /** * Check if a configuration match the BAM layer. * * @param[in] cfg Endpoint configuration. * * @return True if the configuration matches the BAM layer. */ bool factory::has_endpoint(config::endpoint& cfg, io::extension* ext) { if (ext) *ext = io::extension("BAM", false, false); bool is_bam{!strncasecmp("bam", cfg.type.c_str(), 4)}; bool is_bam_bi{!strncasecmp("bam_bi", cfg.type.c_str(), 7)}; if (is_bam || is_bam_bi) cfg.read_timeout = 1; if (is_bam) cfg.cache_enabled = true; return is_bam || is_bam_bi; } /** * Build a BAM endpoint from a configuration. * * @param[in] cfg Endpoint configuration. * @param[out] is_acceptor Will be set to false. * @param[in] cache The persistent cache. * * @return Endpoint matching the given configuration. */ io::endpoint* factory::new_endpoint( config::endpoint& cfg, bool& is_acceptor, std::shared_ptr<persistent_cache> cache) const { // Find DB parameters. database_config db_cfg(cfg); // Is it a BAM or BAM-BI output ? bool is_bam_bi{!strncasecmp(cfg.type.c_str(), "bam_bi", 7)}; // External command file. std::string ext_cmd_file; if (!is_bam_bi) { std::map<std::string, std::string>::const_iterator it = cfg.params.find("command_file"); if (it == cfg.params.end() || it->second.empty()) throw msg_fmt("BAM: command_file parameter not set"); ext_cmd_file = it->second; } // Storage database name. std::string storage_db_name; { std::map<std::string, std::string>::const_iterator it( cfg.params.find("storage_db_name")); if (it != cfg.params.end()) storage_db_name = it->second; } // Connector. std::unique_ptr<bam::connector> c(new bam::connector); if (is_bam_bi) c->connect_reporting(db_cfg); else c->connect_monitoring(ext_cmd_file, db_cfg, storage_db_name, cache); is_acceptor = false; return c.release(); }
apache-2.0
mKaloer/PourMaster
core/src/main/java/pourmaster/FieldDataStore.java
743
package pourmaster; import pourmaster.exceptions.FieldNotFoundException; import pourmaster.fields.FieldList; import pourmaster.fields.Field; import java.io.IOException; /** * Data store for storing and retrieving field data given an field data index. */ public abstract class FieldDataStore { public abstract FieldList getFields(long index) throws IOException; public abstract long appendFields(FieldList fields) throws IOException, ReflectiveOperationException; public abstract Field getField(String name) throws FieldNotFoundException; public abstract int getFieldCount() throws IOException; public abstract Field getField(int id) throws IOException; public abstract void deleteAll() throws IOException; }
apache-2.0
fabricedesre/rust
src/test/run-pass/use.rs
705
// xfail-fast // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[allow(unused_imports)]; #[no_std]; extern mod std; extern mod zed = "std"; extern mod bar = "std#0.9-pre"; use std::str; use x = zed::str; mod baz { pub use bar::str; pub use x = std::str; } pub fn main() { }
apache-2.0
stacycurl/pimpathon
src/test/scala/pimpathon/java/util/concurrent/ThreadFactoryTest.scala
560
package pimpathon.java.util.concurrent import java.util.concurrent.ThreadFactory import pimpathon.PSpec import pimpathon.any._ import pimpathon.java.util.concurrent.threadFactory._ class ThreadFactorySpec extends PSpec { "naming" in basic.naming("name:" + _).calc(factory ⇒ { factory.newThread(runnable).getName ≡ "name:0" factory.newThread(runnable).getName ≡ "name:1" }) private lazy val basic = new ThreadFactory { def newThread(r: Runnable): Thread = new Thread(r) } private lazy val runnable = pimpathon.runnable.create(()) }
apache-2.0
Axway/ats-framework
actionlibrary/src/main/java/com/axway/ats/action/jms/model/sessions/ManagedTopicSession.java
1852
/* * Copyright 2017 Axway Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.axway.ats.action.jms.model.sessions; import javax.jms.JMSException; import javax.jms.Topic; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; public class ManagedTopicSession extends ManagedSession implements TopicSession { private final TopicSession topicSession; public ManagedTopicSession( final TopicSession session ) { super(session); topicSession = session; } @Override public TopicSubscriber createSubscriber( Topic topic ) throws JMSException { return addConsumer(topicSession.createSubscriber(topic)); } @Override public TopicSubscriber createSubscriber( Topic topic, String messageSelector, boolean noLocal ) throws JMSException { return addConsumer(topicSession.createSubscriber(topic, messageSelector, noLocal)); } @Override public TopicPublisher createPublisher( Topic topic ) throws JMSException { return addProducer(topicSession.createPublisher(topic)); } }
apache-2.0
heinigger/utils
thirdParty/monitor/src/main/java/com/yw/monitor/event/IEvents.java
1221
package com.yw.monitor.event; /** * @author:heinigger 2018/11/22 10:49 * @function:采用这样,可以方便定位寻找,单纯用String等简单类型,不易跟踪追寻 */ public abstract class IEvents<T> { public static int EVENTCOUNTER = 1000; /** * 自定义事件的id */ protected int eventId; protected String mEventId; /** * 发送事件的Id */ protected T body; public IEvents() { } public IEvents(T body) { this.body = body; eventId = EVENTCOUNTER++; mEventId = String.valueOf(eventId); } public IEvents(T body, int eventId) { this.body = body; this.eventId = eventId; } @Override public boolean equals(Object obj) { return super.equals(obj) || (obj instanceof IEvents) && additionEqual((IEvents) obj); } private boolean additionEqual(IEvents obj) { return eventId == obj.getEventId(); } public int getEventId() { return eventId; } public String getEventIds() { return mEventId; } public void setmEventId(String mEventId) { this.mEventId = mEventId; } public T getBody() { return body; } }
apache-2.0
carlosFattor/DoceTentacaoSlick
app/forms/SignInForm.scala
662
package forms /** * Created by carlos on 16/10/15. */ import play.api.data.Form import play.api.data.Forms._ import play.api.libs.json.{Json, Format} /** * The form which handles the submission of the credentials. */ /** * The form data. * * @param email The email of the user. * @param password The password of the user. */ case class SignInForm( email: String, password: String) object SignInForm { implicit val SignIn: Format[SignInForm] = Json.format[SignInForm] /** * A play framework form. */ val form = Form( mapping( "email" -> email, "password" -> nonEmptyText )(SignInForm.apply)(SignInForm.unapply) ) }
apache-2.0
Armani2015/expandable-recyclerview-with-gridlayout
expandableListview/src/main/java/com/h6ah4i/android/widget/advrecyclerview/draggable/RecyclerViewDragDropManager.java
61196
/* * Copyright (C) 2015 Haruki Hasegawa * * 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.h6ah4i.android.widget.advrecyclerview.draggable; import android.graphics.Rect; import android.graphics.drawable.NinePatchDrawable; import android.os.Build; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import com.h6ah4i.android.widget.advrecyclerview.event.RecyclerViewOnScrollEventDistributor; import com.h6ah4i.android.widget.advrecyclerview.utils.CustomRecyclerViewUtils; import com.h6ah4i.android.widget.advrecyclerview.utils.WrapperAdapterUtils; import java.lang.ref.WeakReference; /** * Provides item drag &amp; drop operation for {@link android.support.v7.widget.RecyclerView} */ @SuppressWarnings("PointlessBitwiseExpression") public class RecyclerViewDragDropManager implements DraggableItemConstants { private static final String TAG = "ARVDragDropManager"; /** * Default interpolator used for "swap target transition" */ public static final Interpolator DEFAULT_SWAP_TARGET_TRANSITION_INTERPOLATOR = new BasicSwapTargetTranslationInterpolator(); /** * Default interpolator used for "item settle back into place" animation */ public static final Interpolator DEFAULT_ITEM_SETTLE_BACK_INTO_PLACE_ANIMATION_INTERPOLATOR = new DecelerateInterpolator(); // --- /** * Used for listening item drag events */ public interface OnItemDragEventListener { /** * Callback method to be invoked when dragging is started. * * @param position The position of the item. */ void onItemDragStarted(int position); /** * Callback method to be invoked when item position is changed during drag. * * @param fromPosition The old position of the item. * @param toPosition The new position of the item */ void onItemDragPositionChanged(int fromPosition, int toPosition); /** * Callback method to be invoked when dragging is finished. * * @param fromPosition Previous position of the item. * @param toPosition New position of the item. * @param result Indicates whether the dragging operation was succeeded. */ void onItemDragFinished(int fromPosition, int toPosition, boolean result); } // -- private static final int SCROLL_DIR_NONE = 0; private static final int SCROLL_DIR_UP = (1 << 0); private static final int SCROLL_DIR_DOWN = (1 << 1); private static final int SCROLL_DIR_LEFT = (1 << 2); private static final int SCROLL_DIR_RIGHT = (1 << 3); private static final boolean LOCAL_LOGV = false; private static final boolean LOCAL_LOGD = false; private static final float SCROLL_THRESHOLD = 0.3f; // 0.0f < X < 0.5f private static final float SCROLL_AMOUNT_COEFF = 25; private static final float SCROLL_TOUCH_SLOP_MULTIPLY = 1.5f; private RecyclerView mRecyclerView; private Interpolator mSwapTargetTranslationInterpolator = DEFAULT_SWAP_TARGET_TRANSITION_INTERPOLATOR; private ScrollOnDraggingProcessRunnable mScrollOnDraggingProcess; private boolean mScrollEventRegisteredToDistributor; private RecyclerView.OnItemTouchListener mInternalUseOnItemTouchListener; private RecyclerView.OnScrollListener mInternalUseOnScrollListener; private BaseEdgeEffectDecorator mEdgeEffectDecorator; private NinePatchDrawable mShadowDrawable; private float mDisplayDensity; private int mTouchSlop; private int mScrollTouchSlop; private int mInitialTouchX; private int mInitialTouchY; private long mInitialTouchItemId = RecyclerView.NO_ID; private boolean mInitiateOnLongPress; private boolean mInitiateOnMove = true; private int mLongPressTimeout; private boolean mInScrollByMethod; private int mActualScrollByXAmount; private int mActualScrollByYAmount; private Rect mTmpRect1 = new Rect(); private int mItemSettleBackIntoPlaceAnimationDuration = 200; private Interpolator mItemSettleBackIntoPlaceAnimationInterpolator = DEFAULT_ITEM_SETTLE_BACK_INTO_PLACE_ANIMATION_INTERPOLATOR; // these fields are only valid while dragging private DraggableItemWrapperAdapter mAdapter; private RecyclerView.ViewHolder mDraggingItemViewHolder; private DraggingItemInfo mDraggingItemInfo; private DraggingItemDecorator mDraggingItemDecorator; private SwapTargetItemOperator mSwapTargetItemOperator; private int mLastTouchX; private int mLastTouchY; private int mDragStartTouchX; private int mDragStartTouchY; private int mDragMinTouchX; private int mDragMinTouchY; private int mDragMaxTouchX; private int mDragMaxTouchY; private int mScrollDirMask = SCROLL_DIR_NONE; private int mOrigOverScrollMode; private ItemDraggableRange mDraggableRange; private InternalHandler mHandler; private OnItemDragEventListener mItemDragEventListener; private boolean mCanDragH; private boolean mCanDragV; private float mDragEdgeScrollSpeed = 1.0f; @Deprecated private long mDraggingItemId = RecyclerView.NO_ID; /** * Constructor. */ public RecyclerViewDragDropManager() { mInternalUseOnItemTouchListener = new RecyclerView.OnItemTouchListener() { @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { return RecyclerViewDragDropManager.this.onInterceptTouchEvent(rv, e); } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { RecyclerViewDragDropManager.this.onTouchEvent(rv, e); } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { RecyclerViewDragDropManager.this.onRequestDisallowInterceptTouchEvent(disallowIntercept); } }; mInternalUseOnScrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { RecyclerViewDragDropManager.this.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { RecyclerViewDragDropManager.this.onScrolled(recyclerView, dx, dy); } }; mScrollOnDraggingProcess = new ScrollOnDraggingProcessRunnable(this); mLongPressTimeout = ViewConfiguration.getLongPressTimeout(); } /** * Create wrapped adapter. * * @param adapter The target adapter. * @return Wrapped adapter which is associated to this {@link RecyclerViewDragDropManager} instance. */ @SuppressWarnings("unchecked") public RecyclerView.Adapter createWrappedAdapter(@NonNull RecyclerView.Adapter adapter) { if (mAdapter != null) { throw new IllegalStateException("already have a wrapped adapter"); } mAdapter = new DraggableItemWrapperAdapter(this, adapter); return mAdapter; } /** * Indicates this manager instance has released or not. * * @return True if this manager instance has released */ public boolean isReleased() { return (mInternalUseOnItemTouchListener == null); } /** * <p>Attaches {@link android.support.v7.widget.RecyclerView} instance.</p> * <p>Before calling this method, the target {@link android.support.v7.widget.RecyclerView} must set * the wrapped adapter instance which is returned by the * {@link #createWrappedAdapter(android.support.v7.widget.RecyclerView.Adapter)} method.</p> * * @param rv The {@link android.support.v7.widget.RecyclerView} instance */ public void attachRecyclerView(@NonNull RecyclerView rv) { //noinspection deprecation attachRecyclerView(rv, null); } /** * <p>Attaches {@link android.support.v7.widget.RecyclerView} instance.</p> * <p>Before calling this method, the target {@link android.support.v7.widget.RecyclerView} must set * the wrapped adapter instance which is returned by the * {@link #createWrappedAdapter(android.support.v7.widget.RecyclerView.Adapter)} method.</p> * * @param rv The {@link android.support.v7.widget.RecyclerView} instance * @param scrollEventDistributor The distributor for {@link android.support.v7.widget.RecyclerView.OnScrollListener} event */ @Deprecated public void attachRecyclerView(@NonNull RecyclerView rv, @Nullable @SuppressWarnings("deprecation") RecyclerViewOnScrollEventDistributor scrollEventDistributor) { if (rv == null) { throw new IllegalArgumentException("RecyclerView cannot be null"); } if (isReleased()) { throw new IllegalStateException("Accessing released object"); } if (mRecyclerView != null) { throw new IllegalStateException("RecyclerView instance has already been set"); } if (mAdapter == null || getDraggableItemWrapperAdapter(rv) != mAdapter) { throw new IllegalStateException("adapter is not set properly"); } if (scrollEventDistributor != null) { final RecyclerView rv2 = scrollEventDistributor.getRecyclerView(); if (rv2 != null && rv2 != rv) { throw new IllegalArgumentException("The scroll event distributor attached to different RecyclerView instance"); } } mRecyclerView = rv; if (scrollEventDistributor != null) { scrollEventDistributor.add(mInternalUseOnScrollListener); mScrollEventRegisteredToDistributor = true; } else { mRecyclerView.addOnScrollListener(mInternalUseOnScrollListener); mScrollEventRegisteredToDistributor = false; } mRecyclerView.addOnItemTouchListener(mInternalUseOnItemTouchListener); mDisplayDensity = mRecyclerView.getResources().getDisplayMetrics().density; mTouchSlop = ViewConfiguration.get(mRecyclerView.getContext()).getScaledTouchSlop(); mScrollTouchSlop = (int) (mTouchSlop * SCROLL_TOUCH_SLOP_MULTIPLY + 0.5f); mHandler = new InternalHandler(this); if (supportsEdgeEffect()) { // edge effect is available on ICS or later switch (CustomRecyclerViewUtils.getOrientation(mRecyclerView)) { case CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL: mEdgeEffectDecorator = new LeftRightEdgeEffectDecorator(mRecyclerView); break; case CustomRecyclerViewUtils.ORIENTATION_VERTICAL: mEdgeEffectDecorator = new TopBottomEdgeEffectDecorator(mRecyclerView); break; } if (mEdgeEffectDecorator != null) { mEdgeEffectDecorator.start(); } } } /** * <p>Detach the {@link android.support.v7.widget.RecyclerView} instance and release internal field references.</p> * <p>This method should be called in order to avoid memory leaks.</p> */ public void release() { cancelDrag(true); if (mHandler != null) { mHandler.release(); mHandler = null; } if (mEdgeEffectDecorator != null) { mEdgeEffectDecorator.finish(); mEdgeEffectDecorator = null; } if (mRecyclerView != null && mInternalUseOnItemTouchListener != null) { mRecyclerView.removeOnItemTouchListener(mInternalUseOnItemTouchListener); } mInternalUseOnItemTouchListener = null; if (mRecyclerView != null && mInternalUseOnScrollListener != null && mScrollEventRegisteredToDistributor) { mRecyclerView.removeOnScrollListener(mInternalUseOnScrollListener); } mInternalUseOnScrollListener = null; if (mScrollOnDraggingProcess != null) { mScrollOnDraggingProcess.release(); mScrollOnDraggingProcess = null; } mAdapter = null; mRecyclerView = null; mSwapTargetTranslationInterpolator = null; mScrollEventRegisteredToDistributor = false; } /** * Indicates whether currently performing item dragging. * * @return True if currently performing item dragging */ public boolean isDragging() { return (mDraggingItemInfo != null) && (!mHandler.isCancelDragRequested()); } /** * Sets 9-patch image which is used for the actively dragging item * * @param drawable The 9-patch drawable */ public void setDraggingItemShadowDrawable(@Nullable NinePatchDrawable drawable) { mShadowDrawable = drawable; } /** * Sets the interpolator which is used for determining the position of the swapping item. * * @param interpolator Interpolator to set or null to clear */ public void setSwapTargetTranslationInterpolator(@Nullable Interpolator interpolator) { mSwapTargetTranslationInterpolator = interpolator; } /** * Returns whether dragging starts on a long press or not. * * @return True if dragging starts on a long press, false otherwise. */ public boolean isInitiateOnLongPressEnabled() { return mInitiateOnLongPress; } /** * Sets whether dragging starts on a long press. (default: false) * * @param initiateOnLongPress True to initiate dragging on long press. */ public void setInitiateOnLongPress(boolean initiateOnLongPress) { mInitiateOnLongPress = initiateOnLongPress; } /** * Returns whether dragging starts on move motions. * * @return True if dragging starts on move motions, false otherwise. */ public boolean isInitiateOnMoveEnabled() { return mInitiateOnMove; } /** * Sets whether dragging starts on move motions. (default: true) * * @param initiateOnMove True to initiate dragging on move motions. */ public void setInitiateOnMove(boolean initiateOnMove) { mInitiateOnMove = initiateOnMove; } /** * Sets the time required to consider press as long press. (default: 500ms) * * @param longPressTimeout Integer in milli seconds. */ public void setLongPressTimeout(int longPressTimeout) { mLongPressTimeout = longPressTimeout; } /** * Gets the interpolator which ise used for determining the position of the swapping item. * * @return Interpolator which is used for determining the position of the swapping item */ public Interpolator setSwapTargetTranslationInterpolator() { return mSwapTargetTranslationInterpolator; } /** * Gets OnItemDragEventListener listener * * @return The listener object */ public @Nullable OnItemDragEventListener getOnItemDragEventListener() { return mItemDragEventListener; } /** * Sets OnItemDragEventListener listener * * @param listener The listener object */ public void setOnItemDragEventListener(@Nullable OnItemDragEventListener listener) { mItemDragEventListener = listener; } /** * Sets drag edge scroll speed. * * @param speed The coefficient value of drag edge scrolling speed. (valid range: 0.0f .. 2.0) */ public void setDragEdgeScrollSpeed(float speed) { mDragEdgeScrollSpeed = Math.min(Math.max(speed, 0.0f), 2.0f); } /** * Gets drag edge scroll speed. * * @return The coefficient value of drag edges scrolling speed. */ public float getDragEdgeScrollSpeed() { return mDragEdgeScrollSpeed; } /*package*/ boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { final int action = MotionEventCompat.getActionMasked(e); if (LOCAL_LOGV) { Log.v(TAG, "onInterceptTouchEvent() action = " + action); } switch (action) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: handleActionUpOrCancel(action, true); break; case MotionEvent.ACTION_DOWN: if (!isDragging()) { handleActionDown(rv, e); } break; case MotionEvent.ACTION_MOVE: if (isDragging()) { // NOTE: The first ACTION_MOVE event will come here. (maybe a bug of RecyclerView?) handleActionMoveWhileDragging(rv, e); return true; } else { if (handleActionMoveWhileNotDragging(rv, e)) { return true; } } } return false; } /*package*/ void onTouchEvent(RecyclerView rv, MotionEvent e) { final int action = MotionEventCompat.getActionMasked(e); if (LOCAL_LOGV) { Log.v(TAG, "onTouchEvent() action = " + action); } if (!isDragging()) { // Log.w(TAG, "onTouchEvent() - unexpected state"); return; } switch (action) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: handleActionUpOrCancel(action, true); break; case MotionEvent.ACTION_MOVE: handleActionMoveWhileDragging(rv, e); break; } } /*package */ void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (disallowIntercept) { cancelDrag(true); } } /*package*/ void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (LOCAL_LOGV) { Log.v(TAG, "onScrolled(dx = " + dx + ", dy = " + dy + ")"); } if (mInScrollByMethod) { mActualScrollByXAmount = dx; mActualScrollByYAmount = dy; } } /*package*/ void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (LOCAL_LOGV) { Log.v(TAG, "onScrollStateChanged(newState = " + newState + ")"); } if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { cancelDrag(true); } } private boolean handleActionDown(RecyclerView rv, MotionEvent e) { final RecyclerView.ViewHolder holder = CustomRecyclerViewUtils.findChildViewHolderUnderWithoutTranslation(rv, e.getX(), e.getY()); if (!checkTouchedItemState(rv, holder)) { return false; } final int orientation = CustomRecyclerViewUtils.getOrientation(mRecyclerView); final int spanCount = CustomRecyclerViewUtils.getSpanCount(mRecyclerView); mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f); mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f); mInitialTouchItemId = holder.getItemId(); mCanDragH = (orientation == CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL) || ((orientation == CustomRecyclerViewUtils.ORIENTATION_VERTICAL) && (spanCount > 1)); mCanDragV = (orientation == CustomRecyclerViewUtils.ORIENTATION_VERTICAL) || ((orientation == CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL) && (spanCount > 1)); if (mInitiateOnLongPress) { mHandler.startLongPressDetection(e, mLongPressTimeout); } return true; } private void handleOnLongPress(MotionEvent e) { if (mInitiateOnLongPress) { checkConditionAndStartDragging(mRecyclerView, e, false); } } @SuppressWarnings("unchecked") private void startDragging(RecyclerView rv, MotionEvent e, RecyclerView.ViewHolder holder, ItemDraggableRange range) { safeEndAnimation(rv, holder); mHandler.cancelLongPressDetection(); mDraggingItemInfo = new DraggingItemInfo(holder, mLastTouchX, mLastTouchY); mDraggingItemViewHolder = holder; // XXX if setIsRecyclable() is used, another view holder objects will be created // which has the same ID with currently dragging item... Not works as expected. // holder.setIsRecyclable(false); mDraggableRange = range; mOrigOverScrollMode = ViewCompat.getOverScrollMode(rv); ViewCompat.setOverScrollMode(rv, ViewCompat.OVER_SCROLL_NEVER); mLastTouchX = (int) (e.getX() + 0.5f); mLastTouchY = (int) (e.getY() + 0.5f); // disable auto scrolling until user moves the item mDragStartTouchY = mDragMinTouchY = mDragMaxTouchY = mLastTouchY; mDragStartTouchX = mDragMinTouchX = mDragMaxTouchX = mLastTouchX; mScrollDirMask = SCROLL_DIR_NONE; mRecyclerView.getParent().requestDisallowInterceptTouchEvent(true); startScrollOnDraggingProcess(); // raise onDragItemStarted() event mAdapter.onDragItemStarted(mDraggingItemInfo, holder, mDraggableRange); // setup decorators mAdapter.onBindViewHolder(holder, holder.getLayoutPosition()); mDraggingItemDecorator = new DraggingItemDecorator(mRecyclerView, holder, mDraggableRange); mDraggingItemDecorator.setShadowDrawable(mShadowDrawable); mDraggingItemDecorator.start(e, mDraggingItemInfo); int layoutType = CustomRecyclerViewUtils.getLayoutType(mRecyclerView); if (supportsViewTranslation() && (layoutType == CustomRecyclerViewUtils.LAYOUT_TYPE_LINEAR_VERTICAL || layoutType == CustomRecyclerViewUtils.LAYOUT_TYPE_LINEAR_HORIZONTAL)) { mSwapTargetItemOperator = new SwapTargetItemOperator(mRecyclerView, holder, mDraggableRange, mDraggingItemInfo); mSwapTargetItemOperator.setSwapTargetTranslationInterpolator(mSwapTargetTranslationInterpolator); mSwapTargetItemOperator.start(); mSwapTargetItemOperator.update(mDraggingItemDecorator.getDraggingItemTranslationX(), mDraggingItemDecorator.getDraggingItemTranslationY()); } if (mEdgeEffectDecorator != null) { mEdgeEffectDecorator.reorderToTop(); } if (mItemDragEventListener != null) { mItemDragEventListener.onItemDragStarted(mAdapter.getDraggingItemInitialPosition()); } } /** * Cancel dragging. */ public void cancelDrag() { cancelDrag(false); } private void cancelDrag(boolean immediately) { handleActionUpOrCancel(MotionEvent.ACTION_CANCEL, false); if (immediately) { finishDragging(false); } else { if (isDragging()) { mHandler.requestDeferredCancelDrag(); } } } private void finishDragging(boolean result) { // RecyclerView.ViewHolder draggedItem = mDraggingItemViewHolder; if (!isDragging()) { return; } // cancel deferred request if (mHandler != null) { mHandler.removeDeferredCancelDragRequest(); } // NOTE: setOverScrollMode() have to be called before calling removeItemDecoration() if (mRecyclerView != null && mDraggingItemViewHolder != null) { ViewCompat.setOverScrollMode(mRecyclerView, mOrigOverScrollMode); } if (mDraggingItemDecorator != null) { mDraggingItemDecorator.setReturnToDefaultPositionAnimationDuration(mItemSettleBackIntoPlaceAnimationDuration); mDraggingItemDecorator.setReturnToDefaultPositionAnimationInterpolator(mItemSettleBackIntoPlaceAnimationInterpolator); mDraggingItemDecorator.finish(true); } if (mSwapTargetItemOperator != null) { mSwapTargetItemOperator.setReturnToDefaultPositionAnimationDuration(mItemSettleBackIntoPlaceAnimationDuration); mDraggingItemDecorator.setReturnToDefaultPositionAnimationInterpolator(mItemSettleBackIntoPlaceAnimationInterpolator); mSwapTargetItemOperator.finish(true); } if (mEdgeEffectDecorator != null) { mEdgeEffectDecorator.releaseBothGlows(); } stopScrollOnDraggingProcess(); if (mRecyclerView != null && mRecyclerView.getParent() != null) { mRecyclerView.getParent().requestDisallowInterceptTouchEvent(false); } if (mRecyclerView != null) { mRecyclerView.invalidate(); } mDraggableRange = null; mDraggingItemDecorator = null; mSwapTargetItemOperator = null; mDraggingItemViewHolder = null; mDraggingItemInfo = null; mLastTouchX = 0; mLastTouchY = 0; mDragStartTouchX = 0; mDragStartTouchY = 0; mDragMinTouchX = 0; mDragMinTouchY = 0; mDragMaxTouchX = 0; mDragMaxTouchY = 0; mCanDragH = false; mCanDragV = false; int draggingItemInitialPosition = RecyclerView.NO_POSITION; int draggingItemCurrentPosition = RecyclerView.NO_POSITION; // raise onDragItemFinished() event if (mAdapter != null) { draggingItemInitialPosition = mAdapter.getDraggingItemInitialPosition(); draggingItemCurrentPosition = mAdapter.getDraggingItemCurrentPosition(); mAdapter.onDragItemFinished(result); } // if (draggedItem != null) { // draggedItem.setIsRecyclable(true); // } if (mItemDragEventListener != null) { mItemDragEventListener.onItemDragFinished( draggingItemInitialPosition, draggingItemCurrentPosition, result); } } private boolean handleActionUpOrCancel(int action, boolean invokeFinish) { final boolean result = (action == MotionEvent.ACTION_UP); if (mHandler != null) { mHandler.cancelLongPressDetection(); } mInitialTouchX = 0; mInitialTouchY = 0; mLastTouchX = 0; mLastTouchY = 0; mDragStartTouchX = 0; mDragStartTouchY = 0; mDragMinTouchX = 0; mDragMinTouchY = 0; mDragMaxTouchX = 0; mDragMaxTouchY = 0; mInitialTouchItemId = RecyclerView.NO_ID; mCanDragH = false; mCanDragV = false; if (invokeFinish && isDragging()) { if (LOCAL_LOGD) { Log.d(TAG, "dragging finished --- result = " + result); } finishDragging(result); } return true; } private boolean handleActionMoveWhileNotDragging(RecyclerView rv, MotionEvent e) { if (mInitiateOnMove) { return checkConditionAndStartDragging(rv, e, true); } else { return false; } } private boolean checkConditionAndStartDragging(RecyclerView rv, MotionEvent e, boolean checkTouchSlop) { if (mDraggingItemInfo != null) { return false; } final int touchX = (int) (e.getX() + 0.5f); final int touchY = (int) (e.getY() + 0.5f); mLastTouchX = touchX; mLastTouchY = touchY; if (mInitialTouchItemId == RecyclerView.NO_ID) { return false; } if (checkTouchSlop) { if (!((mCanDragH && (Math.abs(touchX - mInitialTouchX) > mTouchSlop)) || (mCanDragV && (Math.abs(touchY - mInitialTouchY) > mTouchSlop)))) { return false; } } final RecyclerView.ViewHolder holder = CustomRecyclerViewUtils.findChildViewHolderUnderWithoutTranslation(rv, mInitialTouchX, mInitialTouchY); if (holder == null) { return false; } int position = CustomRecyclerViewUtils.getSynchronizedPosition(holder); if (position == RecyclerView.NO_POSITION) { return false; } final View view = holder.itemView; final int translateX = (int) (ViewCompat.getTranslationX(view) + 0.5f); final int translateY = (int) (ViewCompat.getTranslationY(view) + 0.5f); final int viewX = touchX - (view.getLeft() + translateX); final int viewY = touchY - (view.getTop() + translateY); if (!mAdapter.canStartDrag(holder, position, viewX, viewY)) { return false; } ItemDraggableRange range = mAdapter.getItemDraggableRange(holder, position); if (range == null) { range = new ItemDraggableRange(0, Math.max(0, mAdapter.getItemCount() - 1)); } verifyItemDraggableRange(range, holder); if (LOCAL_LOGD) { Log.d(TAG, "dragging started"); } startDragging(rv, e, holder, range); return true; } private void verifyItemDraggableRange(ItemDraggableRange range, RecyclerView.ViewHolder holder) { final int start = 0; final int end = Math.max(0, mAdapter.getItemCount() - 1); if (range.getStart() > range.getEnd()) { throw new IllegalStateException("Invalid range specified --- start > range (range = " + range + ")"); } if (range.getStart() < start) { throw new IllegalStateException("Invalid range specified --- start < 0 (range = " + range + ")"); } if (range.getEnd() > end) { throw new IllegalStateException("Invalid range specified --- end >= count (range = " + range + ")"); } if (!range.checkInRange(holder.getAdapterPosition())) { throw new IllegalStateException( "Invalid range specified --- does not contain drag target item" + " (range = " + range + ", position = " + holder.getAdapterPosition() + ")"); } } private void handleActionMoveWhileDragging(RecyclerView rv, MotionEvent e) { mLastTouchX = (int) (e.getX() + 0.5f); mLastTouchY = (int) (e.getY() + 0.5f); mDragMinTouchX = Math.min(mDragMinTouchX, mLastTouchX); mDragMinTouchY = Math.min(mDragMinTouchY, mLastTouchY); mDragMaxTouchX = Math.max(mDragMaxTouchX, mLastTouchX); mDragMaxTouchY = Math.max(mDragMaxTouchY, mLastTouchY); // update drag direction mask updateDragDirectionMask(); // update decorators mDraggingItemDecorator.update(e); if (mSwapTargetItemOperator != null) { mSwapTargetItemOperator.update(mDraggingItemDecorator.getDraggingItemTranslationX(), mDraggingItemDecorator.getDraggingItemTranslationY()); } // check swapping checkItemSwapping(rv); } private void updateDragDirectionMask() { if (CustomRecyclerViewUtils.getOrientation(mRecyclerView) == CustomRecyclerViewUtils.ORIENTATION_VERTICAL) { if (((mDragStartTouchY - mDragMinTouchY) > mScrollTouchSlop) || ((mDragMaxTouchY - mLastTouchY) > mScrollTouchSlop)) { mScrollDirMask |= SCROLL_DIR_UP; } if (((mDragMaxTouchY - mDragStartTouchY) > mScrollTouchSlop) || ((mLastTouchY - mDragMinTouchY) > mScrollTouchSlop)) { mScrollDirMask |= SCROLL_DIR_DOWN; } } else if (CustomRecyclerViewUtils.getOrientation(mRecyclerView) == CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL) { if (((mDragStartTouchX - mDragMinTouchX) > mScrollTouchSlop) || ((mDragMaxTouchX - mLastTouchX) > mScrollTouchSlop)) { mScrollDirMask |= SCROLL_DIR_LEFT; } if (((mDragMaxTouchX - mDragStartTouchX) > mScrollTouchSlop) || ((mLastTouchX - mDragMinTouchX) > mScrollTouchSlop)) { mScrollDirMask |= SCROLL_DIR_RIGHT; } } } private void checkItemSwapping(RecyclerView rv) { final RecyclerView.ViewHolder draggingItem = mDraggingItemViewHolder; final int overlayItemLeft = mLastTouchX - mDraggingItemInfo.grabbedPositionX; final int overlayItemTop = mLastTouchY - mDraggingItemInfo.grabbedPositionY; final RecyclerView.ViewHolder swapTargetHolder = findSwapTargetItem(rv, draggingItem, mDraggingItemInfo, overlayItemLeft, overlayItemTop, mDraggableRange); if ((swapTargetHolder != null) && (swapTargetHolder != mDraggingItemViewHolder)) { int draggingItemCurrentPosition = mAdapter.getDraggingItemCurrentPosition(); swapItems(rv, draggingItemCurrentPosition, draggingItem, swapTargetHolder); } } /*package*/ void handleScrollOnDragging() { final RecyclerView rv = mRecyclerView; switch (CustomRecyclerViewUtils.getOrientation(rv)) { case CustomRecyclerViewUtils.ORIENTATION_VERTICAL: handleScrollOnDraggingInternal(rv, false); break; case CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL: handleScrollOnDraggingInternal(rv, true); break; } } private void handleScrollOnDraggingInternal(RecyclerView rv, boolean horizontal) { final int edge = (horizontal) ? rv.getWidth() : rv.getHeight(); if (edge == 0) { return; } final float invEdge = (1.0f / edge); final float normalizedTouchPos = (horizontal ? mLastTouchX : mLastTouchY) * invEdge; final float threshold = SCROLL_THRESHOLD; final float invThreshold = (1.0f / threshold); final float centerOffset = normalizedTouchPos - 0.5f; final float absCenterOffset = Math.abs(centerOffset); final float acceleration = Math.max(0.0f, threshold - (0.5f - absCenterOffset)) * invThreshold; final int mask = mScrollDirMask; final DraggingItemDecorator decorator = mDraggingItemDecorator; int scrollAmount = (int) Math.signum(centerOffset) * (int) (SCROLL_AMOUNT_COEFF * mDragEdgeScrollSpeed * mDisplayDensity * acceleration + 0.5f); int actualScrolledAmount = 0; final ItemDraggableRange range = mDraggableRange; final int firstVisibleChild = CustomRecyclerViewUtils.findFirstCompletelyVisibleItemPosition(mRecyclerView); final int lastVisibleChild = CustomRecyclerViewUtils.findLastCompletelyVisibleItemPosition(mRecyclerView); boolean reachedToFirstHardLimit = false; boolean reachedToFirstSoftLimit = false; boolean reachedToLastHardLimit = false; boolean reachedToLastSoftLimit = false; if (firstVisibleChild != RecyclerView.NO_POSITION) { if (firstVisibleChild <= range.getStart()) { reachedToFirstSoftLimit = true; } if (firstVisibleChild <= (range.getStart() - 1)) { reachedToFirstHardLimit = true; } } if (lastVisibleChild != RecyclerView.NO_POSITION) { if (lastVisibleChild >= range.getEnd()) { reachedToLastSoftLimit = true; } if (lastVisibleChild >= (range.getEnd() + 1)) { reachedToLastHardLimit = true; } } // apply mask if (scrollAmount > 0) { if ((mask & (horizontal ? SCROLL_DIR_RIGHT : SCROLL_DIR_DOWN)) == 0) { scrollAmount = 0; } } else if (scrollAmount < 0) { if ((mask & (horizontal ? SCROLL_DIR_LEFT : SCROLL_DIR_UP)) == 0) { scrollAmount = 0; } } // scroll if ((!reachedToFirstHardLimit && (scrollAmount < 0)) || (!reachedToLastHardLimit && (scrollAmount > 0))) { safeEndAnimations(rv); actualScrolledAmount = (horizontal) ? scrollByXAndGetScrolledAmount(scrollAmount) : scrollByYAndGetScrolledAmount(scrollAmount); if (scrollAmount < 0) { decorator.setIsScrolling(!reachedToFirstSoftLimit); } else { decorator.setIsScrolling(!reachedToLastSoftLimit); } decorator.refresh(); if (mSwapTargetItemOperator != null) { mSwapTargetItemOperator.update( decorator.getDraggingItemTranslationX(), decorator.getDraggingItemTranslationY()); } } else { decorator.setIsScrolling(false); } final boolean actualIsScrolling = (actualScrolledAmount != 0); if (mEdgeEffectDecorator != null) { final float edgeEffectStrength = 0.005f; final int draggingItemTopLeft = (horizontal) ? decorator.getTranslatedItemPositionLeft() : decorator.getTranslatedItemPositionTop(); final int draggingItemBottomRight = (horizontal) ? decorator.getTranslatedItemPositionRight() : decorator.getTranslatedItemPositionBottom(); final int draggingItemCenter = (draggingItemTopLeft + draggingItemBottomRight) / 2; final int nearEdgePosition; if (firstVisibleChild == 0 && lastVisibleChild == 0) { // has only 1 item nearEdgePosition = (scrollAmount < 0) ? draggingItemTopLeft : draggingItemBottomRight; } else { nearEdgePosition = (draggingItemCenter < (edge / 2)) ? draggingItemTopLeft : draggingItemBottomRight; } final float nearEdgeOffset = (nearEdgePosition * invEdge) - 0.5f; final float absNearEdgeOffset = Math.abs(nearEdgeOffset); float edgeEffectPullDistance = 0; if ((absNearEdgeOffset > 0.4f) && (scrollAmount != 0) && !actualIsScrolling) { if (nearEdgeOffset < 0) { if (horizontal ? decorator.isReachedToLeftLimit() : decorator.isReachedToTopLimit()) { edgeEffectPullDistance = -mDisplayDensity * edgeEffectStrength; } } else { if (horizontal ? decorator.isReachedToRightLimit() : decorator.isReachedToBottomLimit()) { edgeEffectPullDistance = mDisplayDensity * edgeEffectStrength; } } } updateEdgeEffect(edgeEffectPullDistance); } ViewCompat.postOnAnimation(mRecyclerView, mCheckItemSwappingRunnable); } private void updateEdgeEffect(float distance) { if (distance != 0.0f) { if (distance < 0) { // upward mEdgeEffectDecorator.pullFirstEdge(distance); } else { // downward mEdgeEffectDecorator.pullSecondEdge(distance); } } else { mEdgeEffectDecorator.releaseBothGlows(); } } private Runnable mCheckItemSwappingRunnable = new Runnable() { @Override public void run() { if (mDraggingItemViewHolder != null) { checkItemSwapping(mRecyclerView); } } }; private int scrollByYAndGetScrolledAmount(int ry) { // NOTE: mActualScrollByAmount --- Hackish! To detect over scrolling. mActualScrollByYAmount = 0; mInScrollByMethod = true; mRecyclerView.scrollBy(0, ry); mInScrollByMethod = false; return mActualScrollByYAmount; } private int scrollByXAndGetScrolledAmount(int rx) { mActualScrollByXAmount = 0; mInScrollByMethod = true; mRecyclerView.scrollBy(rx, 0); mInScrollByMethod = false; return mActualScrollByXAmount; } /*package*/ RecyclerView getRecyclerView() { return mRecyclerView; } private void startScrollOnDraggingProcess() { mScrollOnDraggingProcess.start(); } private void stopScrollOnDraggingProcess() { if (mScrollOnDraggingProcess != null) { mScrollOnDraggingProcess.stop(); } } private void swapItems( RecyclerView rv, int draggingItemAdapterPosition, @Nullable RecyclerView.ViewHolder draggingItem, @NonNull RecyclerView.ViewHolder swapTargetHolder) { final Rect swapTargetMargins = CustomRecyclerViewUtils.getLayoutMargins(swapTargetHolder.itemView, mTmpRect1); final int fromPosition = draggingItemAdapterPosition; final int toPosition = swapTargetHolder.getAdapterPosition(); final int diffPosition = Math.abs(fromPosition - toPosition); boolean performSwapping = false; if (fromPosition == RecyclerView.NO_POSITION || toPosition == RecyclerView.NO_POSITION) { return; } final long actualDraggingItemId = rv.getAdapter().getItemId(fromPosition); if (actualDraggingItemId != mDraggingItemInfo.id) { if (LOCAL_LOGV) { Log.v(TAG, "RecyclerView state has not been synched to data yet"); } return; } //noinspection StatementWithEmptyBody if (diffPosition == 0) { } else if ((diffPosition == 1) && (draggingItem != null)) { final View v1 = draggingItem.itemView; final View v2 = swapTargetHolder.itemView; final Rect m1 = mDraggingItemInfo.margins; //noinspection UnnecessaryLocalVariable final Rect m2 = swapTargetMargins; if (mCanDragH) { final int left = Math.min(v1.getLeft() - m1.left, v2.getLeft() - m2.left); final int right = Math.max(v1.getRight() + m1.right, v2.getRight() + m2.right); final float midPointOfTheItems = left + ((right - left) * 0.5f); final float midPointOfTheOverlaidItem = (mLastTouchX - mDraggingItemInfo.grabbedPositionX) + (mDraggingItemInfo.width * 0.5f); if (toPosition < fromPosition) { if (midPointOfTheOverlaidItem < midPointOfTheItems) { // swap (up direction) performSwapping = true; } } else { // if (toPosition > fromPosition) if (midPointOfTheOverlaidItem > midPointOfTheItems) { // swap (down direction) performSwapping = true; } } } if (!performSwapping && mCanDragV) { final int top = Math.min(v1.getTop() - m1.top, v2.getTop() - m2.top); final int bottom = Math.max(v1.getBottom() + m1.bottom, v2.getBottom() + m2.bottom); final float midPointOfTheItems = top + ((bottom - top) * 0.5f); final float midPointOfTheOverlaidItem = (mLastTouchY - mDraggingItemInfo.grabbedPositionY) + (mDraggingItemInfo.height * 0.5f); if (toPosition < fromPosition) { if (midPointOfTheOverlaidItem < midPointOfTheItems) { // swap (up direction) performSwapping = true; } } else { // if (toPosition > fromPosition) if (midPointOfTheOverlaidItem > midPointOfTheItems) { // swap (down direction) performSwapping = true; } } } } else { // diffPosition > 1 performSwapping = true; } if (performSwapping) { performSwapItems(rv, swapTargetHolder, swapTargetMargins, fromPosition, toPosition); } } private void performSwapItems(RecyclerView rv, @NonNull RecyclerView.ViewHolder swapTargetHolder, Rect swapTargetMargins, int fromPosition, int toPosition) { if (LOCAL_LOGD) { Log.d(TAG, "item swap (from: " + fromPosition + ", to: " + toPosition + ")"); } if (mItemDragEventListener != null) { mItemDragEventListener.onItemDragPositionChanged(fromPosition, toPosition); } RecyclerView.ViewHolder firstVisibleItem = null; if (rv.getChildCount() > 0) { View child = rv.getChildAt(0); if (child != null) { firstVisibleItem = rv.getChildViewHolder(child); } } final int prevFirstItemPosition = (firstVisibleItem != null) ? firstVisibleItem.getAdapterPosition() : RecyclerView.NO_POSITION; // NOTE: This method invokes notifyItemMoved() method internally. Be careful! mAdapter.moveItem(fromPosition, toPosition); safeEndAnimations(rv); switch (CustomRecyclerViewUtils.getOrientation(rv)) { case CustomRecyclerViewUtils.ORIENTATION_VERTICAL: if (fromPosition == prevFirstItemPosition) { //noinspection UnnecessaryLocalVariable final Rect margins = swapTargetMargins; final int curTopItemHeight = swapTargetHolder.itemView.getHeight() + margins.top + margins.bottom; scrollByYAndGetScrolledAmount(-curTopItemHeight); } else if (toPosition == prevFirstItemPosition) { final Rect margins = mDraggingItemInfo.margins; final int curTopItemHeight = mDraggingItemInfo.height + margins.top + margins.bottom; scrollByYAndGetScrolledAmount(-curTopItemHeight); } break; case CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL: if (fromPosition == prevFirstItemPosition) { //noinspection UnnecessaryLocalVariable final Rect margins = swapTargetMargins; final int curLeftItemHeight = swapTargetHolder.itemView.getWidth() + margins.left + margins.right; scrollByXAndGetScrolledAmount(-curLeftItemHeight); } else if (toPosition == prevFirstItemPosition) { final Rect margins = mDraggingItemInfo.margins; final int curLeftItemHeight = mDraggingItemInfo.width + margins.left + margins.right; scrollByXAndGetScrolledAmount(-curLeftItemHeight); } break; } safeEndAnimations(rv); } private static DraggableItemWrapperAdapter getDraggableItemWrapperAdapter(RecyclerView rv) { return WrapperAdapterUtils.findWrappedAdapter(rv.getAdapter(), DraggableItemWrapperAdapter.class); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean checkTouchedItemState(RecyclerView rv, RecyclerView.ViewHolder holder) { if (!(holder instanceof DraggableItemViewHolder)) { return false; } final int itemPosition = holder.getAdapterPosition(); final RecyclerView.Adapter adapter = rv.getAdapter(); // verify the touched item is valid state if (!(itemPosition >= 0 && itemPosition < adapter.getItemCount())) { return false; } //noinspection RedundantIfStatement if (holder.getItemId() != adapter.getItemId(itemPosition)) { return false; } return true; } private static boolean supportsEdgeEffect() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; } private static boolean supportsViewTranslation() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } private static void safeEndAnimation(RecyclerView rv, RecyclerView.ViewHolder holder) { final RecyclerView.ItemAnimator itemAnimator = (rv != null) ? rv.getItemAnimator() : null; if (itemAnimator != null) { itemAnimator.endAnimation(holder); } } private static void safeEndAnimations(RecyclerView rv) { final RecyclerView.ItemAnimator itemAnimator = (rv != null) ? rv.getItemAnimator() : null; if (itemAnimator != null) { itemAnimator.endAnimations(); } } /*package*/ static RecyclerView.ViewHolder findSwapTargetItem( RecyclerView rv, RecyclerView.ViewHolder draggingItem, DraggingItemInfo draggingItemInfo, int overlayItemLeft, int overlayItemTop, ItemDraggableRange range) { RecyclerView.ViewHolder swapTargetHolder = null; if ((draggingItem == null) || ( draggingItem.getAdapterPosition() != RecyclerView.NO_POSITION && draggingItem.getItemId() == draggingItemInfo.id)) { final int layoutType = CustomRecyclerViewUtils.getLayoutType(rv); final boolean isVerticalLayout = (CustomRecyclerViewUtils.extractOrientation(layoutType) == CustomRecyclerViewUtils.ORIENTATION_VERTICAL); if (isVerticalLayout) { overlayItemLeft = Math.max(overlayItemLeft, rv.getPaddingLeft()); overlayItemLeft = Math.min(overlayItemLeft, Math.max(0, rv.getWidth() - rv.getPaddingRight() - draggingItemInfo.width)); } else { overlayItemTop = Math.max(overlayItemTop, rv.getPaddingTop()); overlayItemTop = Math.min(overlayItemTop, Math.max(0, rv.getHeight() - rv.getPaddingBottom() - draggingItemInfo.height)); } switch (layoutType) { case CustomRecyclerViewUtils.LAYOUT_TYPE_GRID_HORIZONTAL: case CustomRecyclerViewUtils.LAYOUT_TYPE_GRID_VERTICAL: swapTargetHolder = findSwapTargetItemForGridLayoutManager( rv, draggingItem, draggingItemInfo, overlayItemLeft, overlayItemTop, range, isVerticalLayout); break; case CustomRecyclerViewUtils.LAYOUT_TYPE_LINEAR_HORIZONTAL: swapTargetHolder = findSwapTargetItemForLinearLayoutManagerHorizontal(rv, draggingItem, draggingItemInfo, overlayItemLeft, overlayItemTop, range); break; case CustomRecyclerViewUtils.LAYOUT_TYPE_LINEAR_VERTICAL: swapTargetHolder = findSwapTargetItemForLinearLayoutManagerVertical(rv, draggingItem, draggingItemInfo, overlayItemLeft, overlayItemTop, range); break; default: break; } } // check range if (swapTargetHolder != null && range != null) { if (!range.checkInRange(swapTargetHolder.getAdapterPosition())) { swapTargetHolder = null; } } return swapTargetHolder; } private static RecyclerView.ViewHolder findSwapTargetItemForGridLayoutManager( RecyclerView rv, @Nullable RecyclerView.ViewHolder draggingItem, DraggingItemInfo draggingItemInfo, int overlayItemLeft, int overlayItemTop, ItemDraggableRange range, boolean vertical) { RecyclerView.ViewHolder swapTargetHolder = null; int cx = overlayItemLeft + draggingItemInfo.width / 2; int cy = overlayItemTop + draggingItemInfo.height / 2; RecyclerView.ViewHolder vh = CustomRecyclerViewUtils.findChildViewHolderUnderWithoutTranslation(rv, cx, cy); if (vh != null) { if (vh != draggingItem) { swapTargetHolder = vh; } } else { int spanCount = CustomRecyclerViewUtils.getSpanCount(rv); int height = rv.getHeight(); int width = rv.getWidth(); int paddingLeft = (vertical) ? rv.getPaddingLeft() : 0; int paddingTop = (!vertical) ? rv.getPaddingTop() : 0; int paddingRight = (vertical) ? rv.getPaddingRight() : 0; int paddingBottom = (!vertical) ? rv.getPaddingBottom() : 0; int columnWidth = (width - paddingLeft - paddingRight) / spanCount; int rowHeight = (height - paddingTop - paddingBottom) / spanCount; for (int i = spanCount - 1; i >= 0; i--) { int cx2 = (vertical) ? (paddingLeft + (columnWidth * i) + (columnWidth / 2)) : cx; int cy2 = (!vertical) ? (paddingTop + (rowHeight * i) + (rowHeight / 2)) : cy; RecyclerView.ViewHolder vh2 = CustomRecyclerViewUtils.findChildViewHolderUnderWithoutTranslation(rv, cx2, cy2); if (vh2 != null) { int itemCount = rv.getLayoutManager().getItemCount(); int pos = vh2.getAdapterPosition(); if ((pos != RecyclerView.NO_POSITION) && (pos == itemCount - 1)) { if (vh != draggingItem) { swapTargetHolder = vh2; } } break; } } } return swapTargetHolder; } private static RecyclerView.ViewHolder findSwapTargetItemForLinearLayoutManagerVertical( RecyclerView rv, RecyclerView.ViewHolder draggingItem, DraggingItemInfo draggingItemInfo, int overlayItemLeft, int overlayItemTop, ItemDraggableRange range) { RecyclerView.ViewHolder swapTargetHolder = null; if (draggingItem != null) { final int draggingItemPosition = draggingItem.getAdapterPosition(); final int draggingViewTop = draggingItem.itemView.getTop(); if (overlayItemTop < draggingViewTop) { if (draggingItemPosition > 0) { swapTargetHolder = rv.findViewHolderForAdapterPosition(draggingItemPosition - 1); } } else if (overlayItemTop > draggingViewTop) { if (draggingItemPosition < (rv.getAdapter().getItemCount() - 1)) { swapTargetHolder = rv.findViewHolderForAdapterPosition(draggingItemPosition + 1); } } } return swapTargetHolder; } private static RecyclerView.ViewHolder findSwapTargetItemForLinearLayoutManagerHorizontal( RecyclerView rv, @Nullable RecyclerView.ViewHolder draggingItem, DraggingItemInfo draggingItemInfo, int overlayItemLeft, int overlayItemTop, ItemDraggableRange range) { RecyclerView.ViewHolder swapTargetHolder = null; if (draggingItem != null) { final int draggingItemPosition = draggingItem.getAdapterPosition(); final int draggingViewLeft = draggingItem.itemView.getLeft(); if (overlayItemLeft < draggingViewLeft) { if (draggingItemPosition > 0) { swapTargetHolder = rv.findViewHolderForAdapterPosition(draggingItemPosition - 1); } } else if (overlayItemLeft > draggingViewLeft) { if (draggingItemPosition < (rv.getAdapter().getItemCount() - 1)) { swapTargetHolder = rv.findViewHolderForAdapterPosition(draggingItemPosition + 1); } } } return swapTargetHolder; } /** * Sets the duration of "settle back into place" animation. * * @param duration Specify the animation duration in milliseconds */ public void setItemSettleBackIntoPlaceAnimationDuration(int duration) { mItemSettleBackIntoPlaceAnimationDuration = duration; } /** * Gets the duration of "settle back into place" animation. * * @return The duration of "settle back into place" animation in milliseconds */ public int getItemSettleBackIntoPlaceAnimationDuration() { return mItemSettleBackIntoPlaceAnimationDuration; } /** * Sets the interpolator which is used for "settle back into place" animation. * * @param interpolator Interpolator to set or null to clear */ public void setItemSettleBackIntoPlaceAnimationInterpolator(@Nullable Interpolator interpolator) { mItemSettleBackIntoPlaceAnimationInterpolator = interpolator; } /** * Gets the interpolator which ise used for "settle back into place" animation. * * @return Interpolator which is used for "settle back into place" animation */ public @Nullable Interpolator getItemSettleBackIntoPlaceAnimationInterpolator() { return mItemSettleBackIntoPlaceAnimationInterpolator; } /*package*/ void onDraggingItemViewRecycled() { mDraggingItemViewHolder = null; mDraggingItemDecorator.invalidateDraggingItem(); } /*package*/ void onNewDraggingItemViewBound(RecyclerView.ViewHolder holder) { mDraggingItemViewHolder = holder; mDraggingItemDecorator.setDraggingItemViewHolder(holder); } private static class ScrollOnDraggingProcessRunnable implements Runnable { private final WeakReference<RecyclerViewDragDropManager> mHolderRef; private boolean mStarted; public ScrollOnDraggingProcessRunnable(RecyclerViewDragDropManager holder) { mHolderRef = new WeakReference<>(holder); } public void start() { if (mStarted) { return; } final RecyclerViewDragDropManager holder = mHolderRef.get(); if (holder == null) { return; } final RecyclerView rv = holder.getRecyclerView(); if (rv == null) { return; } ViewCompat.postOnAnimation(rv, this); mStarted = true; } public void stop() { if (!mStarted) { return; } mStarted = false; } public void release() { mHolderRef.clear(); mStarted = false; } @Override public void run() { final RecyclerViewDragDropManager holder = mHolderRef.get(); if (holder == null) { return; } if (!mStarted) { return; } // call scrolling process holder.handleScrollOnDragging(); // re-schedule the process final RecyclerView rv = holder.getRecyclerView(); if (rv != null && mStarted) { ViewCompat.postOnAnimation(rv, this); } else { mStarted = false; } } } private static class InternalHandler extends Handler { private static final int MSG_LONGPRESS = 1; private static final int MSG_DEFERRED_CANCEL_DRAG = 2; private RecyclerViewDragDropManager mHolder; private MotionEvent mDownMotionEvent; public InternalHandler(RecyclerViewDragDropManager holder) { mHolder = holder; } public void release() { removeCallbacks(null); mHolder = null; } @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_LONGPRESS: mHolder.handleOnLongPress(mDownMotionEvent); break; case MSG_DEFERRED_CANCEL_DRAG: mHolder.cancelDrag(true); break; } } public void startLongPressDetection(MotionEvent e, int timeout) { cancelLongPressDetection(); mDownMotionEvent = MotionEvent.obtain(e); sendEmptyMessageAtTime(MSG_LONGPRESS, e.getDownTime() + timeout); } public void cancelLongPressDetection() { removeMessages(MSG_LONGPRESS); if (mDownMotionEvent != null) { mDownMotionEvent.recycle(); mDownMotionEvent = null; } } public void removeDeferredCancelDragRequest() { removeMessages(MSG_DEFERRED_CANCEL_DRAG); } public void requestDeferredCancelDrag() { if (isCancelDragRequested()) { return; } sendEmptyMessage(MSG_DEFERRED_CANCEL_DRAG); } public boolean isCancelDragRequested() { return hasMessages(MSG_DEFERRED_CANCEL_DRAG); } } }
apache-2.0
TreetonOrg/Treeton
dev/prosody/src/treeton/prosody/corpus/CorpusException.java
308
/* * Copyright Anatoly Starostin (c) 2017. */ package treeton.prosody.corpus; public class CorpusException extends Exception { public CorpusException(String message) { super(message); } public CorpusException(String message, Throwable cause) { super(message, cause); } }
apache-2.0
libamqp/libamqp
src/TemplateModule/ModuleTest.cpp
801
/* Copyright 2011-2012 StormMQ Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <TestHarness.h> #include "Parent/Module/Module.h" #include "Parent/Module/ModuleTestSupport.h" SUITE(ParentModule) { TEST_FIXTURE(ParentModuleFixture, really_important_test) { } }
apache-2.0
bio-org-au/nsl-editor
test/models/name/as_typeahead/name_parent/partially_restricted/for_forma_test.rb
1453
# frozen_string_literal: true # Copyright 2015 Australian National Botanic Gardens # # This file is part of the NSL Editor. # # 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. # require "test_helper" require "models/name/as_typeahead/name_parent/name_parent_test_helper" # Single Name typeahead test. class ForFormaPartiallyRestrictedTest < ActiveSupport::TestCase def setup set_name_parent_rank_restrictions_off end test "name parent suggestion for forma" do assert !ShardConfig.name_parent_rank_restriction?, "Name parent rank restriction should be off for this test." typeahead = Name::AsTypeahead::ForParent.new( term: "%", avoid_id: 1, rank_id: NameRank.find_by(name: "Forma").id ) typeahead.suggestions.each do |suggestion| suggestion_rank_should_be_at_or_below(suggestion, NameRank.find_by(name: "Species")) end end end
apache-2.0
lerwine/WebAppCodeTemplates
TextProcessing/IndentingStringWriter.cs
2607
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace TextProcessing { public class IndentingStringWriter : TextWriter { private StringBuilder _stringBuilder = new StringBuilder(); private char[] _currentLine = new char[0]; private char[] _currentIndent = new char[0]; private string _indent = "\t"; private int _indentLevel = 0; public override string NewLine { get { return base.NewLine; } set { base.NewLine = value; } } public string Indent { get { return this._indent; } set { string s = (value == null) ? "\t" : value; if (this._indent == s) return; this._indent = s; this.UpdateCurrentIndent(); } } public int IndentLevel { get { return this._indentLevel; } private set { int i = (value < 0) ? 0 : value; if (this._indentLevel == i) return; this._indentLevel = i; this.UpdateCurrentIndent(); } } public override Encoding Encoding { get { return Encoding.Unicode; } } public override void Close() { base.Close(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } public override void Flush() { base.Flush(); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString(); } public override void Write(char value) { base.Write(value); } public override void Write(char[] buffer, int index, int count) { base.Write(buffer, index, count); } private void UpdateCurrentIndent() { lock (this._stringBuilder) { this._currentIndent = new char[0]; if (this._indent.Length > 0) { for (int i = 0; i < this.IndentLevel; i++) this._currentIndent = this._currentIndent.Concat(this._indent.ToCharArray()).ToArray(); } } } } }
apache-2.0
mars-lan/WhereHows
datahub-web/@datahub/utils/tests/integration/components/notifications-test.ts
4406
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, click, settled } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { INotificationsTestContext } from '@datahub/utils/types/tests/notifications'; import { NotificationEvent } from '@datahub/utils/constants/notifications'; import FakeTimers from '@sinonjs/fake-timers'; import { IToast } from '@datahub/utils/types/notifications/service'; import { renderingDone } from '@datahub/utils/test-helpers/rendering'; const toastBaseClass = '.notifications__toast'; const modalBaseClass = '.notification-confirm-modal'; const longNotificationTextContent = 'A long string of text for user notification that contains more than the required number of characters to be displayed in a toast'; module('Integration | Component | notifications', function(hooks): void { setupRenderingTest(hooks); hooks.beforeEach(function(this: INotificationsTestContext) { this.service = this.owner.lookup('service:notifications'); }); test('Notification Component rendering', async function(this: INotificationsTestContext, assert) { const { service } = this; this.set('service', service); await render(hbs`<Notifications />`); assert.dom('[notifications-element]').exists(); }); test('Notifications: Toast component rendering & behavior', async function(this: INotificationsTestContext, assert) { const { service } = this; const msgElement = `${toastBaseClass}__content__msg`; const clock = FakeTimers.install(); const baseNotificationDelay = this.owner.resolveRegistration('config:environment').APP.notificationsTimeout; this.set('service', service); // Installing the fake timers means the runloop timer will not proceed until the clock ticks // therefore, we do not `await render`, but use the renderingDone helper to await settlement of all pending except timers render(hbs`<Notifications />`); service.notify({ type: NotificationEvent.success }); await renderingDone(); assert.dom(msgElement).hasText('Success!'); assert.dom(`${toastBaseClass}--visible`).exists(); assert.dom(`${toastBaseClass}--hidden`).doesNotExist(); await click(`${toastBaseClass}__dismiss`); assert.notOk(service.isShowingToast, 'Expected service to not be showing toast'); assert.dom(`${toastBaseClass}--visible`).doesNotExist(); assert.dom(`${toastBaseClass}--hidden`).exists(); service.notify({ type: NotificationEvent.error, duration: 0 }); await renderingDone(); assert.dom(msgElement).hasText('An error occurred!'); // Expect the notification to still be rendered after notification delay clock.tick(baseNotificationDelay + 1); const { activeNotification = { props: { isSticky: false } } } = service; const toast: IToast = activeNotification.props as IToast; assert.ok(toast.isSticky, 'Expected an error toast to have the flag isSticky set to true'); assert.dom(msgElement).hasText('An error occurred!', 'Expected error toast to be sticky'); await click(`${toastBaseClass}__dismiss`); service.notify({ type: NotificationEvent.info, duration: 0 }); await renderingDone(); assert.dom(msgElement).hasText('Something noteworthy happened.'); await click(`${toastBaseClass}__dismiss`); service.notify({ type: NotificationEvent.success, duration: 0 }); await renderingDone(); assert.dom(msgElement).hasText('Success!'); await click(`${toastBaseClass}__dismiss`); clock.uninstall(); }); test('Notifications: Detail Modal rendering and behavior', async function(this: INotificationsTestContext, assert) { await render(hbs`<Notifications />`); this.service.notify({ type: NotificationEvent.success, content: longNotificationTextContent }); await settled(); assert.dom(modalBaseClass).doesNotExist(); await click(`${toastBaseClass}__content-detail`); assert.dom(`${toastBaseClass}--hidden`).exists(); assert.dom(modalBaseClass).exists(); assert.dom(`${modalBaseClass}__heading-text`).hasText('Notification Detail'); assert.dom(`${modalBaseClass}__content`).hasText(longNotificationTextContent); assert.dom(`${modalBaseClass}__footer`).hasText('Dismiss'); await click(`${modalBaseClass}__footer button`); assert.dom(modalBaseClass).doesNotExist(); }); });
apache-2.0
Ericliu001/basic-algorithms
src/test/java/com/basicalgorithms/jiuzhang/chapter05_depth_first_search/PermutationsII.java
7307
package com.basicalgorithms.jiuzhang.chapter05_depth_first_search; import org.junit.Assert; import org.junit.Test; import java.util.*; /** * Given a list of numbers with duplicate number in it. Find all unique permutations. * Example * For numbers [1,2,2] the unique permutations are: * [ * [1,2,2], * [2,1,2], * [2,2,1] * ] */ public class PermutationsII { /** * Standard Answer!!! */ public class SolutionEric { /* * @param : A list of integers * @return: A list of unique permutations */ public List<List<Integer>> permuteUnique(int[] nums) { if (nums == null || nums.length == 0) { return Collections.singletonList(Collections.emptyList()); } return findAllPermutations(nums, 0, Collections.emptyList()); } private List<List<Integer>> findAllPermutations(final int[] nums, final int startIndex, final List<Integer> combination) { Arrays.sort(nums, startIndex, nums.length); final List<List<Integer>> results = new ArrayList<>(); if (combination.size() >= nums.length) { results.add(combination); } for (int i = startIndex; i < nums.length; i++) { if (startIndex != i && nums[i] == nums[i - 1]) { continue; } final int[] newNums = Arrays.copyOf(nums, nums.length); swap(newNums, startIndex, i); final List<Integer> newCombination = new ArrayList<>(combination); newCombination.add(nums[i]); results.addAll(findAllPermutations(newNums, startIndex + 1, newCombination)); } return results; } private void swap(final int[] nums, final int a, final int b) { int temp = nums[a]; nums[a] = nums[b]; nums[b] = temp; } } @Test public void test1() throws Exception { final int[] nums = {1, 2, 2}; final List<List<Integer>> lists = new SolutionEric().permuteUnique(nums); final Set<List<Integer>> results = new HashSet<>(lists); final Set<List<Integer>> expected = new HashSet<>(lists); expected.add(Arrays.asList(1, 2, 2)); expected.add(Arrays.asList(2, 1, 2)); expected.add(Arrays.asList(2, 2, 1)); Assert.assertEquals(expected.size(), lists.size()); Assert.assertEquals(expected, results); printListList(lists); } @Test public void test2() throws Exception { final int[] nums = {0, 1, 0, 0, 9}; final List<List<Integer>> lists = new SolutionEric().permuteUnique(nums); final Set<List<Integer>> results = new HashSet<>(lists); final Set<List<Integer>> expected = new HashSet<>(lists); expected.add(Arrays.asList(0, 0, 0, 1, 9)); expected.add(Arrays.asList(0, 0, 0, 9, 1)); expected.add(Arrays.asList(0, 0, 1, 0, 9)); expected.add(Arrays.asList(0, 0, 1, 9, 0)); expected.add(Arrays.asList(0, 0, 9, 0, 1)); expected.add(Arrays.asList(0, 0, 9, 1, 0)); expected.add(Arrays.asList(0, 1, 0, 0, 9)); expected.add(Arrays.asList(0, 1, 0, 9, 0)); expected.add(Arrays.asList(0, 1, 9, 0, 0)); expected.add(Arrays.asList(0, 9, 0, 0, 1)); expected.add(Arrays.asList(0, 9, 0, 1, 0)); expected.add(Arrays.asList(0, 9, 1, 0, 0)); expected.add(Arrays.asList(1, 0, 0, 0, 9)); expected.add(Arrays.asList(1, 0, 0, 9, 0)); expected.add(Arrays.asList(1, 0, 9, 0, 0)); expected.add(Arrays.asList(1, 9, 0, 0, 0)); expected.add(Arrays.asList(9, 0, 0, 0, 1)); expected.add(Arrays.asList(9, 0, 0, 1, 0)); expected.add(Arrays.asList(9, 0, 1, 0, 0)); expected.add(Arrays.asList(9, 1, 0, 0, 0)); Assert.assertEquals(expected.size(), lists.size()); Assert.assertEquals(expected, results); printListList(lists); } private void printListList(final List<List<Integer>> lists) { lists.forEach( permutation -> { System.out.println(); System.out.print("{"); System.out.print(permutation.get(0)); permutation.stream() .skip(1) .map(x -> ", " + x) .forEach(System.out::print); System.out.print("}"); } ); } /** * 本代码由九章算法编辑提供。版权所有,转发请注明出处。 * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 * - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,Big Data 项目实战班, * - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code */ class Solution01 { /** * @param nums: A list of integers. * * @return: A list of unique permutations. */ public List<List<Integer>> permuteUnique(int[] nums) { ArrayList<List<Integer>> results = new ArrayList<List<Integer>>(); if (nums == null) { return results; } if (nums.length == 0) { results.add(new ArrayList<Integer>()); return results; } Arrays.sort(nums); ArrayList<Integer> list = new ArrayList<Integer>(); int[] visited = new int[nums.length]; for (int i = 0; i < visited.length; i++) { visited[i] = 0; } helper(results, list, visited, nums); return results; } public void helper(ArrayList<List<Integer>> results, ArrayList<Integer> list, int[] visited, int[] nums) { if (list.size() == nums.length) { results.add(new ArrayList<Integer>(list)); return; } for (int i = 0; i < nums.length; i++) { if (visited[i] == 1 || (i != 0 && nums[i] == nums[i - 1] && visited[i - 1] == 0)) { continue; } /* 上面的判断主要是为了去除重复元素影响。 比如,给出一个排好序的数组,[1,2,2],那么第一个2和第二2如果在结果中互换位置, 我们也认为是同一种方案,所以我们强制要求相同的数字,原来排在前面的,在结果 当中也应该排在前面,这样就保证了唯一性。所以当前面的2还没有使用的时候,就 不应该让后面的2使用。 */ visited[i] = 1; list.add(nums[i]); helper(results, list, visited, nums); list.remove(list.size() - 1); visited[i] = 0; } } } }
apache-2.0
martylamb/nailgun
nailgun-server/src/main/java/com/facebook/nailgun/builtins/NGAlias.java
2915
/* Copyright 2004-2012, Martian Software, Inc. Copyright 2017-Present Facebook, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.facebook.nailgun.builtins; import com.facebook.nailgun.Alias; import com.facebook.nailgun.NGContext; import com.facebook.nailgun.NGServer; import java.util.Iterator; import java.util.Set; /** * Provides a means to view and add aliases. This is aliased by default to the command "<code> * ng-alias</code>". * * <p>No command line validation is performed. If you trigger an exception, your client will display * it. * * <p><b>To view the current alias list</b>, issue the command: * * <pre><code>ng-alias</code></pre> * * with no arguments. * * <p><b>To add or replace an alias</b>, issue the command: * * <pre><code>ng-alias [alias name] [fully qualified aliased class name]</code></pre> * * @author <a href="http://www.martiansoftware.com/contact.html">Marty Lamb</a> */ public class NGAlias { private static String padl(String s, int len) { StringBuilder buf = new StringBuilder(s); while (buf.length() < len) buf.append(" "); return (buf.toString()); } public static void nailMain(NGContext context) throws ClassNotFoundException { String[] args = context.getArgs(); NGServer server = context.getNGServer(); if (args.length == 0) { Set aliases = server.getAliasManager().getAliases(); // let's pad this nicely. first, find the longest alias // name. then pad the others to that width. int maxAliasLength = 0; int maxClassnameLength = 0; for (Iterator i = aliases.iterator(); i.hasNext(); ) { Alias alias = (Alias) i.next(); maxAliasLength = Math.max(maxAliasLength, alias.getName().length()); maxClassnameLength = Math.max(maxClassnameLength, alias.getAliasedClass().getName().length()); } for (Iterator i = aliases.iterator(); i.hasNext(); ) { Alias alias = (Alias) i.next(); context.out.println( padl(alias.getName(), maxAliasLength) + "\t" + padl(alias.getAliasedClass().getName(), maxClassnameLength)); context.out.println(padl("", maxAliasLength) + "\t" + alias.getDescription()); context.out.println(); } } else if (args.length == 2) { server.getAliasManager().addAlias(new Alias(args[0], "", Class.forName(args[1]))); } } }
apache-2.0
arpitgautam/AsyncFBClient
src/main/java/org/async/fbclient/beans/user/Concentration.java
1022
package org.async.fbclient.beans.user; import javax.annotation.Generated; import com.google.gson.annotations.Expose; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; @Generated("com.googlecode.jsonschema2pojo") public class Concentration { @Expose private String id; @Expose private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object other) { return EqualsBuilder.reflectionEquals(this, other); } }
apache-2.0
viczy/commerce
app/api/v1/rest/commodity_api.rb
2396
module V1 module REST class CommodityApi < Grape::API resource :commodities do desc 'Get commodity list' get do commodities = Commodity.all present commodities, with: Entities::Commodity end desc 'Get a commodity' params do requires :id end get ':id' do present Commodity.find(params[:id]), with: Entities::Commodity end desc 'Create a new commodity' params do requires :title, type: String, desc: "title" requires :price, type: Float, desc: "price" requires :cover, type: String, desc: "cover" optional :summary, type: String, desc: "summary" end post do commodity = Commodity.create!({ title: params[:title], price: params[:price], cover: params[:cover], summary: params[:summary] }) present commodity, with: Entities::Commodity end desc 'Update an existing commodity' params do requires :id, type: String, desc: "id" optional :title, type: String, desc: "title" optional :price, type: Float, desc: "price" optional :cover, type: String, desc: "cover" optional :summary, type: String, desc: "summary" end put ':id' do commodity = Commodity.find params[:id] commodity.update({ title: (params[:title]).blank? ? commodity.title : params[:title], price: (params[:price].blank?) ? commodity.price : params[:price], cover: (params[:cover].blank?) ? commodity.cover : params[:cover], summary: (params[:summary].blank?) ? commodity.summary : params[:summary] }) present commodity, with: Entities::Commodity end desc 'Destroy a commodity' params do requires :id, type: String, desc: 'Commodity id' end delete ':id' do commodity = Commodity.find(params[:id]) commodity.destroy present '0' end end end end end
apache-2.0
VamsiSmart/Go-ubiquitous
app/src/main/java/com/example/android/sunshine/app/MainActivity.java
8612
/* * 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.example.android.sunshine.app; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.util.Pair; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.example.android.sunshine.app.data.WeatherContract; import com.example.android.sunshine.app.gcm.RegistrationIntentService; import com.example.android.sunshine.app.sync.SunshineSyncAdapter; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; public class MainActivity extends AppCompatActivity implements ForecastFragment.Callback { private final String LOG_TAG = MainActivity.class.getSimpleName(); private static final String DETAILFRAGMENT_TAG = "DFTAG"; private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer"; private boolean mTwoPane; private String mLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLocation = Utility.getPreferredLocation(this); Uri contentUri = getIntent() != null ? getIntent().getData() : null; setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); if (findViewById(R.id.weather_detail_container) != null) { // The detail container view will be present only in the large-screen layouts // (res/layout-sw600dp). If this view is present, then the activity should be // in two-pane mode. mTwoPane = true; // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. if (savedInstanceState == null) { DetailFragment fragment = new DetailFragment(); if (contentUri != null) { Bundle args = new Bundle(); args.putParcelable(DetailFragment.DETAIL_URI, contentUri); fragment.setArguments(args); } getSupportFragmentManager().beginTransaction() .replace(R.id.weather_detail_container, fragment, DETAILFRAGMENT_TAG) .commit(); } } else { mTwoPane = false; getSupportActionBar().setElevation(0f); } ForecastFragment forecastFragment = ((ForecastFragment)getSupportFragmentManager() .findFragmentById(R.id.fragment_forecast)); forecastFragment.setUseTodayLayout(!mTwoPane); if (contentUri != null) { forecastFragment.setInitialSelectedDate( WeatherContract.WeatherEntry.getDateFromUri(contentUri)); } SunshineSyncAdapter.initializeSyncAdapter(this); // If Google Play Services is up to date, we'll want to register GCM. If it is not, we'll // skip the registration and this device will not receive any downstream messages from // our fake server. Because weather alerts are not a core feature of the app, this should // not affect the behavior of the app, from a user perspective. /* if (checkPlayServices()) { // Because this is the initial creation of the app, we'll want to be certain we have // a token. If we do not, then we will start the IntentService that will register this // application with GCM. SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); boolean sentToken = sharedPreferences.getBoolean(SENT_TOKEN_TO_SERVER, false); if (!sentToken) { Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } } */ } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { startActivity(new Intent(this, SettingsActivity.class)); return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); String location = Utility.getPreferredLocation( this ); // update the location in our second pane using the fragment manager if (location != null && !location.equals(mLocation)) { ForecastFragment ff = (ForecastFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_forecast); if ( null != ff ) { ff.onLocationChanged(); } DetailFragment df = (DetailFragment)getSupportFragmentManager().findFragmentByTag(DETAILFRAGMENT_TAG); if ( null != df ) { df.onLocationChanged(location); } mLocation = location; } } @Override public void onItemSelected(Uri contentUri, ForecastAdapter.ForecastAdapterViewHolder vh) { if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. Bundle args = new Bundle(); args.putParcelable(DetailFragment.DETAIL_URI, contentUri); DetailFragment fragment = new DetailFragment(); fragment.setArguments(args); getSupportFragmentManager().beginTransaction() .replace(R.id.weather_detail_container, fragment, DETAILFRAGMENT_TAG) .commit(); } else { Intent intent = new Intent(this, DetailActivity.class) .setData(contentUri); ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(this, new Pair<View, String>(vh.mIconView, getString(R.string.detail_icon_transition_name))); ActivityCompat.startActivity(this, intent, activityOptions.toBundle()); } } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (apiAvailability.isUserResolvableError(resultCode)) { apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(LOG_TAG, "This device is not supported."); finish(); } return false; } return true; } }
apache-2.0
hortonworks/cloudbreak
ccm-connector/src/main/java/com/sequenceiq/cloudbreak/ccmimpl/cloudinit/DefaultCcmParameterSupplier.java
5756
package com.sequenceiq.cloudbreak.ccmimpl.cloudinit; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.cloudera.thunderhead.service.minasshdmanagement.MinaSshdManagementProto; import com.cloudera.thunderhead.service.minasshdmanagement.MinaSshdManagementProto.GenerateAndRegisterSshTunnelingKeyPairResponse; import com.cloudera.thunderhead.service.minasshdmanagement.MinaSshdManagementProto.MinaSshdService; import com.google.common.base.Throwables; import com.sequenceiq.cloudbreak.ccm.cloudinit.CcmParameterSupplier; import com.sequenceiq.cloudbreak.ccm.cloudinit.CcmParameters; import com.sequenceiq.cloudbreak.ccm.cloudinit.DefaultCcmParameters; import com.sequenceiq.cloudbreak.ccm.cloudinit.DefaultInstanceParameters; import com.sequenceiq.cloudbreak.ccm.cloudinit.DefaultServerParameters; import com.sequenceiq.cloudbreak.ccm.cloudinit.DefaultTunnelParameters; import com.sequenceiq.cloudbreak.ccm.endpoint.BaseServiceEndpoint; import com.sequenceiq.cloudbreak.ccm.endpoint.HostEndpoint; import com.sequenceiq.cloudbreak.ccm.endpoint.KnownServiceIdentifier; import com.sequenceiq.cloudbreak.ccmimpl.altus.GrpcMinaSshdManagementClient; import com.sequenceiq.cloudbreak.logger.MDCBuilder; /** * Default supplier of CCM parameters, which: * <ol> * <li>contacts the minasshd management server via GRPC to acquire a minasshd instance;</li> * <li>creates corresponding server parameters;</li> * <li>contacts the minasshd instance via GRPC to register an instance and generate a keypair;</li> * <li>creates the corresponding instance parameters; and</li> * <li>creates the tunnel parameters based on the passed-in arguments.</li> * </ol> */ @Component public class DefaultCcmParameterSupplier implements CcmParameterSupplier { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCcmParameterSupplier.class); @Inject private GrpcMinaSshdManagementClient grpcMinaSshdManagementClient; @Override public Optional<CcmParameters> getBaseCcmParameters(@Nonnull String actorCrn, @Nonnull String accountId, @Nonnull String keyId) { if (grpcMinaSshdManagementClient == null) { return Optional.empty(); } String requestId = MDCBuilder.getOrGenerateRequestId(); try { MinaSshdService minaSshdService = grpcMinaSshdManagementClient.acquireMinaSshdServiceAndWaitUntilReady( requestId, Objects.requireNonNull(actorCrn, "actorCrn is null"), Objects.requireNonNull(accountId, "accountId is null")); GenerateAndRegisterSshTunnelingKeyPairResponse keyPairResponse = grpcMinaSshdManagementClient.generateAndRegisterSshTunnelingKeyPair( requestId, actorCrn, accountId, minaSshdService.getMinaSshdServiceId(), keyId); return Optional.of( new DefaultCcmParameters( createServerParameters(minaSshdService), createInstanceParameters(keyId, keyPairResponse.getEncipheredPrivateKey()), Collections.emptyList())); } catch (Exception e) { Throwables.throwIfUnchecked(e); throw new RuntimeException(e); } } @Override public Optional<CcmParameters> getCcmParameters( @Nullable CcmParameters baseCcmParameters, @Nullable Map<KnownServiceIdentifier, Integer> tunneledServicePorts) { return ((baseCcmParameters == null) || (tunneledServicePorts == null) || tunneledServicePorts.isEmpty()) ? Optional.empty() : Optional.of( new DefaultCcmParameters( baseCcmParameters.getServerParameters(), baseCcmParameters.getInstanceParameters(), tunneledServicePorts.entrySet().stream() .map(entry -> new DefaultTunnelParameters(entry.getKey(), entry.getValue())) .collect(Collectors.toList()))); } /** * Creates instance parameters. * * @param keyId the key ID under which the private key was registered with CCM * @param encipheredPrivateKey the enciphered private key * @return the instance parameters */ private DefaultInstanceParameters createInstanceParameters(String keyId, String encipheredPrivateKey) { return new DefaultInstanceParameters(null, keyId, encipheredPrivateKey); } /** * Creates server parameters based on the specified minasshd service. * * @param minaSshdService the minasshd service * @return the server parameters */ private DefaultServerParameters createServerParameters(MinaSshdService minaSshdService) { MinaSshdManagementProto.SshTunnelingConfiguration sshTunnelingConfiguration = minaSshdService.getSshTunnelingConfiguration(); MinaSshdManagementProto.NlbPort nlbPort = sshTunnelingConfiguration.getNlbPort(); String ccmHostAddressString = nlbPort.getNlbFqdn(); int ccmPort = nlbPort.getPort(); String ccmPublicKey = sshTunnelingConfiguration.getSshdPublicKey().toStringUtf8(); String minaSshdServiceId = minaSshdService.getMinaSshdServiceId(); return new DefaultServerParameters(new BaseServiceEndpoint(new HostEndpoint(ccmHostAddressString), ccmPort, null), "ssh-rsa " + ccmPublicKey + "\n", minaSshdServiceId); } }
apache-2.0
hekonsek/quickstarts
apps/fabric8mq/src/test/java/io/fabric8/apps/mq/MQKubernetes.java
1910
/* * Copyright 2005-2014 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.apps.mq; import io.fabric8.arquillian.kubernetes.Session; import io.fabric8.kubernetes.api.KubernetesClient; import io.fabric8.kubernetes.api.model.Pod; import org.assertj.core.api.Condition; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Test; import org.junit.runner.RunWith; import static io.fabric8.kubernetes.assertions.Assertions.assertThat; @RunWith(Arquillian.class) public class MQKubernetes { @ArquillianResource KubernetesClient client; @ArquillianResource Session session; /* * If you receive java.lang.NoSuchMethodError, check issue #3499 */ @Test public void testKubernetes() throws Exception { String serviceName = "fabric8mq"; assertThat(client).replicationController(serviceName).isNotNull(); assertThat(client).hasServicePort(serviceName, 6163); assertThat(client).pods() .runningStatus() .filterNamespace(session.getNamespace()) .haveAtLeast(1, new Condition<Pod>() { @Override public boolean matches(Pod podSchema) { return true; } }); } }
apache-2.0
aleo72/ww-ceem-radar
src/main/java/gov/nasa/worldwind/util/TileKey.java
6232
/* * Copyright (C) 2012 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. * All Rights Reserved. */ package gov.nasa.worldwind.util; import gov.nasa.worldwind.geom.Angle; /** * @author tag * @version $Id: TileKey.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class TileKey implements Comparable<TileKey> { private final int level; private final int row; private final int col; private final String cacheName; private final int hash; /** * @param level * @param row * @param col * @param cacheName * @throws IllegalArgumentException if <code>level</code>, <code>row</code> or <code>column</code> is negative or if * <code>cacheName</code> is null or empty */ public TileKey(int level, int row, int col, String cacheName) { if (level < 0) { String msg = Logging.getMessage("TileKey.levelIsLessThanZero"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // if (row < 0) // { // String msg = Logging.getMessage("generic.RowIndexOutOfRange", row); // Logging.logger().severe(msg); // throw new IllegalArgumentException(msg); // } // if (col < 0) // { // String msg = Logging.getMessage("generic.ColumnIndexOutOfRange", col); // Logging.logger().severe(msg); // throw new IllegalArgumentException(msg); // } if (cacheName == null || cacheName.length() < 1) { String msg = Logging.getMessage("TileKey.cacheNameIsNullOrEmpty"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.level = level; this.row = row; this.col = col; this.cacheName = cacheName; this.hash = this.computeHash(); } /** * @param latitude * @param longitude * @param levelNumber * @throws IllegalArgumentException if any parameter is null */ public TileKey(Angle latitude, Angle longitude, LevelSet levelSet, int levelNumber) { if (latitude == null || longitude == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } if (levelSet == null) { String msg = Logging.getMessage("nullValue.LevelSetIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Level l = levelSet.getLevel(levelNumber); this.level = levelNumber; this.row = Tile.computeRow(l.getTileDelta().getLatitude(), latitude, levelSet.getTileOrigin().getLatitude()); this.col = Tile.computeColumn(l.getTileDelta().getLongitude(), longitude, levelSet.getTileOrigin().getLongitude()); this.cacheName = l.getCacheName(); this.hash = this.computeHash(); } /** * @param tile * @throws IllegalArgumentException if <code>tile</code> is null */ public TileKey(Tile tile) { if (tile == null) { String msg = Logging.getMessage("nullValue.TileIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.level = tile.getLevelNumber(); this.row = tile.getRow(); this.col = tile.getColumn(); this.cacheName = tile.getCacheName(); this.hash = this.computeHash(); } public int getLevelNumber() { return level; } public int getRow() { return row; } public int getColumn() { return col; } public String getCacheName() { return cacheName; } private int computeHash() { int result; result = this.level; result = 29 * result + this.row; result = 29 * result + this.col; result = 29 * result + (this.cacheName != null ? this.cacheName.hashCode() : 0); return result; } /** * Compare two tile keys. Keys are ordered based on level, row, and column (in that order). * * @param key Key to compare with. * * @return 0 if the keys are equal. 1 if this key &gt; {@code key}. -1 if this key &lt; {@code key}. * * @throws IllegalArgumentException if <code>key</code> is null */ public final int compareTo(TileKey key) { if (key == null) { String msg = Logging.getMessage("nullValue.KeyIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // No need to compare Sectors because they are redundant with row and column if (key.level == this.level && key.row == this.row && key.col == this.col) return 0; if (this.level < key.level) // Lower-res levels compare lower than higher-res return -1; if (this.level > key.level) return 1; if (this.row < key.row) return -1; if (this.row > key.row) return 1; if (this.col < key.col) return -1; return 1; // tile.col must be > this.col because equality was tested above } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final TileKey tileKey = (TileKey) o; if (this.col != tileKey.col) return false; if (this.level != tileKey.level) return false; //noinspection SimplifiableIfStatement if (this.row != tileKey.row) return false; return !(this.cacheName != null ? !this.cacheName.equals(tileKey.cacheName) : tileKey.cacheName != null); } @Override public int hashCode() { return this.hash; } @Override public String toString() { return this.cacheName + "/" + this.level + "/" + this.row + "/" + col; } }
apache-2.0
whmain/LivingHelper
app/src/androidTest/java/com/ahern/livinghelper/ExampleInstrumentedTest.java
748
package com.ahern.livinghelper; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.ahern.livinghelper", appContext.getPackageName()); } }
apache-2.0
intellimate/Server
src/main/java/org/intellimate/server/proto/AppListOrBuilder.java
962
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: server-protobuf/app_list.proto package org.intellimate.server.proto; public interface AppListOrBuilder extends // @@protoc_insertion_point(interface_extends:intellimate.AppList) com.google.protobuf.MessageOrBuilder { /** * <code>repeated .intellimate.App apps = 1;</code> */ java.util.List<org.intellimate.server.proto.App> getAppsList(); /** * <code>repeated .intellimate.App apps = 1;</code> */ org.intellimate.server.proto.App getApps(int index); /** * <code>repeated .intellimate.App apps = 1;</code> */ int getAppsCount(); /** * <code>repeated .intellimate.App apps = 1;</code> */ java.util.List<? extends org.intellimate.server.proto.AppOrBuilder> getAppsOrBuilderList(); /** * <code>repeated .intellimate.App apps = 1;</code> */ org.intellimate.server.proto.AppOrBuilder getAppsOrBuilder( int index); }
apache-2.0
xuhaoyang/Weibo
app/src/main/java/com/xhy/weibo/ui/vh/KeepViewHolder.java
5843
package com.xhy.weibo.ui.vh; import android.content.Context; import android.support.v7.widget.CardView; import android.support.v7.widget.PopupMenu; import android.text.TextUtils; import android.view.MenuItem; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.xhy.weibo.R; import com.xhy.weibo.model.Status; import com.xhy.weibo.api.URLs; import com.xhy.weibo.ui.activity.UserInfoActivity; import com.xhy.weibo.ui.activity.WriteStatusActivity; import com.xhy.weibo.utils.Constants; import com.xhy.weibo.utils.DateUtils; import com.xhy.weibo.utils.StringUtils; import java.util.HashMap; import hk.xhy.android.common.bind.ViewById; import hk.xhy.android.common.ui.vh.OnListItemClickListener; import hk.xhy.android.common.ui.vh.ViewHolder; import hk.xhy.android.common.utils.ActivityUtils; import hk.xhy.android.common.utils.GsonUtil; import hk.xhy.android.common.utils.ScreenUtils; /** * Created by xuhaoyang on 2017/2/25. */ public class KeepViewHolder extends ViewHolder { private static final String TAG = KeepViewHolder.class.getSimpleName(); @ViewById(R.id.iv_avatar) public ImageView iv_avatar; @ViewById(R.id.tv_subhead) public TextView tv_subhead; @ViewById(R.id.tv_content) public TextView tv_content; @ViewById(R.id.tv_caption) public TextView tv_caption; @ViewById(R.id.cv_item) public CardView cv_item; private boolean animateItems = false; private int lastAnimatedPosition = -1; public KeepViewHolder(View itemView) { super(itemView); } /** * @param context * @param model * @param listener */ public void bind(final Context context, final Status model, final OnListItemClickListener listener) { if (model != null) { runEnterAnimation(this.itemView, getAdapterPosition()); //设置头像 if (TextUtils.isEmpty(model.getUserinfo().getFace50())) { iv_avatar.setImageResource(R.drawable.user_avatar); } else { String url = URLs.AVATAR_IMG_URL + model.getUserinfo().getFace50(); Glide.with(iv_avatar.getContext()).load(url).error(R.drawable.user_avatar). fitCenter().into(iv_avatar); } iv_avatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ActivityUtils.startActivityByContext(itemView.getContext(), UserInfoActivity.class , new HashMap<String, Object>() {{ put(Constants.USER_ID, model.getUid()); }}); } }); //设置用户名 tv_subhead.setText(model.getUserinfo().getUsername()); //设置时间 tv_caption.setText(DateUtils.getShotTime(model.getTime())); //设置正文 tv_content.setText( StringUtils.getWeiboContent(itemView.getContext(), tv_content, model.getContent())); cv_item.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPopupMenu(tv_caption, model); // listener.OnListItemClick(getAdapterPosition()); } }); } } private void runEnterAnimation(View itemView, int position) { animateItems = true; /** * 动画效果不好 暂时性改成能接受 */ if (position <= 8) { return; } if (position > lastAnimatedPosition) { lastAnimatedPosition = position; itemView.setTranslationY(ScreenUtils.getScreenHeight() / 2); itemView.animate() .translationY(0) // .setStartDelay(100 * position) .setInterpolator(new DecelerateInterpolator(2.f)) .setDuration(500) .start(); } } public void showPopupMenu(View view, final Status model) { //参数View 是设置当前菜单显示的相对于View组件位置,具体位置系统会处理 PopupMenu popupMenu = new PopupMenu(itemView.getContext(), view); //加载menu布局 popupMenu.getMenuInflater().inflate(R.menu.menu_status_detail_comment, popupMenu.getMenu()); //设置menu中的item点击事件 popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_commet_comment: ActivityUtils.startActivityByContext(itemView.getContext(), WriteStatusActivity.class, new HashMap<String, Object>() {{ put(Constants.TYPE, Constants.FORWARD_TYPE); put(Constants.TAG, Constants.COMMENT_ADPATER_CODE); put(Constants.STATUS_INTENT, GsonUtil.toJson(model)); }}); break; // case R.id.action_commet_forward: // break; } return true; } }); //设置popupWindow消失的点击事件 popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() { @Override public void onDismiss(PopupMenu menu) { } }); popupMenu.show(); } }
apache-2.0
hoangdongtien/studentlog
StudentLog/src/com/aprotrain/sl/dal/dao/impl/EmployeeServiceImpl.java
1590
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.aprotrain.sl.dal.dao.impl; import com.aprotrain.sl.dal.common.AbstractDao; import com.aprotrain.sl.dal.entity.Course; import com.aprotrain.sl.dal.entity.Employee; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; /** * * @author admin */ public class EmployeeServiceImpl extends AbstractDao<Employee> { public EmployeeServiceImpl() { super(); this.setEntityType(Employee.class); } public Employee checkLogin(String internalEmail, String password) { Session session = this.getSession(); Query query = session.createQuery("FROM Employee WHERE internalEmail=:mail AND password=:password"); query.setString("mail", internalEmail); query.setString("password", password); query.setMaxResults(1); List<Employee> list = query.list(); Employee e = null; if (!list.isEmpty()) { e = list.get(0); } session.close(); return e; } public List<Employee> search(String FullName) { Session session = this.getSession(); Query query = session.createQuery("FROM Employee WHERE FullName like '%' + :FName + '%'"); query.setParameter("FName", FullName); List<Employee> list = query.list(); session.close(); return list; } }
apache-2.0
joel-costigliola/assertj-core
src/test/java/org/assertj/core/condition/JediCondition.java
1204
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2020 the original author or authors. */ package org.assertj.core.condition; import static org.assertj.core.util.Sets.newLinkedHashSet; import java.util.Set; import org.assertj.core.api.Condition; /** * * A {@code Condition} checking is a Jedi * * @author Nicolas François */ public class JediCondition extends Condition<String> { private final Set<String> jedis = newLinkedHashSet("Luke", "Yoda", "Obiwan"); JediCondition(String description) { super(description); } public JediCondition() { super("Jedi"); } @Override public boolean matches(String value) { return jedis.contains(value); } }
apache-2.0
jbertram/activemq-artemis-old
artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/NamedNodeIdNodeLocator.java
2137
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.core.server.impl; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.TopologyMember; import org.apache.activemq.artemis.core.server.LiveNodeLocator; public class NamedNodeIdNodeLocator extends LiveNodeLocator { private final String nodeID; private final Pair<TransportConfiguration, TransportConfiguration> liveConfiguration; public NamedNodeIdNodeLocator(String nodeID, Pair<TransportConfiguration, TransportConfiguration> liveConfiguration) { this.nodeID = nodeID; this.liveConfiguration = liveConfiguration; } @Override public void locateNode(long timeout) throws ActiveMQException { //noop } @Override public void locateNode() throws ActiveMQException { //noop } @Override public Pair<TransportConfiguration, TransportConfiguration> getLiveConfiguration() { return liveConfiguration; } @Override public String getNodeID() { return nodeID; } @Override public void nodeUP(TopologyMember member, boolean last) { } @Override public void nodeDown(long eventUID, String nodeID) { } }
apache-2.0
heroiclabs/nakama
console/ui/src/app/account/friends/friends.component.ts
2616
// Copyright 2020 The Nakama 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. import {Component, Injectable, OnInit} from '@angular/core'; import { ApiAccount, ApiFriend, ApiFriendList, ConsoleService, UserRole, } from '../../console.service'; import {ActivatedRoute, ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot} from '@angular/router'; import {AuthenticationService} from '../../authentication.service'; import {Observable} from 'rxjs'; @Component({ templateUrl: './friends.component.html', styleUrls: ['./friends.component.scss'] }) export class FriendsComponent implements OnInit { public error = ''; public account: ApiAccount; public friends: Array<ApiFriend> = []; constructor( private readonly route: ActivatedRoute, private readonly router: Router, private readonly consoleService: ConsoleService, private readonly authService: AuthenticationService, ) {} ngOnInit(): void { this.route.data.subscribe( d => { this.friends.length = 0; this.friends.push(...d[0].friends); }, err => { this.error = err; }); this.route.parent.data.subscribe( d => { this.account = d[0].account; }, err => { this.error = err; }); } deleteAllowed(): boolean { return this.authService.sessionRole <= UserRole.USER_ROLE_MAINTAINER; } deleteFriend(event, i: number, f: ApiFriend): void { event.target.disabled = true; event.preventDefault(); this.error = ''; this.consoleService.deleteFriend('', this.account.user.id, f.user.id).subscribe(() => { this.error = ''; this.friends.splice(i, 1); }, err => { this.error = err; }); } } @Injectable({providedIn: 'root'}) export class FriendsResolver implements Resolve<ApiFriendList> { constructor(private readonly consoleService: ConsoleService) {} resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<ApiFriendList> { const userId = route.parent.paramMap.get('id'); return this.consoleService.getFriends('', userId); } }
apache-2.0