repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
AppCamps/TeachingPlatform
|
frontend/containers/posts/index.js
|
import { connect } from "react-redux";
import Posts from "../../components/posts";
import { fetchPosts } from "../../actions/posts";
import { postsSelector, postsPaginationSelector } from "../../selectors/posts";
import { userSelector } from "../../selectors/shared/user";
export function mapStateToProps(state) {
const pagination = postsPaginationSelector(state);
return {
posts: postsSelector(state, pagination.current),
pagination,
user: userSelector(state),
};
}
export function mapDispatchToProps(dispatch) {
return {
fetchPosts: (fragments, user) => dispatch(fetchPosts(fragments, user)),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Posts);
|
tgodzik/intellij-community
|
platform/platform-tests/testSrc/com/intellij/psi/search/scope/packageSet/PatternRegexpConvertorTest.java
|
<gh_stars>1-10
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.search.scope.packageSet;
import junit.framework.TestCase;
public class PatternRegexpConvertorTest extends TestCase {
public void testConvertToRegexp() {
assertEquals("a\\.[^\\.]*", FilePatternPackageSet.convertToRegexp("a.*", '.'));
assertEquals("a\\.(.*\\.)?[^\\.]*", FilePatternPackageSet.convertToRegexp("a..*", '.'));
assertEquals("a\\/[^\\/]*", FilePatternPackageSet.convertToRegexp("a/*", '/'));
assertEquals("a\\/.*\\.css", FilePatternPackageSet.convertToRegexp("a/*.css", '/'));
assertEquals("a\\/(.*\\/)?[^\\/]*", FilePatternPackageSet.convertToRegexp("a//*", '/'));
assertEquals("[^\\.]*", FilePatternPackageSet.convertToRegexp("*", '.'));
}
}
|
jonnatanSoftware/lutece-core-5.1.2-master
|
src/java/fr/paris/lutece/portal/business/user/AdminUserHome.java
|
<filename>src/java/fr/paris/lutece/portal/business/user/AdminUserHome.java<gh_stars>0
/*
* Copyright (c) 2002-2014, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* License 1.0
*/
package fr.paris.lutece.portal.business.user;
import fr.paris.lutece.portal.business.rbac.AdminRole;
import fr.paris.lutece.portal.business.right.Right;
import fr.paris.lutece.portal.business.user.authentication.LuteceDefaultAdminUser;
import fr.paris.lutece.portal.service.spring.SpringContextService;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* This class provides instances management methods (create, find, ...) for AdminUser objects
*/
public final class AdminUserHome
{
// Static variable pointed at the DAO instance
private static IAdminUserDAO _dao = (IAdminUserDAO) SpringContextService.getBean( "adminUserDAO" );
/**
* Private constructor
*/
private AdminUserHome( )
{
}
/**
* Get the user infos from the access code.
* @param strUserLogin the login
* @return user info
*/
public static AdminUser findUserByLogin( String strUserLogin )
{
return _dao.selectUserByAccessCode( strUserLogin );
}
/**
* Get the user access code from its email.
* @param strEmail The email
* @return The access code of the user with the given email, or null if no user has been found
*/
public static String findUserByEmail( String strEmail )
{
return _dao.selectUserByEmail( strEmail );
}
/**
* Get the user infos from user id
* @param nUserId the user identifier
* @return The user
*/
public static AdminUser findByPrimaryKey( int nUserId )
{
return _dao.load( nUserId );
}
/**
* @return the user list
*/
public static Collection<AdminUser> findUserList( )
{
return _dao.selectUserList( );
}
/**
* @param user The AdminUser
*/
public static void create( AdminUser user )
{
_dao.insert( user );
}
/**
* @param user The AdminUser
*/
public static void update( AdminUser user )
{
_dao.store( user );
}
/**
* @param nUserId the user identifier
*/
public static void remove( int nUserId )
{
_dao.delete( nUserId );
}
/**
* Get the right list associated to a given user id
* @param nUserId the id of the user to retrieve rights
* @return the right list
*/
public static Map<String, Right> getRightsListForUser( int nUserId )
{
return _dao.selectRightsListForUser( nUserId );
}
/**
* @param nUserId The user identifier
* @param strRightId The right identifier
*/
public static void createRightForUser( int nUserId, String strRightId )
{
_dao.insertRightsListForUser( nUserId, strRightId );
}
/**
* @param nUserId The user identifier
*/
public static void removeAllRightsForUser( int nUserId )
{
_dao.deleteAllRightsForUser( nUserId );
}
/**
* @param user The Admin User object
*/
public static void removeAllDelegatedRightsForUser( AdminUser user )
{
_dao.deleteAllDelegatedRightsForUser( user.getUserId( ), user.getUserLevel( ) );
}
/**
* @param user The Admin User object
*/
public static void removeAllOwnRightsForUser( AdminUser user )
{
_dao.deleteAllOwnRightsForUser( user.getUserId( ), user.getUserLevel( ) );
}
/**
* Get the role list associated to a given user id
* @param nUserId the id of the user to retrieve rights
* @return the role list
*/
public static Map<String, AdminRole> getRolesListForUser( int nUserId )
{
return _dao.selectRolesListForUser( nUserId );
}
/**
* @param nUserId the id of the user
* @param strRightId the right identifier
*/
public static void createRoleForUser( int nUserId, String strRightId )
{
_dao.insertRolesListForUser( nUserId, strRightId );
}
/**
* @param nUserId the user identifier
*/
public static void removeAllRolesForUser( int nUserId )
{
_dao.deleteAllRolesForUser( nUserId );
}
/**
* Checks wether the role is in use or not
* @param strRoleKey the role key to check
* @return true if the role is attributed, false otherwise
*/
public static boolean checkRoleAttributed( String strRoleKey )
{
return _dao.checkRoleAttributed( strRoleKey );
}
/**
* Checks if a given login is already in use
* @param strAccessCode The login
* @return user ID if the access code is already used by another user, -1 otherwise
*/
public static int checkAccessCodeAlreadyInUse( String strAccessCode )
{
return _dao.checkAccessCodeAlreadyInUse( strAccessCode );
}
/**
* Checks if a given email is already in use
* @param strEmail The email
* @return user ID if the email is already used by another user, -1 otherwise
*/
public static int checkEmailAlreadyInUse( String strEmail )
{
return _dao.checkEmailAlreadyInUse( strEmail );
}
/**
* Check if the user has the role
* @param user The AdminUser
* @param strRoleKey The role Key
* @return true if the user has the role
*/
public static boolean hasRole( AdminUser user, String strRoleKey )
{
return _dao.hasRole( user.getUserId( ), strRoleKey );
}
/**
* Remove role for an user
* @param nUserId The ID of the user
* @param strRoleKey The role key
*/
public static void removeRoleForUser( int nUserId, String strRoleKey )
{
_dao.deleteRoleForUser( nUserId, strRoleKey );
}
// ////////////////////////////////////////////////////////////////
// / for no-module mode
/**
* @param user the LuteceDefaultAdminUSer
*/
public static void create( LuteceDefaultAdminUser user )
{
_dao.insert( user );
}
/**
* @param user the LuteceDefaultAdminUSer
*/
public static void update( LuteceDefaultAdminUser user )
{
_dao.store( user );
}
/**
* Get the user infos from user id
* @param nUserId the user identifier
* @return the delfault admin user
*/
public static LuteceDefaultAdminUser findLuteceDefaultAdminUserByPrimaryKey( int nUserId )
{
return _dao.loadDefaultAdminUser( nUserId );
}
/**
* Get all users having a given role
* @param strRoleKey The role key
* @return A collection of AdminUser
*/
public static Collection<AdminUser> findByRole( String strRoleKey )
{
return _dao.selectUsersByRole( strRoleKey );
}
/**
* Get all users having a given level
* @param nIdLevel The level
* @return A collection of AdminUser
*/
public static Collection<AdminUser> findByLevel( int nIdLevel )
{
return _dao.selectUsersByLevel( nIdLevel );
}
/**
* Update role key if role key name has change
* @param strOldRoleKey The old role key name
* @param role The new role
*/
public static void updateUsersRole( String strOldRoleKey, AdminRole role )
{
_dao.storeUsersRole( strOldRoleKey, role );
}
/**
* Get all users by using a filter.
* @param auFilter The filter
* @return A collection of AdminUser
*/
public static Collection<AdminUser> findUserByFilter( AdminUserFilter auFilter )
{
return _dao.selectUsersByFilter( auFilter );
}
/**
* Get all users having a given right
* @param strIdRight The ID right
* @return A collection of AdminUser
*/
public static Collection<AdminUser> findByRight( String strIdRight )
{
return _dao.selectUsersByRight( strIdRight );
}
/**
* Check if the user has the given right
* @param user The Admin User
* @param strIdRight The ID right
* @return true if the user has the right
*/
public static boolean hasRight( AdminUser user, String strIdRight )
{
return _dao.hasRight( user.getUserId( ), strIdRight );
}
/**
* Remove a right for an user
* @param nUserId The user ID
* @param strIdRight The right ID
*/
public static void removeRightForUser( int nUserId, String strIdRight )
{
_dao.deleteRightForUser( nUserId, strIdRight );
}
/**
* Gets the history of password of the given user
* @param nUserID Id of the user
* @return The collection of recent passwords used by the user.
*/
public static List<String> selectUserPasswordHistory( int nUserID )
{
return _dao.selectUserPasswordHistory( nUserID );
}
/**
* Get the number of password change done by a user since the given date.
* @param minDate Minimum date to consider.
* @param nUserId Id of the user
* @return The number of password change done by the user since the given date.
*/
public static int countUserPasswordHistoryFromDate( Timestamp minDate, int nUserId )
{
return _dao.countUserPasswordHistoryFromDate( minDate, nUserId );
}
/**
* Log a password change in the password history
* @param strPassword <PASSWORD> of the user
* @param nUserId Id of the user
*/
public static void insertNewPasswordInHistory( String strPassword, int nUserId )
{
_dao.insertNewPasswordInHistory( strPassword, nUserId );
}
/**
* Remove every password saved in the password history for a user.
* @param nUserId Id of the user
*/
public static void removeAllPasswordHistoryForUser( int nUserId )
{
_dao.removeAllPasswordHistoryForUser( nUserId );
}
/**
* Get a map of anonymization status of a user field.
* @return A map containing the associations of user field name and a boolean describing whether the field should be anonymized.
*/
public static Map<String, Boolean> getAnonymizationStatusUserStaticField( )
{
return _dao.selectAnonymizationStatusUserStaticField( );
}
/**
* Update the anonymization status of a user field.
* @param strFieldName Name of the field to update
* @param bAnonymizeFiled True if the field should be anonymize, false otherwise
*/
public static void updateAnonymizationStatusUserStaticField( String strFieldName, boolean bAnonymizeFiled )
{
_dao.updateAnonymizationStatusUserStaticField( strFieldName, bAnonymizeFiled );
}
/**
* Get the list of id of user with the expired status.
* @return The list of if of user with the expired status.
*/
public static List<Integer> findAllExpiredUserId( )
{
return _dao.findAllExpiredUserId( );
}
/**
* Get the list of id of users that have an expired time life but not the expired status
* @param currentTimestamp Timestamp describing the current time.
* @return the list of id of users with expired time life
*/
public static List<Integer> getIdUsersWithExpiredLifeTimeList( Timestamp currentTimestamp )
{
return _dao.getIdUsersWithExpiredLifeTimeList( currentTimestamp );
}
/**
* Get the list of id of users that need to receive their first alert
* @param firstAlertMaxDate The maximum expiration date to send first alert.
* @return the list of id of users that need to receive their first alert
*/
public static List<Integer> getIdUsersToSendFirstAlert( Timestamp firstAlertMaxDate )
{
return _dao.getIdUsersToSendFirstAlert( firstAlertMaxDate );
}
/**
* Get the list of id of users that need to receive their first alert
* @param alertMaxDate The maximum date to send alerts.
* @param timeBetweenAlerts Timestamp describing the time between two alerts.
* @param maxNumberAlerts Maximum number of alerts to send to a user
* @return the list of id of users that need to receive their first alert
*/
public static List<Integer> getIdUsersToSendOtherAlert( Timestamp alertMaxDate, Timestamp timeBetweenAlerts,
int maxNumberAlerts )
{
return _dao.getIdUsersToSendOtherAlert( alertMaxDate, timeBetweenAlerts, maxNumberAlerts );
}
/**
* Get the list of id of users that have an expired password but not the change password flag
* @param currentTimestamp Timestamp describing the current time.
* @return the list of id of users with expired passwords
*/
public static List<Integer> getIdUsersWithExpiredPasswordsList( Timestamp currentTimestamp )
{
return _dao.getIdUsersWithExpiredPasswordsList( currentTimestamp );
}
/**
* Update status of a list of user accounts
* @param listIdUser List of user accounts to update
* @param nNewStatus New status of the user
*/
public static void updateUserStatus( List<Integer> listIdUser, int nNewStatus )
{
_dao.updateUserStatus( listIdUser, nNewStatus );
}
/**
* Increment the number of alert send to users by 1
* @param listIdUser The list of users to update
*/
public static void updateNbAlert( List<Integer> listIdUser )
{
_dao.updateNbAlert( listIdUser );
}
/**
* Set the "change password" flag of users to true
* @param listIdUser The list of users to update
*/
public static void updateChangePassword( List<Integer> listIdUser )
{
_dao.updateChangePassword( listIdUser );
}
/**
* Update the admin user expiration date with the new values. Also update his alert account to 0
* @param nIdUser Id of the admin user to update
* @param newExpirationDate Id of the user to update
*/
public static void updateUserExpirationDate( int nIdUser, Timestamp newExpirationDate )
{
_dao.updateUserExpirationDate( nIdUser, newExpirationDate );
}
/**
* Update the admin user last login date.
* @param nIdUser Id of the admin user to update
* @param dateLastLogin New last login date of the user
*/
public static void updateDateLastLogin( int nIdUser, Timestamp dateLastLogin )
{
_dao.updateDateLastLogin( nIdUser, dateLastLogin );
}
}
|
altermarkive/training
|
algorithms/code/leetcode/lc344_reverse_string/LC344ReverseStringTests.java
|
<gh_stars>0
package leetcode.lc344_reverse_string;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public final class LC344ReverseStringTests {
@Test
public void testExample() throws Exception {
char[] s = { 'h', 'e', 'l', 'l', 'o' };
new LC344ReverseString().reverseString(s);
assertArrayEquals(new char[] { 'o', 'l', 'l', 'e', 'h' }, s);
}
}
|
BerciTheBeast/chess-api
|
node_modules/chess-ai-kong/src/monitoring/monitoring.js
|
'use strict';
var cutoffs = [];
var consoleTree = [];
var nbNodeSearched = 0;
var nbCutoffs = 0;
var watches = require('./watches');
//Settings
var enabled = false;
function isEnabled() {
return enabled;
}
function setEnabled(enabledFlag) {
if(enabledFlag === undefined || typeof enabledFlag !== 'boolean') {
throw new Error('monitor value type!');
} else {
enabled = enabledFlag;
}
}
/**
* Add a cutoff node.
*
* @param path The node path
* @param alpha The alpha
* @param beta The beta
* @param type The type of search (Maximizing or Minimizing)
* @param score The score
*/
function addCutoffNode(path, alpha, beta, type, score) {
if(enabled) {
cutoffs.push(
{
path: path,
alpha: alpha,
beta: beta,
type: type,
score: score
}
);
}
}
/**
* Add a search node.
*
* @param path The node path
* @param alpha The alpha
* @param beta The beta
* @param type The type (min or max)
* @param score The score
*/
function addSearchNode(path, alpha, beta, type, score) {
if(enabled) {
consoleTree.push(
{
path: path,
alpha: alpha,
beta: beta,
type: type,
score: score
}
);
}
}
/**
* Start the watch. If the watch does not exist, it is created.
*
* @param itemKey The watch key
*/
function startWatch(itemKey) {
if(enabled) {
watches.startWatch(itemKey)
}
}
/**
* Stop the watch.
*
* @param itemKey The watch key
*/
function stopWatch(itemKey) {
if(enabled) {
watches.stopWatch(itemKey)
}
}
/**
* Reset all monitoring variables.
*/
function reset() {
if(enabled) {
cutoffs.splice(0, cutoffs.length);
consoleTree.splice(0, consoleTree.length);
nbNodeSearched = 0;
nbCutoffs = 0;
watches.reset();
}
}
/**
* Clear all monitoring devices.
*/
function clear() {
if (enabled) {
cutoffs.splice(0, cutoffs.length);
consoleTree.splice(0, consoleTree.length);
nbNodeSearched = 0;
nbCutoffs = 0;
watches.clear();
}
}
/**
* Print logs monitored logs in the console.
*
* @param full true to dump the full logs.
* @param string true to dump logs as String, false to dump objects
*/
function dumpLogs(full, string) {
if (enabled) {
console.log(consoleTree.length + ' node searched');
console.log(cutoffs.length + ' cut-offs');
//Log watches
watches.dumpLogs();
if(full) {
if (string) {
var strings;
if (cutoffs.length > 0) {
strings = ['--CUTOFFS--'];
cutoffs.forEach(function (cutoff) {
strings.push('\n');
strings.push('{'
+ 'path: ' + cutoff.path
+ ', type: ' + cutoff.type
+ ', alpha: ' + cutoff.alpha
+ ', beta: ' + cutoff.beta
+ ', score: ' + cutoff.score
+ '}');
});
console.log(strings.join(''));
}
if (consoleTree.length > 0) {
strings = ['--TREE--'];
consoleTree.forEach(function (node) {
strings.push('\n');
strings.push('{'
+ 'path: ' + node.path
+ ', type: ' + node.type
+ ', alpha: ' + node.alpha
+ ', beta: ' + node.beta
+ ', score: ' + node.score
+ '}');
});
console.log(strings.join(''));
}
} else {
console.log(consoleTree);
console.log(cutoffs);
}
}
}
}
module.exports.addSearchNode = addSearchNode;
module.exports.addCutoffNode = addCutoffNode;
module.exports.setEnabled = setEnabled;
module.exports.isEnabled = isEnabled;
module.exports.startWatch = startWatch;
module.exports.stopWatch = stopWatch;
module.exports.dumpLogs = dumpLogs;
module.exports.clear = clear;
module.exports.reset = reset;
|
omkarshinde221/etherpad
|
src/node_modules/etherpad-require-kernel/mock_require.js
|
<reponame>omkarshinde221/etherpad<gh_stars>10-100
/*!
require-kernel
Created by <NAME> on 01/04/11.
Released to the Public Domain on 17/01/12.
*/
var fs = require('fs');
var pathutil = require('path');
var urlutil = require('url');
var events = require('events');
var kernelPath = pathutil.join(__dirname, 'kernel.js');
var kernel = fs.readFileSync(kernelPath, 'utf8');
var buildKernel = require('vm').runInThisContext(
'(function (XMLHttpRequest) {return ' + kernel + '})', kernelPath);
/* Cheap URL request implementation */
var fs_client = (new function () {
var STATUS_MESSAGES = {
403: '403: Access denied.'
, 404: '404: File not found.'
, 405: '405: Only the HEAD or GET methods are allowed.'
, 500: '500: Error reading file.'
};
function request(options, callback) {
var path = fsPathForURIPath(options.path);
var method = options.method;
var response = new (require('events').EventEmitter);
response.setEncoding = function (encoding) {this._encoding = encoding};
response.statusCode = 504;
response.headers = {};
var request = new (require('events').EventEmitter);
request.end = function () {
if (options.method != 'HEAD' && options.method != 'GET') {
response.statusCode = 405;
response.headers['Allow'] = 'HEAD, GET';
callback(response);
response.emit('data', STATUS_MESSAGES[response.statusCode])
response.emit('end');
} else {
fs.stat(path, function (error, stats) {
if (error) {
if (error.code == 'ENOENT') {
response.StatusCode = 404;
} else if (error.code == 'EACCESS') {
response.StatusCode = 403;
} else {
response.StatusCode = 502;
}
} else if (stats.isFile()) {
var date = new Date()
var modifiedLast = new Date(stats.mtime);
var modifiedSince = (options.headers || {})['if-modified-since'];
response.headers['Date'] = date.toUTCString();
response.headers['Last-Modified'] = modifiedLast.toUTCString();
if (modifiedSince && modifiedLast
&& modifiedSince >= modifiedLast) {
response.StatusCode = 304;
} else {
response.statusCode = 200;
}
} else {
response.StatusCode = 404;
}
if (method == 'HEAD') {
callback(response);
response.emit('end');
} else if (response.statusCode != 200) {
response.headers['Content-Type'] = 'text/plain; charset=utf-8';
callback(response);
response.emit('data', STATUS_MESSAGES[response.statusCode])
response.emit('end');
} else {
fs.readFile(path, function (error, text) {
if (error) {
if (error.code == 'ENOENT') {
response.statusCode = 404;
} else if (error.code == 'EACCESS') {
response.statusCode = 403;
} else {
response.statusCode = 502;
}
response.headers['Content-Type'] = 'text/plain; charset=utf-8';
callback(response);
response.emit('data', STATUS_MESSAGES[response.statusCode])
response.emit('end');
} else {
response.statusCode = 200;
response.headers['Content-Type'] =
'application/javascript; charset=utf-8';
callback(response);
response.emit('data', text);
response.emit('end');
}
});
}
});
}
};
return request;
}
this.request = request;
}());
function requestURL(url, method, headers, callback) {
var parsedURL = urlutil.parse(url);
var client = undefined;
if (parsedURL.protocol == 'file:') {
client = fs_client;
} else if (parsedURL.protocol == 'http:') {
client = require('http');
} else if (parsedURL.protocol == 'https:') {
client = require('https');
}
if (client) {
var request = client.request({
host: parsedURL.host
, port: parsedURL.port
, path: parsedURL.path
, method: method
, headers: headers
}, function (response) {
var buffer = undefined;
response.setEncoding('utf8');
response.on('data', function (chunk) {
buffer = buffer || '';
buffer += chunk;
});
response.on('close', function () {
callback(502, {});
});
response.on('end', function () {
callback(response.statusCode, response.headers, buffer);
});
});
request.on('error', function () {
callback(502, {});
});
request.end();
}
}
function fsPathForURIPath(path) {
path = decodeURIComponent(path);
if (path.charAt(0) == '/') { // Account for '/C:\Windows' type of paths.
path = pathutil.resolve('/', path.slice(1));
}
path = pathutil.normalize(path);
return path;
}
function normalizePathAsURI(path) {
var parsedUrl = urlutil.parse(path);
if (parsedUrl.protocol === undefined) {
parsedUrl.protocol = 'file:';
parsedUrl.path = pathutil.resolve(parsedUrl.path);
}
return urlutil.format(parsedUrl);
}
var buildMockXMLHttpRequestClass = function () {
var emitter = new events.EventEmitter();
var requestCount = 0;
var idleTimer = undefined;
var idleHandler = function () {
emitter.emit('idle');
};
var requested = function (info) {
clearTimeout(idleTimer);
requestCount++;
emitter.emit('requested', info);
};
var responded = function (info) {
emitter.emit('responded', info);
requestCount--;
if (requestCount == 0) {
idleTimer = setTimeout(idleHandler, 0);
}
};
var MockXMLHttpRequest = function () {
};
MockXMLHttpRequest.prototype = new function () {
this.open = function(method, url, async) {
this.async = async;
this.url = normalizePathAsURI(url);
}
this.withCredentials = false; // Pass CORS capability checks.
this.send = function () {
var parsedURL = urlutil.parse(this.url);
var info = {
async: !!this.async
, url: this.url
};
if (!this.async) {
if (parsedURL.protocol == 'file:') {
requested(info);
try {
this.status = 200;
var path = fsPathForURIPath(parsedURL.pathname);
this.responseText = fs.readFileSync(path);
} catch (e) {
this.status = 404;
}
this.readyState = 4;
responded(info);
} else {
throw "The resource at " + JSON.stringify(this.url)
+ " cannot be retrieved synchronously.";
}
} else {
var self = this;
requestURL(this.url, 'GET', {},
function (status, headers, content) {
self.status = status;
self.responseText = content;
self.readyState = 4;
var handler = self.onreadystatechange;
handler && handler();
responded(info);
}
);
requested(info);
}
}
};
MockXMLHttpRequest.emitter = emitter;
return MockXMLHttpRequest;
}
function requireForPaths(rootPath, libraryPath) {
var MockXMLHttpRequest = buildMockXMLHttpRequestClass();
var mockRequire = buildKernel(MockXMLHttpRequest);
if (rootPath !== undefined) {
mockRequire.setRootURI(normalizePathAsURI(rootPath));
}
if (libraryPath != undefined) {
mockRequire.setLibraryURI(normalizePathAsURI(libraryPath));
}
mockRequire.emitter = MockXMLHttpRequest.emitter;
mockRequire._compileFunction = function (code, filename) {
return require('vm').runInThisContext('(function () {'
+ code + '\n'
+ '})', filename);
};
return mockRequire;
}
exports.kernelSource = kernel;
exports.requireForPaths = requireForPaths;
|
mikevegap/wicketinaction
|
src/main/java/wicket/in/action/common/Cheese.java
|
<gh_stars>0
package wicket.in.action.common;
import java.io.Serializable;
public final class Cheese implements Serializable {
private String description;
private String name;
private double price;
public Cheese() {
}
public Cheese(String name, String description, double price) {
super();
this.name = name;
this.description = description;
this.price = price;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Cheese) {
Cheese that = (Cheese) obj;
return Objects.equal(name, that.name);
}
return false;
}
public String getDescription() {
return description;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
@Override
public int hashCode() {
return Objects.hashCode(name);
}
public void setDescription(String description) {
this.description = description;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return name;
}
}
|
guodingfang/RuoYi-Vue
|
wisdomSite-ui/src/api/people/workerLib.js
|
<reponame>guodingfang/RuoYi-Vue
import request from '@/utils/request'
// 查询建筑工人库列表
export function getPtable(query) {
return request({
url: '/ws/teamPersonLibrary/list',
method: 'get',
params: query
})
}
// 详情
export function detailWork(id) {
return request({
url: '/ws/teamPersonLibrary/' + id,
method: 'get',
})
}
// 职业履历列表 deleted=1&id=
export function getRtable(query) {
return request({
url: '/ws/teamPerson/list',
method: 'get',
params: query
})
}
// 职业履历列表
export function getNtable(idNumber) {
return request({
url: `/ws/teamPersonLibrary/${idNumber}/ceitificates`,
method: 'get',
})
}
// 黑名单列表
export function getBtable(query) {
return request({
url: '/ws/blacklist/list',
method: 'get',
params: query
})
}
// 黑名单列表
export function getJtable(query) {
return request({
url: '/ws/projectParticipatingUnit/list',
method: 'get',
params: query
})
}
// // 查询班组下人员 列表
// export function getPerson(query) {
// return request({
// url: '/ws/teamPerson/list',
// method: 'get',
// params: query
// })
// }
// // 查询班组下人员 列表
// export function detailAtte(id) {
// return request({
// url: '/ws/attendanceRecord/list/' + id,
// method: 'get',
// })
// }
//
|
UnderflowDevelopment/RiseClient
|
src/main/java/net/minecraft/client/renderer/entity/layers/LayerArmorBase.java
|
<filename>src/main/java/net/minecraft/client/renderer/entity/layers/LayerArmorBase.java<gh_stars>1-10
package net.minecraft.client.renderer.entity.layers;
import com.google.common.collect.Maps;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.entity.RendererLivingEntity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.src.Config;
import net.minecraft.util.ResourceLocation;
import net.optifine.CustomItems;
import net.optifine.reflect.Reflector;
import net.optifine.reflect.ReflectorForge;
import net.optifine.shaders.Shaders;
import net.optifine.shaders.ShadersRender;
import java.util.Map;
public abstract class LayerArmorBase<T extends ModelBase> implements LayerRenderer<EntityLivingBase> {
protected static final ResourceLocation ENCHANTED_ITEM_GLINT_RES = new ResourceLocation("textures/misc/enchanted_item_glint.png");
private static final Map<String, ResourceLocation> ARMOR_TEXTURE_RES_MAP = Maps.newHashMap();
private final RendererLivingEntity<?> renderer;
private final float alpha = 1.0F;
private final float colorR = 1.0F;
private final float colorG = 1.0F;
private final float colorB = 1.0F;
protected T field_177189_c;
protected T field_177186_d;
private boolean field_177193_i;
public LayerArmorBase(final RendererLivingEntity<?> rendererIn) {
this.renderer = rendererIn;
this.initArmor();
}
public void doRenderLayer(final EntityLivingBase entitylivingbaseIn, final float p_177141_2_, final float p_177141_3_, final float partialTicks, final float p_177141_5_, final float p_177141_6_, final float p_177141_7_, final float scale) {
this.renderLayer(entitylivingbaseIn, p_177141_2_, p_177141_3_, partialTicks, p_177141_5_, p_177141_6_, p_177141_7_, scale, 4);
this.renderLayer(entitylivingbaseIn, p_177141_2_, p_177141_3_, partialTicks, p_177141_5_, p_177141_6_, p_177141_7_, scale, 3);
this.renderLayer(entitylivingbaseIn, p_177141_2_, p_177141_3_, partialTicks, p_177141_5_, p_177141_6_, p_177141_7_, scale, 2);
this.renderLayer(entitylivingbaseIn, p_177141_2_, p_177141_3_, partialTicks, p_177141_5_, p_177141_6_, p_177141_7_, scale, 1);
}
public boolean shouldCombineTextures() {
return false;
}
private void renderLayer(final EntityLivingBase entitylivingbaseIn, final float p_177182_2_, final float p_177182_3_, final float p_177182_4_, final float p_177182_5_, final float p_177182_6_, final float p_177182_7_, final float p_177182_8_, final int armorSlot) {
final ItemStack itemstack = this.getCurrentArmor(entitylivingbaseIn, armorSlot);
if (itemstack != null && itemstack.getItem() instanceof ItemArmor) {
final ItemArmor itemarmor = (ItemArmor) itemstack.getItem();
T t = this.func_177175_a(armorSlot);
t.setModelAttributes(this.renderer.getMainModel());
t.setLivingAnimations(entitylivingbaseIn, p_177182_2_, p_177182_3_, p_177182_4_);
if (Reflector.ForgeHooksClient.exists()) {
t = this.getArmorModelHook(entitylivingbaseIn, itemstack, armorSlot, t);
}
this.func_177179_a(t, armorSlot);
final boolean flag = this.isSlotForLeggings(armorSlot);
if (!Config.isCustomItems() || !CustomItems.bindCustomArmorTexture(itemstack, flag ? 2 : 1, null)) {
if (Reflector.ForgeHooksClient_getArmorTexture.exists()) {
this.renderer.bindTexture(this.getArmorResource(entitylivingbaseIn, itemstack, flag ? 2 : 1, null));
} else {
this.renderer.bindTexture(this.getArmorResource(itemarmor, flag));
}
}
if (Reflector.ForgeHooksClient_getArmorTexture.exists()) {
if (ReflectorForge.armorHasOverlay(itemarmor, itemstack)) {
final int j = itemarmor.getColor(itemstack);
final float f3 = (float) (j >> 16 & 255) / 255.0F;
final float f4 = (float) (j >> 8 & 255) / 255.0F;
final float f5 = (float) (j & 255) / 255.0F;
GlStateManager.color(this.colorR * f3, this.colorG * f4, this.colorB * f5, this.alpha);
t.render(entitylivingbaseIn, p_177182_2_, p_177182_3_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_);
if (!Config.isCustomItems() || !CustomItems.bindCustomArmorTexture(itemstack, flag ? 2 : 1, "overlay")) {
this.renderer.bindTexture(this.getArmorResource(entitylivingbaseIn, itemstack, flag ? 2 : 1, "overlay"));
}
}
GlStateManager.color(this.colorR, this.colorG, this.colorB, this.alpha);
t.render(entitylivingbaseIn, p_177182_2_, p_177182_3_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_);
if (!this.field_177193_i && itemstack.hasEffect() && (!Config.isCustomItems() || !CustomItems.renderCustomArmorEffect(entitylivingbaseIn, itemstack, t, p_177182_2_, p_177182_3_, p_177182_4_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_))) {
this.func_177183_a(entitylivingbaseIn, t, p_177182_2_, p_177182_3_, p_177182_4_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_);
}
return;
}
switch (itemarmor.getArmorMaterial()) {
case LEATHER:
final int i = itemarmor.getColor(itemstack);
final float f = (float) (i >> 16 & 255) / 255.0F;
final float f1 = (float) (i >> 8 & 255) / 255.0F;
final float f2 = (float) (i & 255) / 255.0F;
GlStateManager.color(this.colorR * f, this.colorG * f1, this.colorB * f2, this.alpha);
t.render(entitylivingbaseIn, p_177182_2_, p_177182_3_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_);
if (!Config.isCustomItems() || !CustomItems.bindCustomArmorTexture(itemstack, flag ? 2 : 1, "overlay")) {
this.renderer.bindTexture(this.getArmorResource(itemarmor, flag, "overlay"));
}
case CHAIN:
case IRON:
case GOLD:
case DIAMOND:
GlStateManager.color(this.colorR, this.colorG, this.colorB, this.alpha);
t.render(entitylivingbaseIn, p_177182_2_, p_177182_3_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_);
}
if (!this.field_177193_i && itemstack.isItemEnchanted() && (!Config.isCustomItems() || !CustomItems.renderCustomArmorEffect(entitylivingbaseIn, itemstack, t, p_177182_2_, p_177182_3_, p_177182_4_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_))) {
this.func_177183_a(entitylivingbaseIn, t, p_177182_2_, p_177182_3_, p_177182_4_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_);
}
}
}
public ItemStack getCurrentArmor(final EntityLivingBase entitylivingbaseIn, final int armorSlot) {
return entitylivingbaseIn.getCurrentArmor(armorSlot - 1);
}
public T func_177175_a(final int p_177175_1_) {
return this.isSlotForLeggings(p_177175_1_) ? this.field_177189_c : this.field_177186_d;
}
private boolean isSlotForLeggings(final int armorSlot) {
return armorSlot == 2;
}
private void func_177183_a(final EntityLivingBase entitylivingbaseIn, final T modelbaseIn, final float p_177183_3_, final float p_177183_4_, final float p_177183_5_, final float p_177183_6_, final float p_177183_7_, final float p_177183_8_, final float p_177183_9_) {
if (!Config.isShaders() || !Shaders.isShadowPass) {
final float f = (float) entitylivingbaseIn.ticksExisted + p_177183_5_;
this.renderer.bindTexture(ENCHANTED_ITEM_GLINT_RES);
if (Config.isShaders()) {
ShadersRender.renderEnchantedGlintBegin();
}
GlStateManager.enableBlend();
GlStateManager.depthFunc(514);
GlStateManager.depthMask(false);
final float f1 = 0.5F;
GlStateManager.color(f1, f1, f1, 1.0F);
for (int i = 0; i < 2; ++i) {
GlStateManager.disableLighting();
GlStateManager.blendFunc(768, 1);
final float f2 = 0.76F;
GlStateManager.color(0.5F * f2, 0.25F * f2, 0.8F * f2, 1.0F);
GlStateManager.matrixMode(5890);
GlStateManager.loadIdentity();
final float f3 = 0.33333334F;
GlStateManager.scale(f3, f3, f3);
GlStateManager.rotate(30.0F - (float) i * 60.0F, 0.0F, 0.0F, 1.0F);
GlStateManager.translate(0.0F, f * (0.001F + (float) i * 0.003F) * 20.0F, 0.0F);
GlStateManager.matrixMode(5888);
modelbaseIn.render(entitylivingbaseIn, p_177183_3_, p_177183_4_, p_177183_6_, p_177183_7_, p_177183_8_, p_177183_9_);
}
GlStateManager.matrixMode(5890);
GlStateManager.loadIdentity();
GlStateManager.matrixMode(5888);
GlStateManager.enableLighting();
GlStateManager.depthMask(true);
GlStateManager.depthFunc(515);
GlStateManager.disableBlend();
if (Config.isShaders()) {
ShadersRender.renderEnchantedGlintEnd();
}
}
}
private ResourceLocation getArmorResource(final ItemArmor p_177181_1_, final boolean p_177181_2_) {
return this.getArmorResource(p_177181_1_, p_177181_2_, null);
}
private ResourceLocation getArmorResource(final ItemArmor p_177178_1_, final boolean p_177178_2_, final String p_177178_3_) {
final String s = String.format("textures/models/armor/%s_layer_%d%s.png", p_177178_1_.getArmorMaterial().getName(), Integer.valueOf(p_177178_2_ ? 2 : 1), p_177178_3_ == null ? "" : String.format("_%s", p_177178_3_));
ResourceLocation resourcelocation = ARMOR_TEXTURE_RES_MAP.get(s);
if (resourcelocation == null) {
resourcelocation = new ResourceLocation(s);
ARMOR_TEXTURE_RES_MAP.put(s, resourcelocation);
}
return resourcelocation;
}
protected abstract void initArmor();
protected abstract void func_177179_a(T p_177179_1_, int p_177179_2_);
protected T getArmorModelHook(final EntityLivingBase p_getArmorModelHook_1_, final ItemStack p_getArmorModelHook_2_, final int p_getArmorModelHook_3_, final T p_getArmorModelHook_4_) {
return p_getArmorModelHook_4_;
}
public ResourceLocation getArmorResource(final Entity p_getArmorResource_1_, final ItemStack p_getArmorResource_2_, final int p_getArmorResource_3_, final String p_getArmorResource_4_) {
final ItemArmor itemarmor = (ItemArmor) p_getArmorResource_2_.getItem();
String s = itemarmor.getArmorMaterial().getName();
String s1 = "minecraft";
final int i = s.indexOf(58);
if (i != -1) {
s1 = s.substring(0, i);
s = s.substring(i + 1);
}
String s2 = String.format("%s:textures/models/armor/%s_layer_%d%s.png", s1, s, Integer.valueOf(this.isSlotForLeggings(p_getArmorResource_3_) ? 2 : 1), p_getArmorResource_4_ == null ? "" : String.format("_%s", p_getArmorResource_4_));
s2 = Reflector.callString(Reflector.ForgeHooksClient_getArmorTexture, p_getArmorResource_1_, p_getArmorResource_2_, s2, Integer.valueOf(p_getArmorResource_3_), p_getArmorResource_4_);
ResourceLocation resourcelocation = ARMOR_TEXTURE_RES_MAP.get(s2);
if (resourcelocation == null) {
resourcelocation = new ResourceLocation(s2);
ARMOR_TEXTURE_RES_MAP.put(s2, resourcelocation);
}
return resourcelocation;
}
}
|
zhouhaifeng/vpe
|
src/frr/pceplib/pcep_utils_logging.c
|
/*
* This file is part of the PCEPlib, a PCEP protocol library.
*
* Copyright (C) 2020 Volta Networks https://voltanet.io/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Author : <NAME> <<EMAIL>>
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdarg.h>
#include <stdio.h>
#include "pcep_utils_logging.h"
/* Forward declaration */
int pcep_stdout_logger(int priority, const char *format, va_list args);
static pcep_logger_func logger_func = pcep_stdout_logger;
static int logging_level_ = LOG_INFO;
void register_logger(pcep_logger_func logger)
{
logger_func = logger;
}
void set_logging_level(int level)
{
logging_level_ = level;
}
int get_logging_level()
{
return logging_level_;
}
void pcep_log(int priority, const char *format, ...)
{
va_list va;
va_start(va, format);
logger_func(priority, format, va);
va_end(va);
}
void pcep_log_hexbytes(int priority, const char *message, const uint8_t *bytes,
uint8_t bytes_len)
{
char byte_str[2048] = {0};
int i = 0;
snprintf(byte_str, 2048, "%s ", message);
for (; i < bytes_len; i++) {
snprintf(byte_str, 2048, "%02x ", bytes[i]);
}
snprintf(byte_str, 2048, "\n");
pcep_log(priority, "%s", byte_str);
}
/* Defined with a return type to match the FRR logging signature.
* Assuming glibc printf() is thread-safe. */
int pcep_stdout_logger(int priority, const char *format, va_list args)
{
if (priority <= logging_level_) {
vprintf(format, args);
printf("\n");
}
return 0;
}
|
Lowkhee/VeganOption
|
java/squeek/veganoption/integration/bop/BiomesOPlenty.java
|
<filename>java/squeek/veganoption/integration/bop/BiomesOPlenty.java
package squeek.veganoption.integration.bop;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import squeek.veganoption.content.ContentHelper;
import squeek.veganoption.integration.IntegratorBase;
public class BiomesOPlenty extends IntegratorBase
{
@Override
public void oredict()
{
OreDictionary.registerOre(ContentHelper.sunflowerSeedOreDict, new ItemStack(getItem("food"), 1, 3));
}
}
|
datamarts/prostore
|
dtm-jdbc-driver/src/main/java/ru/datamart/prostore/jdbc/core/SqlParser.java
|
/*
* Copyright © 2022 DATAMART LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.datamart.prostore.jdbc.core;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SqlParser {
private SqlParser() {
}
public static List<Query> parseSql(String query) throws SQLException {
int inParen = 0;
char[] aChars = query.toCharArray();
boolean whitespaceOnly = true;
List<Query> nativeQueries = null;
StringBuilder nativeSql = new StringBuilder();
int fragmentStart = 0;
if (query.isEmpty()) {
return Collections.singletonList(new Query(query, true));
}
int i = 0;
while (i < aChars.length) {
char aChar = aChars[i];
whitespaceOnly &= aChar == ';' || Character.isWhitespace(aChar);
switch (aChar) {
case '"':
i = parseDoubleQuotes(aChars, i);
break;
case '\'':
i = parseSingleQuotes(aChars, i);
break;
case '(':
++inParen;
break;
case ')':
--inParen;
break;
case ';':
whitespaceOnly = appendInParenCharsAndCheckWhitespace(inParen,
aChars, whitespaceOnly, nativeSql, fragmentStart, i);
fragmentStart = i + 1;
if (nativeQueries == null) {
nativeQueries = new ArrayList<>();
}
nativeQueries.add(new Query(nativeSql.toString(), false));
nativeSql.setLength(0);
break;
default:
break;
}
++i;
}
return getQueries(aChars, whitespaceOnly, nativeQueries, nativeSql, fragmentStart);
}
private static boolean appendInParenCharsAndCheckWhitespace(int inParen,
char[] aChars,
boolean whitespaceOnly,
StringBuilder nativeSql,
int fragmentStart,
int i) throws SQLException {
if (inParen == 0) {
if (!whitespaceOnly) {
nativeSql.append(aChars, fragmentStart, i - fragmentStart);
return true;
}
} else {
throw new SQLException(String.format("Invalid sql query %s", Arrays.toString(aChars)));
}
return false;
}
private static List<Query> getQueries(char[] aChars,
boolean whitespaceOnly,
List<Query> nativeQueries,
StringBuilder nativeSql,
int fragmentStart) {
if (fragmentStart < aChars.length && !whitespaceOnly) {
nativeSql.append(aChars, fragmentStart, aChars.length - fragmentStart);
}
if (nativeSql.length() == 0) {
return nativeQueries != null ? nativeQueries : Collections.emptyList();
} else {
return getQueriesIfNativeSqlNonEmpty(whitespaceOnly, nativeQueries, nativeSql);
}
}
private static List<Query> getQueriesIfNativeSqlNonEmpty(boolean whitespaceOnly,
List<Query> nativeQueries,
StringBuilder nativeSql) {
Query lastQuery = new Query(nativeSql.toString(), false);
if (nativeQueries == null) {
return Collections.singletonList(lastQuery);
} else {
if (!whitespaceOnly) {
nativeQueries.add(lastQuery);
}
return nativeQueries;
}
}
private static int parseSingleQuotes(char[] query, int offset) {
while (true) {
++offset;
if (offset >= query.length) {
break;
}
if (query[offset] == '\'') {
return offset;
}
}
return query.length;
}
private static int parseDoubleQuotes(char[] query, int offset) {
do {
++offset;
} while (offset < query.length && query[offset] != '"');
return offset;
}
}
|
monowar/mCerebrum-Library
|
system/src/main/java/org/md2k/mcerebrum/system/cerebralcortexwebapi/models/stream/DataDescriptor.java
|
<reponame>monowar/mCerebrum-Library
/*
* Copyright (c) 2018, The University of Memphis, MD2K Center of Excellence
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.md2k.mcerebrum.system.cerebralcortexwebapi.models.stream;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Provides a description for the data collected in the data stream.
*/
public class DataDescriptor {
/**
*<p>
* Serialized name: "type"
* Exposed to serialization.
* </p>
*/
@SerializedName("type")
@Expose
private String type;
/**
*<p>
* Serialized name: "unit"
* Exposed to serialization.
* </p>
*/
@SerializedName("unit")
@Expose
private String unit;
/**
* No arguments constructor for use in serialization
*/
public DataDescriptor() {}
/**
* Constructor
*
* @param unit Unit of this <code>DataDescriptor</code>.
* @param type Type of this <code>DataDescriptor</code>.
*/
public DataDescriptor(String type, String unit) {
super();
this.type = type;
this.unit = unit;
}
/**
* Returns the type of this <code>DataDescriptor</code>.
* @return The type of this <code>DataDescriptor</code>.
*/
public String getType() {
return type;
}
/**
* Sets the type of this <code>DataDescriptor</code>.
* @param type The type of this <code>DataDescriptor</code>.
*/
public void setType(String type) {
this.type = type;
}
/**
* Returns the unit of this <code>DataDescriptor</code>.
* @return The unit of this <code>DataDescriptor</code>.
*/
public String getUnit() {
return unit;
}
/**
* Sets the unit of this <code>DataDescriptor</code>.
* @param unit The unit of this <code>DataDescriptor</code>.
*/
public void setUnit(String unit) {
this.unit = unit;
}
}
|
alantao5056/USACO_Silver
|
2019/December/milkvisits/Milkvisits2.java
|
<reponame>alantao5056/USACO_Silver
import java.io.IOException;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Milkvisits2 {
private static int N;
private static int M;
private static String MILKTYPES;
private static LinkedList<Integer>[] connection;
private static int[] groups;
public static boolean ifMilkInPath(int start, int end, char milkType, String MILKTYPES) {
if (groups[start] == groups[end]) {
if (MILKTYPES.charAt(start) == milkType) {
return true;
}
return false;
}
return true;
}
public static void main(String[] args) throws IOException{
String fileInput = new String(Files.readAllBytes(Paths.get("milkvisits.in")));
StringTokenizer st = new StringTokenizer(fileInput);
PrintWriter pr = new PrintWriter(new FileWriter("milkvisits.out"));
final int N = Integer.parseInt(st.nextToken());
final int M = Integer.parseInt(st.nextToken());
final String MILKTYPES = ' ' + st.nextToken();
// initilizing connection
connection = new LinkedList[N + 1];
int x, y;
for (int i = 0; i < N - 1; i++) {
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
if (connection[x] == null) {
connection[x] = new LinkedList<Integer>();
}
if (connection[y] == null) {
connection[y] = new LinkedList<Integer>();
}
connection[x].add(y);
connection[y].add(x);
}
// grouping
groups = new int[N + 1];
int curGroup = 1;
for (int i = 1; i < N + 1; i++) {
if (groups[i] == 0) {
Queue<Integer> q = new LinkedList<>();
groups[i] = curGroup;
q.add(i);
// bfs this area
while (!q.isEmpty()) {
int cur = q.poll();
char curMilkType = MILKTYPES.charAt(cur);
for (int neighbor : connection[cur]) {
if (MILKTYPES.charAt(neighbor) == curMilkType && groups[neighbor] == 0) {
// in the same group
groups[neighbor] = curGroup;
q.add(neighbor);
}
}
}
curGroup++;
}
}
int a, b;
char c;
for (int i = 0; i < M; i++) {
a = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
c = st.nextToken().charAt(0);
pr.print(ifMilkInPath(a, b, c, MILKTYPES) ? '1' : '0');
}
pr.println();
pr.close();
}
}
|
asaaki/ArangoDB
|
js/common/tests/shell-general-graph.js
|
<reponame>asaaki/ArangoDB
/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true */
/*global require, assertEqual, assertTrue, assertFalse, fail */
////////////////////////////////////////////////////////////////////////////////
/// @brief test the general-graph class
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// 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 holder is triAGENS GmbH, Cologne, Germany
///
/// @author <NAME>, <NAME>
/// @author Copyright 2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
var jsunity = require("jsunity");
var arangodb = require("org/arangodb");
var db = arangodb.db;
var graph = require("org/arangodb/general-graph");
var ERRORS = arangodb.errors;
var _ = require("underscore");
// -----------------------------------------------------------------------------
// --SECTION-- graph module
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: general-graph Creation and edge definition
////////////////////////////////////////////////////////////////////////////////
function GeneralGraphCreationSuite() {
var rn = "UnitTestRelationName";
var rn1 = "UnitTestRelationName1";
var vn1 = "UnitTestVerticies1";
var vn2 = "UnitTestVerticies2";
var vn3 = "UnitTestVerticies3";
var vn4 = "UnitTestVerticies4";
var gn = "UnitTestGraph";
var edgeDef = graph._edgeDefinitions(
graph._undirectedRelation(rn, vn1),
graph._directedRelation(rn1,
[vn1, vn2], [vn3, vn4]
)
);
var gN1 = "UnitTestEdgeDefDeleteGraph1",
gN2 = "UnitTestEdgeDefDeleteGraph2",
ec1 = "UnitTestEdgeDefDeleteEdgeCol1",
ec2 = "UnitTestEdgeDefDeleteEdgeCol2",
ec3 = "UnitTestEdgeDefDeleteEdgeCol3",
vc1 = "UnitTestEdgeDefDeleteVertexCol1",
vc2 = "UnitTestEdgeDefDeleteVertexCol2",
vc3 = "UnitTestEdgeDefDeleteVertexCol3",
vc4 = "UnitTestEdgeDefDeleteVertexCol4",
vc5 = "UnitTestEdgeDefDeleteVertexCol5",
vc6 = "UnitTestEdgeDefDeleteVertexCol6";
return {
setUp: function() {
try {
graph._drop(gN1, true);
} catch(ignore) {
}
try {
graph._drop(gN2, true);
} catch(ignore) {
}
},
tearDown: function() {
db._drop(ec1);
db._drop(ec2);
db._drop(ec3);
db._drop(vc1);
db._drop(vc2);
db._drop(vc3);
db._drop(vc4);
db._drop(vc5);
db._drop(vc6);
try {
graph._drop(gN1, true);
} catch(ignore) {
}
try {
graph._drop(gN2, true);
} catch(ignore) {
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Graph Creation
////////////////////////////////////////////////////////////////////////////////
test_undirectedRelation : function () {
var r = graph._undirectedRelation(rn, [vn1, vn2]);
assertEqual(r, {
collection: rn,
from: [vn1, vn2],
to: [vn1, vn2]
});
},
test_undirectedRelationWithSingleCollection : function () {
var r = graph._undirectedRelation(rn, vn1);
assertEqual(r, {
collection: rn,
from: [vn1],
to: [vn1]
});
},
test_undirectedRelationWithMissingName : function () {
try {
graph._undirectedRelation("", [vn1, vn2]);
fail();
}
catch (err) {
assertEqual(err.errorMessage, "Invalid parameter type. arg1 must not be empty");
}
},
test_undirectedRelationWithTooFewArgs : function () {
try {
graph._undirectedRelation([vn1, vn2]);
fail();
}
catch (err) {
assertEqual(err.errorMessage, "Invalid number of arguments. Expected: 2");
}
},
test_undirectedRelationWithInvalidSecondArg : function () {
try {
var param = {};
param[vn1] = vn2;
graph._undirectedRelation(rn, param);
fail();
}
catch (err) {
assertEqual(err.errorMessage, "Invalid parameter type. arg2 must not be empty");
}
},
test_collectionSorting: function() {
var g = graph._create(
gn,
graph._edgeDefinitions(
graph._directedRelation(rn1, [vn2, vn1], [vn4, vn3])
)
);
assertEqual([vn1, vn2], g.__edgeDefinitions[0].from);
assertEqual([vn3, vn4], g.__edgeDefinitions[0].to);
},
test_directedRelation : function () {
var r = graph._directedRelation(rn,
[vn1, vn2], [vn3, vn4]);
assertEqual(r, {
collection: rn,
from: [vn1, vn2],
to: [vn3, vn4]
});
},
test_directedRelationWithMissingName : function () {
try {
graph._directedRelation("",
[vn1, vn2], [vn3, vn4]);
fail();
}
catch (err) {
assertEqual(err.errorMessage, "Invalid parameter type. arg1 must be non empty string");
}
},
test_directedRelationWithTooFewArgs : function () {
try {
graph._directedRelation([vn1, vn2], [vn3, vn4]);
fail();
}
catch (err) {
assertEqual(err.errorMessage, "Invalid number of arguments. Expected: 3");
}
},
test_directedRelationWithInvalidSecondArg : function () {
try {
var param = {};
param[vn1] = vn2;
graph._directedRelation(rn, param, vn3);
fail();
}
catch (err) {
assertEqual(err.errorMessage, "Invalid parameter type. arg2 must be non empty string or array");
}
},
test_directedRelationWithInvalidThirdArg : function () {
try {
var param = {};
param[vn1] = vn2;
graph._directedRelation(rn, vn3, param);
fail();
}
catch (err) {
assertEqual(err.errorMessage, "Invalid parameter type. arg3 must be non empty string or array");
}
},
testEdgeDefinitions : function () {
//with empty args
assertEqual(graph._edgeDefinitions(), []);
//with args
assertEqual(graph._edgeDefinitions(
graph._undirectedRelation(rn, vn1),
graph._directedRelation(rn1,
[vn1, vn2], [vn3, vn4])
), [
{
collection: rn,
from: [vn1],
to: [vn1]
},
{
collection: rn1,
from: [vn1, vn2],
to: [vn3, vn4]
}
]);
},
testExtendEdgeDefinitions : function () {
//with empty args
assertEqual(graph._edgeDefinitions(), []);
//with args
var ed =graph._edgeDefinitions(
graph._undirectedRelation("relationName", "vertexC1"),
graph._directedRelation("relationName",
["vertexC1", "vertexC2"], ["vertexC3", "vertexC4"])
);
graph._extendEdgeDefinitions(ed,
graph._undirectedRelation("relationName", "vertexC1")
);
assertEqual(ed, [
{
collection: "relationName",
from: ["vertexC1"],
to: ["vertexC1"]
},
{
collection: "relationName",
from: ["vertexC1", "vertexC2"],
to: ["vertexC3", "vertexC4"]
},
{
collection: "relationName",
from: ["vertexC1"],
to: ["vertexC1"]
}
]);
},
test_create : function () {
if (db._collection("_graphs").exists(gn)) {
db._collection("_graphs").remove(gn);
}
var a = graph._create(
gn,
graph._edgeDefinitions(
graph._undirectedRelation(rn, vn1),
graph._directedRelation(rn1, [vn1, vn2], [vn3, vn4])
)
);
assertTrue(a.__vertexCollections.hasOwnProperty(vn1));
assertTrue(a.__vertexCollections.hasOwnProperty(vn2));
assertTrue(a.__vertexCollections.hasOwnProperty(vn3));
assertTrue(a.__vertexCollections.hasOwnProperty(vn4));
assertTrue(a.__edgeCollections.hasOwnProperty(rn));
assertTrue(a.__edgeCollections.hasOwnProperty(rn1));
assertEqual(a.__edgeDefinitions, [
{
"collection" : rn,
"from" : [
vn1
],
"to" : [
vn1
]
},
{
"collection" : rn1,
"from" : [
vn1,
vn2
],
"to" : [
vn3,
vn4
]
}
]
);
},
test_create_WithOut_EdgeDefiniton : function () {
if (db._collection("_graphs").exists(gn)) {
db._collection("_graphs").remove(gn);
}
var g = graph._create(
gn
);
assertEqual(g.__edgeDefinitions, []);
},
test_create_WithOut_Name : function () {
if (db._collection("_graphs").exists(gn)) {
db._collection("_graphs").remove(gn);
}
try {
graph._create(
"",
graph._edgeDefinitions(
graph._undirectedRelation("relationName", "vertexC1"),
graph._directedRelation("relationName2",
["vertexC1", "vertexC2"], ["vertexC3", "vertexC4"]
)
)
);
fail();
} catch (err) {
assertEqual(err.errorMessage, ERRORS.ERROR_GRAPH_CREATE_MISSING_NAME.message);
}
},
test_create_With_Already_Existing_Graph : function () {
if (db._collection("_graphs").exists(gn)) {
db._collection("_graphs").remove(gn);
}
graph._create(gn, edgeDef);
try {
graph._create(gn, edgeDef);
} catch (err) {
assertEqual(err.errorNum, ERRORS.ERROR_GRAPH_DUPLICATE.code);
assertEqual(err.errorMessage, ERRORS.ERROR_GRAPH_DUPLICATE.message);
}
},
test_get_graph : function () {
if (db._collection("_graphs").exists(gn)) {
db._collection("_graphs").remove(gn);
}
graph._create(gn, edgeDef);
var a = graph._graph(gn);
assertTrue(a.__vertexCollections.hasOwnProperty(vn1));
assertTrue(a.__vertexCollections.hasOwnProperty(vn2));
assertTrue(a.__vertexCollections.hasOwnProperty(vn3));
assertTrue(a.__vertexCollections.hasOwnProperty(vn4));
assertTrue(a.__edgeCollections.hasOwnProperty(rn));
assertTrue(a.__edgeCollections.hasOwnProperty(rn1));
assertEqual(a.__edgeDefinitions, [
{
"collection" : rn,
"from" : [
vn1
],
"to" : [
vn1
]
},
{
"collection" : rn1,
"from" : [
vn1,
vn2
],
"to" : [
vn3,
vn4
]
}
]
);
},
test_get_graph_without_hit : function () {
try {
graph._graph(gn + "UnknownExtension");
fail();
} catch (e) {
assertEqual(e.errorNum, ERRORS.ERROR_GRAPH_NOT_FOUND.code);
assertEqual(e.errorMessage, ERRORS.ERROR_GRAPH_NOT_FOUND.message);
}
},
test_creationOfGraphShouldNotAffectCollections: function() {
if(graph._exists(gn)) {
graph._drop(gn, true);
}
var edgeDef2 = [graph._directedRelation(rn, vn1, vn2)];
var g = graph._create(gn, edgeDef2);
var v1 = g[vn1].save({_key: "1"})._id;
var v2 = g[vn2].save({_key: "2"})._id;
var v3 = g[vn1].save({_key: "3"})._id;
g[rn].save(v1, v2, {});
assertEqual(g[vn1].count(), 2);
assertEqual(g[vn2].count(), 1);
assertEqual(g[rn].count(), 1);
try {
g[rn].save(v2, v3, {});
fail();
} catch (e) {
// This should create an error
assertEqual(g[rn].count(), 1);
}
try {
db[rn].save(v2, v3, {});
} catch (e) {
// This should not create an error
fail();
}
assertEqual(g[rn].count(), 2);
db[vn2].remove(v2);
// This should not remove edges
assertEqual(g[rn].count(), 2);
g[vn1].remove(v1);
// This should remove edges
assertEqual(g[rn].count(), 1);
graph._drop(gn, true);
},
test_deleteEdgeDefinitionFromExistingGraph1: function() {
var dr1 = graph._directedRelation(ec1, [vc1], [vc1, vc2]),
g1 = graph._create(gN1, [dr1]);
try {
g1._deleteEdgeDefinition(ec1);
} catch (e) {
assertEqual(
e.errorMessage,
arangodb.errors.ERROR_GRAPH_EDGE_COLLECTION_NOT_USED.message
);
}
},
test_deleteEdgeDefinitionFromExistingGraph2: function() {
var dr1 = graph._directedRelation(ec1, [vc1], [vc1, vc2]),
dr2 = graph._directedRelation(ec2, [vc3], [vc4, vc5]),
dr3 = graph._directedRelation(ec3, [vc4], [vc5]),
g1 = graph._create(gN1, [dr1, dr2, dr3]);
assertEqual([dr1, dr2, dr3], g1.__edgeDefinitions);
g1._deleteEdgeDefinition(ec1);
assertEqual([dr2, dr3], g1.__edgeDefinitions);
assertEqual([vc1, vc2], g1._orphanCollections());
assertTrue(db._collection(ec1) !== null);
g1._deleteEdgeDefinition(ec2);
assertEqual([dr3], g1.__edgeDefinitions);
assertEqual([vc1, vc2, vc3], g1._orphanCollections());
assertTrue(db._collection(ec2) !== null);
},
test_deleteEdgeDefinitionFromExistingGraphAndDropIt: function() {
var dr1 = graph._directedRelation(ec1, [vc1], [vc1, vc2]),
dr2 = graph._directedRelation(ec2, [vc3], [vc4, vc5]),
dr3 = graph._directedRelation(ec3, [vc4], [vc5]),
g1 = graph._create(gN1, [dr1, dr2, dr3]);
assertEqual([dr1, dr2, dr3], g1.__edgeDefinitions);
g1._deleteEdgeDefinition(ec1, true);
assertEqual([dr2, dr3], g1.__edgeDefinitions);
assertEqual([vc1, vc2], g1._orphanCollections());
assertTrue(db._collection(ec1) === null);
g1._deleteEdgeDefinition(ec2, true);
assertEqual([dr3], g1.__edgeDefinitions);
assertEqual([vc1, vc2, vc3], g1._orphanCollections());
assertTrue(db._collection(ec2) === null);
},
test_extendEdgeDefinitionFromExistingGraph1: function() {
try {
graph._drop(gN1, true);
} catch(ignore) {
}
var dr1 = graph._directedRelation(ec1, [vc1], [vc2]),
dr2 = graph._directedRelation(ec1, [vc2], [vc3]),
g1 = graph._create(gN1, [dr1]);
try {
g1._extendEdgeDefinitions(dr2);
} catch (e) {
assertEqual(
e.errorMessage,
arangodb.errors.ERROR_GRAPH_COLLECTION_MULTI_USE.message
);
}
try {
graph._drop(gN1, true);
} catch(ignore) {
}
},
test_extendEdgeDefinitionFromExistingGraph2: function() {
var dr1 = graph._directedRelation(ec1, [vc1], [vc1, vc2]),
dr2 = graph._directedRelation(ec2, [vc3], [vc4, vc5]),
dr2a = graph._directedRelation(ec2, [vc3], [vc4]),
g1 = graph._create(gN1, [dr1]),
g2 = graph._create(gN2, [dr2]);
try {
g1._extendEdgeDefinitions(dr2a);
} catch (e) {
assertEqual(
e.errorMessage,
ec2 + " " + arangodb.errors.ERROR_GRAPH_COLLECTION_USE_IN_MULTI_GRAPHS.message
);
}
try {
graph._drop(gN1, true);
} catch(ignore) {
}
try {
graph._drop(gN2, true);
} catch(ignore) {
}
},
test_extendEdgeDefinitionFromExistingGraph3: function() {
try {
graph._drop(gN1, true);
} catch(ignore) {
}
try {
graph._drop(gN2, true);
} catch(ignore) {
}
var dr1 = graph._directedRelation(ec1, [vc1], [vc1, vc2]),
dr2 = graph._directedRelation(ec2, [vc3], [vc4, vc5]),
dr3 = graph._directedRelation(ec3, [vc3], [vc4]),
g1 = graph._create(gN1, [dr1]),
g2 = graph._create(gN2, [dr2]);
assertEqual([dr1], g1.__edgeDefinitions);
g1._addVertexCollection(vc3);
assertEqual([vc3], g1._orphanCollections());
g1._extendEdgeDefinitions(dr3);
assertEqual([dr1, dr3], g1.__edgeDefinitions);
assertEqual([], g1._orphanCollections());
g1._extendEdgeDefinitions(dr2);
assertEqual([dr1, dr3, dr2], g1.__edgeDefinitions);
},
test_extendEdgeDefinitionFromExistingGraph4: function() {
try {
graph._drop(gN1, true);
} catch(ignore) {
}
try {
graph._drop(gN2, true);
} catch(ignore) {
}
var dr1 = graph._directedRelation(ec1, [vc1], [vc1, vc2]),
dr2 = graph._directedRelation(ec2, [vc4, vc3, vc1, vc2], [vc4, vc3, vc1, vc2]),
g1 = graph._create(gN1, [dr1]);
g1._extendEdgeDefinitions(dr2);
assertEqual([dr1, dr2], g1.__edgeDefinitions);
var edgeDefinition = _.findWhere(g1.__edgeDefinitions, {collection: ec2});
assertEqual(edgeDefinition.from, [vc1, vc2, vc3, vc4]);
assertEqual(edgeDefinition.to, [vc1, vc2, vc3, vc4]);
},
test_editEdgeDefinitionFromExistingGraph1: function() {
var dr1 = graph._directedRelation(ec1, [vc1], [vc1, vc2]),
dr2 = graph._directedRelation(ec2, [vc3], [vc4, vc5]),
g1 = graph._create(gN1, [dr1]);
try {
g1._editEdgeDefinitions(dr2);
} catch (e) {
assertEqual(
e.errorMessage,
arangodb.errors.ERROR_GRAPH_EDGE_COLLECTION_NOT_USED.message
);
}
},
test_editEdgeDefinitionFromExistingGraph2: function() {
var dr1 = graph._directedRelation(ec1, [vc1, vc2], [vc3, vc4]),
dr2 = graph._directedRelation(ec2, [vc1], [vc4]),
dr3 = graph._directedRelation(ec1, [vc5], [vc5]),
g1 = graph._create(gN1, [dr1, dr2]),
g2 = graph._create(gN2, [dr1]);
g1._editEdgeDefinitions(dr3);
assertEqual([dr3, dr2], g1.__edgeDefinitions);
assertEqual([dr3], g2.__edgeDefinitions);
g2 = graph._graph(gN2);
assertEqual(g1._orphanCollections().sort(), [vc2, vc3].sort());
assertEqual(g2._orphanCollections().sort(), [vc1, vc2, vc3, vc4].sort());
},
test_editEdgeDefinitionFromExistingGraph3: function() {
var dr1 = graph._directedRelation(ec1, [vc1], [vc1, vc2]),
dr2 = graph._directedRelation(ec1, [vc3], [vc4, vc5]),
dr3 = graph._directedRelation(ec2, [vc2], [vc2, vc3]),
g1 = graph._create(gN1, [dr1, dr3]),
g2 = graph._create(gN2, [dr1]);
g1._addVertexCollection(vc4);
g2._addVertexCollection(vc5);
g2._addVertexCollection(vc6);
g1._editEdgeDefinitions(dr2, true);
assertEqual([dr2, dr3], g1.__edgeDefinitions);
assertEqual([dr2], g2.__edgeDefinitions);
g2 = graph._graph(gN2);
assertEqual([vc1], g1._orphanCollections());
assertEqual(g2._orphanCollections().sort(), [vc1, vc2, vc6].sort());
try {
graph._drop(gN1, true);
} catch(ignore) {
}
try {
graph._drop(gN2, true);
} catch(ignore) {
}
}
};
}
// -----------------------------------------------------------------------------
// --SECTION-- Simple Queries
// -----------------------------------------------------------------------------
function GeneralGraphAQLQueriesSuite() {
// Definition of names
var graphName = "UnitTestsGraph";
var included = "UnitTestIncluded";
var excluded = "UnitTestExcluded";
var v1 = "UnitTestV1";
var v2 = "UnitTestV2";
var v3 = "UnitTestV3";
var dropInclExcl = function() {
if (graph._exists(graphName)) {
graph._drop(graphName, true);
}
};
var e1, e2, e3;
var createInclExcl = function() {
dropInclExcl();
var inc = graph._directedRelation(
included, [v1], [v1, v2]
);
var exc = graph._directedRelation(
excluded, [v1], [v3]
);
var g = graph._create(graphName, [inc, exc]);
g[v1].save({_key: "1"});
g[v1].save({_key: "2"});
g[v2].save({_key: "1"});
g[v3].save({_key: "1"});
e1 = g[included].save(
v1 + "/1",
v2 + "/1",
{
_key: "e1",
val: true
}
)._id;
e2 = g[included].save(
v1 + "/2",
v1 + "/1",
{
_key: "e2",
val: false
}
)._id;
e3 = g[excluded].save(
v1 + "/1",
v3 + "/1",
{
_key: "e3",
val: false
}
)._id;
return g;
};
var findIdInResult = function(result, id) {
return _.some(result, function(i) {
return i._id === id;
});
};
// The testee graph object
var g;
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief setUp: query creation for edges and vertices
////////////////////////////////////////////////////////////////////////////////
setUp: function() {
g = createInclExcl();
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: query creation for edges and vertices
////////////////////////////////////////////////////////////////////////////////
tearDown: function() {
dropInclExcl();
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: restrict construct on edges
////////////////////////////////////////////////////////////////////////////////
test_restrictOnEdges: function() {
var query = g._edges().restrict(included);
assertEqual(query.printQuery(), "FOR edges_0 IN GRAPH_EDGES("
+ '@graphName,{},@options_0)');
var bindVars = query.bindVars;
assertEqual(bindVars.graphName, graphName);
assertEqual(bindVars
.options_0
.edgeCollectionRestriction, [included]);
assertEqual(bindVars
.options_0
.direction, "outbound"
);
var result = query.toArray();
assertEqual(result.length, 2);
assertTrue(findIdInResult(result, e1), "Did not include e1");
assertTrue(findIdInResult(result, e2), "Did not include e2");
assertFalse(findIdInResult(result, e3), "e3 is not excluded");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: query creation for Vertices
////////////////////////////////////////////////////////////////////////////////
test_vertices: function() {
var query = g._vertices(v1 + "/1");
assertEqual(query.printQuery(), 'FOR vertices_0 IN GRAPH_VERTICES('
+ '@graphName,@vertexExample_0,@options_0)');
var bindVars = query.bindVars;
assertEqual(bindVars.graphName, graphName);
assertEqual(bindVars.vertexExample_0, {_id: v1 + "/1"});
var result = query.toArray();
assertEqual(result.length, 1);
assertTrue(findIdInResult(result, v1 + "/1"), "Did not include " + v1 + "/1");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: restrict error handling
////////////////////////////////////////////////////////////////////////////////
test_restrictErrorHandlingSingle: function() {
try {
g._edges(v1 + "/1").restrict([included, "unknown"]);
fail();
} catch (err) {
assertEqual(err.errorNum, ERRORS.ERROR_BAD_PARAMETER.code);
assertEqual(err.errorMessage, "edge collections: unknown are not known to the graph");
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: restrict error handling on multiple failures
////////////////////////////////////////////////////////////////////////////////
test_restrictErrorHandlingMultiple: function() {
try {
g._edges(v1 + "/1").restrict(["failed", included, "unknown", "foxxle"]);
fail();
} catch (err) {
assertEqual(err.errorNum, ERRORS.ERROR_BAD_PARAMETER.code);
assertEqual(err.errorMessage,
"edge collections: failed and unknown and foxxle are not known to the graph");
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: filter construct on Edges
////////////////////////////////////////////////////////////////////////////////
test_filterOnEdges: function() {
var query = g._edges().filter({val: true});
assertEqual(query.printQuery(), "FOR edges_0 IN GRAPH_EDGES("
+ '@graphName,{},@options_0) '
+ 'FILTER MATCHES(edges_0,[{"val":true}])');
var bindVars = query.bindVars;
assertEqual(bindVars.graphName, graphName);
assertEqual(bindVars.options_0, {
direction: "outbound",
edgeExamples: [{}]
});
var result = query.toArray();
assertEqual(result.length, 1);
assertTrue(findIdInResult(result, e1), "Did not include e1");
assertFalse(findIdInResult(result, e2), "e2 is not excluded");
assertFalse(findIdInResult(result, e3), "e3 is not excluded");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: counting of query results
////////////////////////////////////////////////////////////////////////////////
//
test_queryCount: function() {
var query = g._edges();
assertEqual(query.count(), 3);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Cursor iteration
////////////////////////////////////////////////////////////////////////////////
test_cursorIteration: function() {
var query = g._edges();
var list = [e1, e2, e3];
var next;
assertTrue(query.hasNext());
next = query.next();
list = _.without(list, next._id);
assertEqual(list.length, 2);
assertTrue(query.hasNext());
next = query.next();
list = _.without(list, next._id);
assertEqual(list.length, 1);
assertTrue(query.hasNext());
next = query.next();
list = _.without(list, next._id);
assertEqual(list.length, 0);
assertFalse(query.hasNext());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Cursor recreation after iteration
////////////////////////////////////////////////////////////////////////////////
test_cursorIterationAndRecreation: function() {
var query = g._edges();
var list = [e1, e2, e3];
var next;
assertTrue(query.hasNext());
next = query.next();
list = _.without(list, next._id);
assertEqual(list.length, 2);
assertTrue(query.hasNext());
next = query.next();
list = _.without(list, next._id);
assertEqual(list.length, 1);
assertTrue(query.hasNext());
next = query.next();
list = _.without(list, next._id);
assertEqual(list.length, 0);
assertFalse(query.hasNext());
query = query.filter({val: true});
list = [e1];
assertTrue(query.hasNext());
next = query.next();
list = _.without(list, next._id);
assertEqual(list.length, 0);
assertFalse(query.hasNext());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Is cursor recreated after counting of query results and appending filter
////////////////////////////////////////////////////////////////////////////////
test_cursorRecreationAfterCount: function() {
var query = g._edges();
assertEqual(query.count(), 3);
query = query.filter({val: true});
assertEqual(query.count(), 1);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Is cursor recreated after to array of query results and appending filter
////////////////////////////////////////////////////////////////////////////////
test_cursorRecreationAfterToArray: function() {
var query = g._edges();
var result = query.toArray();
assertTrue(findIdInResult(result, e1), "Did not include e1");
assertTrue(findIdInResult(result, e2), "Did not include e2");
assertTrue(findIdInResult(result, e3), "Did not include e3");
query = query.filter({val: true});
result = query.toArray();
assertTrue(findIdInResult(result, e1), "Did not include e1");
assertFalse(findIdInResult(result, e2), "e2 is not excluded");
assertFalse(findIdInResult(result, e3), "e3 is not excluded");
}
};
}
function ChainedFluentAQLResultsSuite() {
var gn = "UnitTestGraph";
var user = "UnitTestUsers";
var product = "UnitTestProducts";
var isFriend = "UnitTestIsFriend";
var hasBought = "UnitTestHasBought";
var uaName = "Alice";
var ubName = "Bob";
var ucName = "Charly";
var udName = "Diana";
var p1Name = "HiFi";
var p2Name = "Shirt";
var p3Name = "TV";
var pTypeElec = "Electro";
var pTypeCloth = "Cloth";
var ud1 = 2000;
var ud2 = 2001;
var ud3 = 2002;
var ud4 = 2003;
var d1 = 2004;
var d2 = 2005;
var d3 = 2006;
var d4 = 2007;
var d5 = 2008;
var g;
var edgeDef = [];
edgeDef.push(graph._undirectedRelation(isFriend, user));
edgeDef.push(graph._directedRelation(hasBought, user, product));
var findBoughts = function(result, list) {
var boughts = _.sortBy(
_.filter(result, function(e) {
return e._id.split("/")[0] === hasBought;
}),
"date"
);
assertEqual(list.length, boughts.length, "Did not return all expected boughts");
_.each(list.sort(), function(v, i) {
assertEqual(boughts[i].date, v);
});
};
var findFriends = function(result, list) {
var friends = _.sortBy(
_.filter(result, function(e) {
return e._id.split("/")[0] === isFriend;
}),
"since"
);
assertEqual(list.length, friends.length, "Did not return all expected friendships");
_.each(list.sort(), function(v, i) {
assertEqual(friends[i].since, v);
});
};
var dropData = function() {
try {
graph._drop(gn, true);
} catch(ignore) {
}
};
var createTestData = function() {
dropData();
g = graph._create(gn, edgeDef);
var ua = g[user].save({name: uaName})._id;
var ub = g[user].save({name: ubName})._id;
var uc = g[user].save({name: ucName})._id;
var ud = g[user].save({name: udName})._id;
var p1 = g[product].save({name: p1Name, type: pTypeElec})._id;
var p2 = g[product].save({name: p2Name, type: pTypeCloth})._id;
var p3 = g[product].save({name: p3Name, type: pTypeElec})._id;
g[isFriend].save(ua, ub, {
since: ud1
});
g[isFriend].save(ua, uc, {
since: ud2
});
g[isFriend].save(ub, ud, {
since: ud3
});
g[isFriend].save(uc, ud, {
since: ud4
});
g[hasBought].save(ua, p1, {
date: d1
});
g[hasBought].save(ub, p1, {
date: d2
});
g[hasBought].save(ub, p3, {
date: d3
});
g[hasBought].save(ud, p1, {
date: d4
});
g[hasBought].save(ud, p2, {
date: d5
});
};
var plainVertexQueryStmt = function(depth) {
return "FOR vertices_" + depth + " IN "
+ "GRAPH_VERTICES("
+ "@graphName,"
+ "@vertexExample_" + depth + ","
+ "@options_" + depth + ")";
};
var plainNeighborQueryStmt = function(depth, vdepth) {
return "FOR neighbors_" + depth + " IN "
+ "GRAPH_NEIGHBORS("
+ "@graphName,"
+ "vertices_" + vdepth + ","
+ "@options_" + depth + ")";
};
var vertexFilterStmt = function(direction, eDepth, vDepth) {
switch(direction) {
case "both":
return "FILTER edges_"
+ eDepth
+ "._from == vertices_"
+ vDepth
+ "._id || edges_"
+ eDepth
+ "._to == vertices_"
+ vDepth
+ "._id";
case "from":
return "FILTER edges_"
+ eDepth
+ "._from == vertices_"
+ vDepth
+ "._id";
case "to":
return "FILTER edges_"
+ eDepth
+ "._to == vertices_"
+ vDepth
+ "._id";
default:
fail("Helper function does not know direction:" + direction);
}
};
var plainEdgesQueryStmt = function(depth, vDepth, type) {
if (!type) {
type = "vertices";
}
var q = "FOR edges_" + depth + " IN "
+ "GRAPH_EDGES("
+ "@graphName,";
if(vDepth > -1) {
q += type + "_" + vDepth;
if (type === "neighbors") {
q += ".vertex";
}
q += ",";
} else {
q += "{},";
}
q += "@options_" + depth + ")";
return q;
};
return {
setUp: createTestData,
tearDown: dropData,
test_getAllVerticiesResultingAQL: function() {
var query = g._vertices();
var stmt = query.printQuery();
assertEqual(stmt, plainVertexQueryStmt(0));
assertEqual(query.bindVars.vertexExample_0, {});
assertEqual(query.bindVars.options_0, {});
},
test_getAllVerticies: function() {
var result = g._vertices().toArray();
assertEqual(result.length, 7);
var sorted = _.sortBy(result, "name");
assertEqual(sorted[0].name, uaName);
assertEqual(sorted[1].name, ubName);
assertEqual(sorted[2].name, ucName);
assertEqual(sorted[3].name, udName);
assertEqual(sorted[4].name, p1Name);
assertEqual(sorted[5].name, p2Name);
assertEqual(sorted[6].name, p3Name);
},
test_getVertexByIdResultingAQL: function() {
var a_id = g[user].firstExample({name: uaName})._id;
var query = g._vertices(a_id);
var stmt = query.printQuery();
assertEqual(stmt, plainVertexQueryStmt(0));
assertEqual(query.bindVars.vertexExample_0, {_id: a_id});
assertEqual(query.bindVars.options_0, {});
},
test_getVertexById: function() {
var a_id = g[user].firstExample({name: uaName})._id;
var result = g._vertices(a_id).toArray();
assertEqual(result.length, 1);
assertEqual(result[0].name, uaName);
},
test_getVerticesByIdResultingAQL: function() {
var a_id = g[user].firstExample({name: uaName})._id;
var b_id = g[user].firstExample({name: ubName})._id;
var query = g._vertices([a_id, b_id]);
var stmt = query.printQuery();
assertEqual(stmt, plainVertexQueryStmt(0));
assertEqual(query.bindVars.vertexExample_0, [{_id: a_id}, {_id: b_id}]);
assertEqual(query.bindVars.options_0, {});
},
test_getVerticiesById: function() {
var a_id = g[user].firstExample({name: uaName})._id;
var b_id = g[user].firstExample({name: ubName})._id;
var result = g._vertices([a_id, b_id]).toArray();
assertEqual(result.length, 2);
var sorted = _.sortBy(result, "name");
assertEqual(sorted[0].name, uaName);
assertEqual(sorted[1].name, ubName);
},
test_getVertexByExampleResultingAQL: function() {
var query = g._vertices({
name: uaName
});
var stmt = query.printQuery();
assertEqual(stmt, plainVertexQueryStmt(0));
assertEqual(query.bindVars.vertexExample_0, {name: uaName});
assertEqual(query.bindVars.options_0, {});
},
test_getVertexByExample: function() {
var result = g._vertices({
name: uaName
}).toArray();
assertEqual(result.length, 1);
assertEqual(result[0].name, uaName);
},
test_getVerticiesByExampleResultingAQL: function() {
var query = g._vertices([{
name: uaName
},{
name: p1Name
}]);
var stmt = query.printQuery();
assertEqual(stmt, plainVertexQueryStmt(0));
assertEqual(query.bindVars.vertexExample_0, [
{name: uaName},
{name: p1Name}
]);
assertEqual(query.bindVars.options_0, {});
},
test_getVerticiesByExample: function() {
var result = g._vertices([{
name: uaName
},{
name: p1Name
}]).toArray();
assertEqual(result.length, 2);
var sorted = _.sortBy(result, "name");
assertEqual(sorted[0].name, uaName);
assertEqual(sorted[1].name, p1Name);
},
test_getVerticiesByExampleAndIdMixResultingAQL: function() {
var b_id = g[user].firstExample({name: ubName})._id;
var query = g._vertices([{
name: uaName
},
b_id,
{
name: ucName
}]);
var stmt = query.printQuery();
assertEqual(stmt, plainVertexQueryStmt(0));
assertEqual(query.bindVars.vertexExample_0, [
{name: uaName},
{_id: b_id},
{name: ucName}
]);
assertEqual(query.bindVars.options_0, {});
},
test_getVerticiesByExampleAndIdMix: function() {
var b_id = g[user].firstExample({name: ubName})._id;
var result = g._vertices([{
name: uaName
},
b_id,
{
name: ucName
}]).toArray();
assertEqual(result.length, 3);
var sorted = _.sortBy(result, "name");
assertEqual(sorted[0].name, uaName);
assertEqual(sorted[1].name, ubName);
assertEqual(sorted[2].name, ucName);
},
test_getAllEdgesResultingAQL: function() {
var query = g._edges();
var stmt = query.printQuery();
assertEqual(stmt, plainEdgesQueryStmt(0));
assertEqual(query.bindVars.options_0, {
direction: "outbound",
edgeExamples: [{}]
});
},
test_getAllEdges: function() {
var result = g._edges().toArray();
assertEqual(result.length, 9);
findFriends(result, [ud1, ud2, ud3, ud4]);
findBoughts(result, [d1, d2, d3, d4, d5]);
},
test_getEdgeByIdResultingAQL: function() {
var a_id = g[hasBought].firstExample({date: d1})._id;
var query = g._edges(a_id);
var stmt = query.printQuery();
assertEqual(stmt, plainEdgesQueryStmt(0));
assertEqual(query.bindVars.options_0, {
direction: "outbound",
edgeExamples: [{_id: a_id}]
});
},
test_getEdgeById: function() {
var a_id = g[hasBought].firstExample({date: d1})._id;
var result = g._edges(a_id).toArray();
assertEqual(result.length, 1);
findBoughts(result, [d1]);
},
test_getEdgesByIdResultingAQL: function() {
var a_id = g[hasBought].firstExample({date: d1})._id;
var b_id = g[isFriend].firstExample({since: ud2})._id;
var query = g._edges([a_id, b_id]);
var stmt = query.printQuery();
assertEqual(stmt, plainEdgesQueryStmt(0));
assertEqual(query.bindVars.options_0, {
direction: "outbound",
edgeExamples: [
{_id: a_id},
{_id: b_id}
]
});
},
test_getEdgesById: function() {
var a_id = g[hasBought].firstExample({date: d1})._id;
var b_id = g[isFriend].firstExample({since: ud2})._id;
var result = g._edges([a_id, b_id]).toArray();
assertEqual(result.length, 2);
findBoughts(result, [d1]);
findFriends(result, [ud2]);
},
test_getEdgeByExampleResultingAQL: function() {
var query = g._edges({
date: d2
});
var stmt = query.printQuery();
assertEqual(stmt, plainEdgesQueryStmt(0));
assertEqual(query.bindVars.options_0, {
direction: "outbound",
edgeExamples: [
{date: d2}
]
});
},
test_getEdgeByExample: function() {
var result = g._edges({
date: d2
}).toArray();
assertEqual(result.length, 1);
findBoughts(result, [d2]);
},
test_getEdgesByExampleResultingAQL: function() {
var query = g._edges([{
since: ud3
},{
date: d3
}]);
var stmt = query.printQuery();
assertEqual(stmt, plainEdgesQueryStmt(0));
assertEqual(query.bindVars.options_0, {
direction: "outbound",
edgeExamples: [
{since: ud3},
{date: d3}
]
});
},
test_getEdgesByExample: function() {
var result = g._edges([{
since: ud3
},{
date: d3
}]).toArray();
assertEqual(result.length, 2);
findBoughts(result, [d3]);
findFriends(result, [ud3]);
},
test_getEdgesByExampleAndIdMixResultingAQL: function() {
var b_id = g[hasBought].firstExample({date: d1})._id;
var query = g._edges([{
date: d5
},
b_id,
{
since: ud1
}]);
var stmt = query.printQuery();
assertEqual(stmt, plainEdgesQueryStmt(0));
assertEqual(query.bindVars.options_0, {
direction: "outbound",
edgeExamples: [
{date: d5},
{_id: b_id},
{since: ud1}
]
});
},
test_getEdgesByExampleAndIdMix: function() {
var b_id = g[hasBought].firstExample({date: d1})._id;
var result = g._edges([{
date: d5
},
b_id,
{
since: ud1
}]).toArray();
assertEqual(result.length, 3);
findBoughts(result, [d1, d5]);
findFriends(result, [ud1]);
},
test_getEdgesForSelectedVertexResultingAQL: function() {
var query = g._vertices({name: uaName})
.edges();
var stmt = query.printQuery();
var expected = [];
expected.push(plainVertexQueryStmt(0));
expected.push(plainEdgesQueryStmt(1, 0));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.vertexExample_0, {name: uaName});
assertEqual(query.bindVars.options_0, {});
assertEqual(query.bindVars.options_1, {
direction: "any",
edgeExamples: [{}]
});
},
test_getEdgesForSelectedVertex: function() {
var result = g._vertices({name: uaName})
.edges()
.toArray();
assertEqual(result.length, 3);
findBoughts(result, [d1]);
findFriends(result, [ud1, ud2]);
},
test_getInEdgesForSelectedVertexResultingAQL: function() {
var query = g._vertices({name: ubName})
.inEdges();
var stmt = query.printQuery();
var expected = [];
expected.push(plainVertexQueryStmt(0));
expected.push(plainEdgesQueryStmt(1, 0));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.vertexExample_0, {name: ubName});
assertEqual(query.bindVars.options_0, {});
assertEqual(query.bindVars.options_1, {
direction: "inbound",
edgeExamples: [{}]
});
},
test_getInEdgesForSelectedVertex: function() {
var result = g._vertices({name: ubName})
.inEdges()
.toArray();
assertEqual(result.length, 1);
findFriends(result, [ud1]);
},
test_getOutEdgesForSelectedVertexResultingAQL: function() {
var query = g._vertices({name: ubName})
.outEdges();
var stmt = query.printQuery();
var expected = [];
expected.push(plainVertexQueryStmt(0));
expected.push(plainEdgesQueryStmt(1, 0));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.vertexExample_0, {name: ubName});
assertEqual(query.bindVars.options_0, {});
assertEqual(query.bindVars.options_1, {
direction: "outbound",
edgeExamples: [{}]
});
},
test_getOutEdgesForSelectedVertex: function() {
var result = g._vertices({name: ubName})
.outEdges()
.toArray();
assertEqual(result.length, 3);
findBoughts(result, [d2, d3]);
findFriends(result, [ud3]);
},
test_getVerticesForSelectedEdgeResultingAQL: function() {
var query = g._edges({since: ud1})
.vertices();
var stmt = query.printQuery();
var expected = [];
expected.push(plainEdgesQueryStmt(0));
expected.push(plainVertexQueryStmt(1));
expected.push(vertexFilterStmt("both", 0, 1));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.options_0, {
direction: "outbound",
edgeExamples: [{since: ud1}]
});
assertEqual(query.bindVars.options_1, {});
},
test_getVerticesForSelectedEdge: function() {
var result = g._edges({since: ud1})
.vertices()
.toArray();
assertEqual(result.length, 2);
var sorted = _.sortBy(result, "name");
assertEqual(sorted[0].name, uaName);
assertEqual(sorted[1].name, ubName);
},
test_toVertexForSelectedEdgeResultingAQL: function() {
var query = g._edges({since: ud1})
.toVertices();
var stmt = query.printQuery();
var expected = [];
expected.push(plainEdgesQueryStmt(0));
expected.push(plainVertexQueryStmt(1));
expected.push(vertexFilterStmt("to", 0, 1));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.options_0, {
direction: "outbound",
edgeExamples: [{since: ud1}]
});
assertEqual(query.bindVars.options_1, {});
},
test_toVertexForSelectedEdge: function() {
var result = g._edges({since: ud1})
.toVertices()
.toArray();
assertEqual(result.length, 1);
assertEqual(result[0].name, ubName);
},
test_fromVertexForSelectedEdgeResultingAQL: function() {
var query = g._edges({since: ud1})
.fromVertices();
var stmt = query.printQuery();
var expected = [];
expected.push(plainEdgesQueryStmt(0));
expected.push(plainVertexQueryStmt(1));
expected.push(vertexFilterStmt("from", 0, 1));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.options_0, {
direction: "outbound",
edgeExamples: [{since: ud1}]
});
assertEqual(query.bindVars.options_1, {});
},
test_fromVertexForSelectedEdge: function() {
var result = g._edges({since: ud1})
.fromVertices()
.toArray();
assertEqual(result.length, 1);
assertEqual(result[0].name, uaName);
},
test_getAllVerticesThroughOutgoingEdgeResultingAQL: function() {
var query = g._vertices({name: uaName})
.outEdges()
.toVertices();
var stmt = query.printQuery();
var expected = [];
expected.push(plainVertexQueryStmt(0));
expected.push(plainEdgesQueryStmt(1, 0));
expected.push(plainVertexQueryStmt(2));
expected.push(vertexFilterStmt("to", 1, 2));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.vertexExample_0, {
name: uaName
});
assertEqual(query.bindVars.options_0, {});
assertEqual(query.bindVars.options_1, {
direction: "outbound",
edgeExamples: [{}]
});
assertEqual(query.bindVars.options_2, {});
},
test_getAllVerticesThroughOutgoingEdges: function() {
var result = g._vertices({name: uaName})
.outEdges()
.toVertices()
.toArray();
assertEqual(result.length, 3);
var sorted = _.sortBy(result, "name");
assertEqual(sorted[0].name, ubName);
assertEqual(sorted[1].name, ucName);
assertEqual(sorted[2].name, p1Name);
},
test_getAllVerticesThroughOutgoingEdgesWithFilterResultingAQL: function() {
var query = g._vertices({name: uaName})
.outEdges([
{since: ud1},
{date: d1}
])
.toVertices();
var stmt = query.printQuery();
var expected = [];
expected.push(plainVertexQueryStmt(0));
expected.push(plainEdgesQueryStmt(1, 0));
expected.push(plainVertexQueryStmt(2));
expected.push(vertexFilterStmt("to", 1, 2));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.vertexExample_0, {
name: uaName
});
assertEqual(query.bindVars.options_0, {});
assertEqual(query.bindVars.options_1, {
direction: "outbound",
edgeExamples: [
{since: ud1},
{date: d1}
]
});
assertEqual(query.bindVars.options_2, {});
},
test_getAllVerticesThroughOutgoingEdgesWithFilter: function() {
var result = g._vertices({name: uaName})
.outEdges([
{since: ud1},
{date: d1}
]).toVertices()
.toArray();
assertEqual(result.length, 2);
var sorted = _.sortBy(result, "name");
assertEqual(sorted[0].name, ubName);
assertEqual(sorted[1].name, p1Name);
},
test_getNeighborsOfSelectedVerticesResultingAQL: function() {
var query = g._vertices({name: uaName})
.neighbors();
var stmt = query.printQuery();
var expected = [];
expected.push(plainVertexQueryStmt(0));
expected.push(plainNeighborQueryStmt(1, 0));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.options_0, {});
assertEqual(query.bindVars.options_1, {
neighborExamples: {}
});
},
test_getNeighborsOfSelectedVertices: function() {
var result = g._vertices({name: uaName})
.neighbors()
.toArray();
assertEqual(result.length, 3);
var sorted = _.sortBy(result, "name");
assertEqual(sorted[0].name, ubName);
assertEqual(sorted[1].name, ucName);
assertEqual(sorted[2].name, p1Name);
},
test_getExampleNeighborsOfSelectedVerticesResultingAQL: function() {
var query = g._vertices({name: uaName})
.neighbors([{
name: ubName
},{
name: p1Name
}]);
var stmt = query.printQuery();
var expected = [];
expected.push(plainVertexQueryStmt(0));
expected.push(plainNeighborQueryStmt(1, 0));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.options_0, {});
assertEqual(query.bindVars.options_1, {
neighborExamples: [{
name: ubName
},{
name: p1Name
}]
});
},
test_getExampleNeighborsOfSelectedVertices: function() {
var result = g._vertices({name: uaName})
.neighbors([{
name: ubName
},{
name: p1Name
}])
.toArray();
assertEqual(result.length, 2);
var sorted = _.sortBy(result, "name");
assertEqual(sorted[0].name, ubName);
assertEqual(sorted[1].name, p1Name);
},
test_getEdgesOfNeighborsResultingAQL: function() {
var query = g._vertices({name: uaName})
.neighbors()
.outEdges();
var stmt = query.printQuery();
var expected = [];
expected.push(plainVertexQueryStmt(0));
expected.push(plainNeighborQueryStmt(1, 0));
expected.push(plainEdgesQueryStmt(2, 1, "neighbors"));
assertEqual(stmt, expected.join(" "));
assertEqual(query.bindVars.options_0, {});
assertEqual(query.bindVars.options_1, {
neighborExamples: {}
});
assertEqual(query.bindVars.options_2, {
direction: "outbound",
edgeExamples: [{}]
});
},
test_getEdgesOfNeighbors: function() {
var result = g._vertices({name: uaName})
.neighbors()
.outEdges()
.toArray();
assertEqual(result.length, 4);
findFriends(result, [ud3, ud4]);
findBoughts(result, [d2, d3]);
},
test_path: function() {
var result = g._vertices({name: uaName})
.edges()
.toVertices()
.path()
.toArray();
assertEqual(uaName, result[0][0].name);
assertEqual(ud1, result[0][1].since);
assertEqual(ubName, result[0][2].name);
assertEqual(uaName, result[1][0].name);
assertEqual(ud2, result[1][1].since);
assertEqual(ucName, result[1][2].name);
assertEqual(uaName, result[2][0].name);
assertEqual(d1, result[2][1].date);
assertEqual(p1Name, result[2][2].name);
},
test_pathVertices: function() {
var result = g._vertices({name: uaName})
.edges()
.toVertices()
.pathVertices()
.toArray();
assertEqual(uaName, result[0][0].name);
assertEqual(ubName, result[0][1].name);
assertEqual(uaName, result[1][0].name);
assertEqual(ucName, result[1][1].name);
assertEqual(uaName, result[2][0].name);
assertEqual(p1Name, result[2][1].name);
},
test_pathEdges: function() {
var result = g._vertices({name: uaName})
.edges()
.toVertices()
.pathEdges()
.toArray();
assertEqual(ud1, result[0][0].since);
assertEqual(ud2, result[1][0].since);
assertEqual(d1, result[2][0].date);
}
};
}
function EdgesAndVerticesSuite() {
var g;
var vertexId1, vertexId2;
var unitTestGraphName = "unitTestGraph";
var ec1 = "unitTestEdgeCollection1";
var ec2 = "unitTestEdgeCollection2";
var vc1 = "unitTestVertexCollection1";
var vc2 = "unitTestVertexCollection2";
var vc3 = "unitTestVertexCollection3";
var vc4 = "unitTestVertexCollection4";
var fillCollections = function() {
var ids = {};
var vertex = g[vc1].save({first_name: "Tam"});
ids.vId11 = vertex._id;
vertex = g[vc1].save({first_name: "Tem"});
ids.vId12 = vertex._id;
vertex = g[vc1].save({first_name: "Tim"});
ids.vId13 = vertex._id;
vertex = g[vc1].save({first_name: "Tom"});
ids.vId14 = vertex._id;
vertex = g[vc1].save({first_name: "Tum"});
ids.vId15 = vertex._id;
vertex = g[vc3].save({first_name: "Tam"});
ids.vId31 = vertex._id;
vertex = g[vc3].save({first_name: "Tem"});
ids.vId32 = vertex._id;
vertex = g[vc3].save({first_name: "Tim"});
ids.vId33 = vertex._id;
vertex = g[vc3].save({first_name: "Tom"});
ids.vId34 = vertex._id;
vertex = g[vc3].save({first_name: "Tum"});
ids.vId35 = vertex._id;
var edge = g[ec1].save(ids.vId11, ids.vId12, {});
ids.eId11 = edge._id;
edge = g[ec1].save(ids.vId11, ids.vId13, {});
ids.eId12 = edge._id;
edge = g[ec1].save(ids.vId11, ids.vId14, {});
ids.eId13 = edge._id;
edge = g[ec1].save(ids.vId11, ids.vId15, {});
ids.eId14 = edge._id;
edge = g[ec1].save(ids.vId12, ids.vId11, {});
ids.eId15 = edge._id;
edge = g[ec1].save(ids.vId13, ids.vId11, {});
ids.eId16 = edge._id;
edge = g[ec1].save(ids.vId14, ids.vId11, {});
ids.eId17 = edge._id;
edge = g[ec1].save(ids.vId15, ids.vId11, {});
ids.eId18 = edge._id;
edge = g[ec2].save(ids.vId11, ids.vId31, {});
ids.eId21 = edge._id;
edge = g[ec2].save(ids.vId11, ids.vId32, {});
ids.eId22 = edge._id;
edge = g[ec2].save(ids.vId11, ids.vId33, {});
ids.eId23 = edge._id;
edge = g[ec2].save(ids.vId11, ids.vId34, {});
ids.eId24 = edge._id;
edge = g[ec2].save(ids.vId11, ids.vId35, {});
ids.eId25 = edge._id;
return ids;
};
return {
setUp : function() {
try {
arangodb.db._collection("_graphs").remove(unitTestGraphName);
} catch (ignore) {
}
g = graph._create(
unitTestGraphName,
graph._edgeDefinitions(
graph._undirectedRelation(ec1, vc1),
graph._directedRelation(ec2,
[vc1, vc2], [vc3, vc4]
)
)
);
},
tearDown : function() {
graph._drop(unitTestGraphName, true);
},
test_dropGraph1 : function () {
var myGraphName = unitTestGraphName + "2";
var myEdgeColName = "unitTestEdgeCollection4711";
var myVertexColName = vc1;
graph._create(
myGraphName,
graph._edgeDefinitions(
graph._undirectedRelation(myEdgeColName, myVertexColName)
)
);
graph._drop(myGraphName, true);
assertFalse(graph._exists(myGraphName));
assertTrue(db._collection(myVertexColName) !== null);
assertTrue(db._collection(myEdgeColName) === null);
},
test_dropGraph2 : function () {
var myGraphName = unitTestGraphName + "2";
var myEdgeColName = "unitTestEdgeCollection4711";
var myVertexColName = vc1;
graph._create(
myGraphName,
graph._edgeDefinitions(
graph._undirectedRelation(myEdgeColName, myVertexColName)
)
);
graph._drop(myGraphName);
assertFalse(graph._exists(myGraphName));
assertTrue(db._collection(myVertexColName) !== null);
assertTrue(db._collection(myEdgeColName) !== null);
},
test_createGraphWithCollectionDuplicateOK : function () {
var myGraphName = unitTestGraphName + "2";
graph._create(
myGraphName,
graph._edgeDefinitions(
graph._undirectedRelation(ec1, vc1)
)
);
assertTrue(graph._exists(myGraphName));
graph._drop(myGraphName, true);
assertFalse(graph._exists(myGraphName));
assertTrue(db._collection(vc1) !== null);
assertTrue(db._collection(ec1) !== null);
},
test_createGraphWithCollectionDuplicateNOK1 : function () {
var myGraphName = unitTestGraphName + "2";
try {
graph._create(
myGraphName,
graph._edgeDefinitions(
graph._undirectedRelation(ec1, vc2)
)
);
} catch (e) {
assertEqual(
e.errorMessage,
ec1 + " " + arangodb.errors.ERROR_GRAPH_COLLECTION_USE_IN_MULTI_GRAPHS.message
);
}
assertFalse(graph._exists(myGraphName));
assertTrue(db._collection(vc2) !== null);
assertTrue(db._collection(ec1) !== null);
},
test_createGraphWithCollectionDuplicateNOK2 : function () {
var myGraphName = unitTestGraphName + "2";
var myED = "unitTestEdgeCollection4711";
var myVD1 = "unitTestVertexCollection4711";
var myVD2 = "unitTestVertexCollection4712";
try {graph._drop(myGraphName, true)} catch (ignore){}
try {db._drop(myED)} catch (ignore){}
try {
graph._create(
myGraphName,
graph._edgeDefinitions(
graph._undirectedRelation(myED, myVD1),
graph._undirectedRelation(myED, myVD2)
)
);
} catch (e) {
assertEqual(
e.errorMessage,
arangodb.errors.ERROR_GRAPH_COLLECTION_MULTI_USE.message
);
}
assertFalse(graph._exists(myGraphName));
assertTrue(db._collection(myVD1) === null);
assertTrue(db._collection(myVD2) === null);
assertTrue(db._collection(myED) === null);
},
test_edgeCollections : function () {
var edgeCollections = g._edgeCollections();
assertEqual(edgeCollections[0].name(), ec1);
assertEqual(edgeCollections[1].name(), ec2);
},
test_vertexCollections : function () {
var vertexCollections = g._vertexCollections();
assertEqual(vertexCollections[0].name(), vc1);
assertEqual(vertexCollections[1].name(), vc2);
assertEqual(vertexCollections[2].name(), vc3);
assertEqual(vertexCollections[3].name(), vc4);
},
test_vC_save : function () {
var vertex = g[vc1].save({first_name: "Tom"});
assertFalse(vertex.error);
vertexId1 = vertex._id;
var vertexObj = g[vc1].document(vertexId1);
assertEqual(vertexObj.first_name, "Tom");
},
test_vC_replace : function () {
var vertex = g[vc1].save({first_name: "Tom"});
var vertexId = vertex._id;
vertex = g[vc1].replace(vertexId, {first_name: "Tim"});
assertFalse(vertex.error);
var vertexObj = g[vc1].document(vertexId);
assertEqual(vertexObj.first_name, "Tim");
},
test_vC_update : function () {
var vertex = g[vc1].save({first_name: "Tim"});
var vertexId = vertex._id;
vertex = g[vc1].update(vertexId, {age: 42});
assertFalse(vertex.error);
var vertexObj = g[vc1].document(vertexId);
assertEqual(vertexObj.first_name, "Tim");
assertEqual(vertexObj.age, 42);
},
test_vC_remove : function () {
var vertex = g[vc1].save({first_name: "Tim"});
var vertexId = vertex._id;
var result = g[vc1].remove(vertexId);
assertTrue(result);
},
test_vC_removeWithEdge : function () {
var vertex1 = g[vc1].save({first_name: "Tim"});
var vId1 = vertex1._id;
var vertex2 = g[vc1].save({first_name: "Tom"});
var vId2 = vertex2._id;
var edge = g[ec1].save(vId1, vId2, {});
var edgeId = edge._id;
var result = g[vc1].remove(vId1);
assertTrue(result);
assertFalse(db[ec1].exists(edgeId));
result = g[vc1].remove(vId2);
assertTrue(result);
},
test_eC_save_undirected : function() {
var vertex1 = g[vc1].save({first_name: "Tom"});
var vId1 = vertex1._id;
var vertex2 = g[vc1].save({first_name: "Tim"});
var vId2 = vertex2._id;
var edge = g[ec1].save(vertexId1, vId2, {});
assertFalse(edge.error);
g[vc1].remove(vId1);
g[vc1].remove(vId2);
},
test_eC_save_directed : function() {
var vertex1 = g[vc2].save({first_name: "Tom"});
vertexId1 = vertex1._id;
var vertex2 = g[vc4].save({first_name: "Tim"});
vertexId2 = vertex2._id;
var edge = g[ec2].save(vertexId1, vertexId2, {});
assertFalse(edge.error);
g[vc2].remove(vertexId1);
g[vc4].remove(vertexId2);
},
test_eC_save_withError : function() {
var vertex1 = g[vc1].save({first_name: "Tom"});
vertexId1 = vertex1._id;
var vertex2 = g[vc2].save({first_name: "Tim"});
vertexId2 = vertex2._id;
try {
g[ec1].save(vertexId1, vertexId2, {});
fail();
} catch (e) {
assertEqual(e.errorNum, 1906);
}
g[vc1].remove(vertexId1);
g[vc2].remove(vertexId2);
},
test_eC_replace : function() {
var vertex1 = g[vc1].save({first_name: "Tom"});
var vertexId1 = vertex1._id;
var vertex2 = g[vc1].save({first_name: "Tim"});
var vertexId2 = vertex2._id;
var edge = g[ec1].save(vertexId1, vertexId2, {});
var edgeId1 = edge._id;
edge = g[ec1].replace(edgeId1, {label: "knows"});
assertFalse(edge.error);
var edgeObj = g[ec1].document(edgeId1);
assertEqual(edgeObj.label, "knows");
assertEqual(edgeObj._id, edgeId1);
},
test_eC_update : function () {
var vertex1 = g[vc1].save({first_name: "Tom"});
var vertexId1 = vertex1._id;
var vertex2 = g[vc1].save({first_name: "Tim"});
var vertexId2 = vertex2._id;
var edge = g[ec1].save(vertexId1, vertexId2, {});
var edgeId1 = edge._id;
edge = g[ec1].replace(edgeId1, {label: "knows"});
edge = g[ec1].update(edgeId1, {blub: "blub"});
assertFalse(edge.error);
var edgeObj = g[ec1].document(edgeId1);
assertEqual(edgeObj.label, "knows");
assertEqual(edgeObj.blub, "blub");
assertEqual(edgeObj._id, edgeId1);
},
test_eC_remove : function () {
var vertex1 = g[vc1].save({first_name: "Tom"});
var vertexId1 = vertex1._id;
var vertex2 = g[vc1].save({first_name: "Tim"});
var vertexId2 = vertex2._id;
var edge = g[ec1].save(vertexId1, vertexId2, {});
var edgeId1 = edge._id;
edge = g[ec1].remove(edgeId1);
assertTrue(edge);
},
test_eC_removeWithEdgesAsVertices : function () {
var myGraphName = unitTestGraphName + "0815";
var myEC02 = "unitTestEdgeCollection02";
var myVC01 = "unitTestVertexCollection01";
try {
graph._drop(myGraphName, true);
db._drop(myEC02);
db._drop(myVC01);
} catch (ignore) {
}
var g2 = graph._create(
myGraphName,
graph._edgeDefinitions(
graph._directedRelation(myEC02,
[ec1], [myVC01]
)
)
);
var vertex1 = g[vc1].save({first_name: "Tom"});
var vertexId1 = vertex1._id;
var vertex2 = g[vc1].save({first_name: "Tim"});
var vertexId2 = vertex2._id;
var vertex3 = g2.unitTestVertexCollection01.save({first_name: "Ralph"});
var vertexId3 = vertex3._id;
var edge = g[ec1].save(vertexId1, vertexId2, {});
var edge2 = g2.unitTestEdgeCollection02.save(edge._id, vertexId3, {});
var edgeId1 = edge._id;
edge = g[ec1].remove(edgeId1);
assertTrue(edge);
assertFalse(db._exists(edge2._id));
graph._drop(myGraphName, true);
assertFalse(graph._exists(myGraphName));
},
test_eC_removeWithEdgesAsVerticesCircle : function () {
var gN1 = "unitTestGraphCircle1";
var gN2 = "unitTestGraphCircle2";
var gN3 = "unitTestGraphCircle3";
var gN4 = "unitTestGraphCircle4";
var eC1 = "unitTestEdgeCollectionCircle1";
var eC2 = "unitTestEdgeCollectionCircle2";
var eC3 = "unitTestEdgeCollectionCircle3";
var eC4 = "unitTestEdgeCollectionCircle4";
var vC1 = "unitTestVertexCollectionCircle1";
var vC2 = "unitTestVertexCollectionCircle2";
var vC3 = "unitTestVertexCollectionCircle3";
var vC4 = "unitTestVertexCollectionCircle4";
try {
graph._drop(gN1, true);
graph._drop(gN2, true);
graph._drop(gN3, true);
graph._drop(gN4, true);
db._drop(eC1);
db._drop(eC2);
db._drop(eC3);
db._drop(eC4);
db._drop(vC1);
db._drop(vC2);
db._drop(vC3);
db._drop(vC4);
} catch (ignore) {
}
db._createEdgeCollection(eC1)
db._createEdgeCollection(eC2)
db._createEdgeCollection(eC3)
db._createEdgeCollection(eC4)
db._create(vC1)
db._create(vC2)
db._create(vC3)
db._create(vC4)
var vertex1 = db[vC1].save({});
var vertexId1 = vertex1._id;
var vertex2 = db[vC1].save({});
var vertexId2 = vertex2._id;
var vertex3 = db[vC1].save({});
var vertexId3 = vertex3._id;
var vertex4 = db[vC1].save({});
var vertexId4 = vertex4._id;
var edge1 = db[eC1].save(eC4 + "/4", vertexId1, {_key: "1"});
var edge2 = db[eC2].save(eC1 + "/1", vertexId2, {_key: "2"});
var edge3 = db[eC3].save(eC2 + "/2", vertexId3, {_key: "3"});
var edge4 = db[eC4].save(eC3 + "/3", vertexId4, {_key: "4"});
var g1 = graph._create(
gN1,
graph._edgeDefinitions(
graph._directedRelation(eC1, [eC4], [vC1])
)
);
var g2 = graph._create(
gN2,
graph._edgeDefinitions(
graph._directedRelation(eC2, [eC1], [vC2])
)
);
var g3 = graph._create(
gN3,
graph._edgeDefinitions(
graph._directedRelation(eC3, [eC2], [vC3])
)
);
var g4 = graph._create(
gN4,
graph._edgeDefinitions(
graph._directedRelation(eC4, [eC3], [vC4])
)
);
assertTrue(db._exists(edge1._id));
assertTrue(db._exists(edge2._id));
assertTrue(db._exists(edge3._id));
assertTrue(db._exists(edge4._id));
assertTrue(db._exists(vertexId1));
assertTrue(db._exists(vertexId2));
assertTrue(db._exists(vertexId3));
assertTrue(db._exists(vertexId4));
var edge = g1[eC1].remove(edge1._id);
assertFalse(db._exists(edge1._id));
assertFalse(db._exists(edge2._id));
assertFalse(db._exists(edge3._id));
assertFalse(db._exists(edge4._id));
assertTrue(db._exists(vertexId1));
assertTrue(db._exists(vertexId2));
assertTrue(db._exists(vertexId3));
assertTrue(db._exists(vertexId4));
graph._drop(gN1, true);
graph._drop(gN2, true);
graph._drop(gN3, true);
graph._drop(gN4, true);
},
test_getInVertex : function() {
var ids = fillCollections();
var result = g._fromVertex(ids.eId11);
assertEqual(result._id, ids.vId11);
},
test_getOutVertex : function() {
var ids = fillCollections();
var result = g._toVertex(ids.eId11);
assertEqual(result._id, ids.vId12);
result = g._toVertex(ids.eId25);
assertEqual(result._id, ids.vId35);
}
};
}
function GeneralGraphCommonNeighborsSuite() {
var testGraph, actual;
var v1ColName = "UnitTestsAhuacatlVertex1";
var v2ColName = "UnitTestsAhuacatlVertex2";
var eColName = "UnitTestsAhuacatlEdge1";
var v1;
var v2;
var v3;
var v4;
var v5;
var v6;
var v7;
var v8;
var createKeyValueObject = function(key, value) {
var res = {};
res[key] = value;
return res;
};
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////
setUp: function () {
db._drop(v1ColName);
db._drop(v2ColName);
db._drop(eColName);
var vertex1 = db._create(v1ColName);
var vertex2 = db._create(v2ColName);
var edge1 = db._createEdgeCollection(eColName);
v1 = vertex1.save({ _key: "v1" , hugo : true})._id;
v2 = vertex1.save({ _key: "v2" ,hugo : true})._id;
v3 = vertex1.save({ _key: "v3" , heinz : 1})._id;
v4 = vertex1.save({ _key: "v4" , harald : "meier"})._id;
v5 = vertex2.save({ _key: "v5" , ageing : true})._id;
v6 = vertex2.save({ _key: "v6" , harald : "meier", ageing : true})._id;
v7 = vertex2.save({ _key: "v7" ,harald : "meier"})._id;
v8 = vertex2.save({ _key: "v8" ,heinz : 1, harald : "meier"})._id;
function makeEdge(from, to, collection) {
collection.save(from, to, { what: from.split("/")[1] + "->" + to.split("/")[1] });
}
makeEdge(v1, v2, edge1);
makeEdge(v2, v3, edge1);
makeEdge(v3, v5, edge1);
makeEdge(v2, v6, edge1);
makeEdge(v6, v7, edge1);
makeEdge(v4, v7, edge1);
makeEdge(v3, v7, edge1);
makeEdge(v8, v1, edge1);
makeEdge(v3, v5, edge1);
makeEdge(v3, v8, edge1);
try {
db._collection("_graphs").remove("_graphs/bla3");
} catch (ignore) {
}
testGraph = graph._create(
"bla3",
graph._edgeDefinitions(
graph._directedRelation(eColName,
[v1ColName, v2ColName],
[v1ColName, v2ColName]
)
)
);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////
tearDown: function () {
db._drop(v1ColName);
db._drop(v2ColName);
db._drop(eColName);
try {
db._collection("_graphs").remove("_graphs/bla3");
} catch (ignore) {
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief checks GRAPH_COMMON_NEIGHBORS() and GRAPH_COMMON_PROPERTIES()
////////////////////////////////////////////////////////////////////////////////
testNeighborsAnyV3: function () {
actual = testGraph._neighbors(v3);
assertTrue(actual[0]._id, v2);
assertTrue(actual[1]._id, v5);
assertTrue(actual[2]._id, v8);
assertTrue(actual[3]._id, v5);
assertTrue(actual[4]._id, v7);
},
testNeighborsAnyV6: function () {
actual = testGraph._neighbors(v6);
assertTrue(actual[0]._id, v2);
assertTrue(actual[1]._id, v7);
},
testCommonNeighborsAny: function () {
actual = testGraph._commonNeighbors(v3 , v6);
assertEqual(actual[0][v3][v6][0]._id , v2);
assertEqual(actual[0][v3][v6][1]._id , v7);
actual = testGraph._countCommonNeighbors(v3 , v6);
assertEqual(actual[0][v3][0][v6] , 2);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief checks GRAPH_COMMON_NEIGHBORS()
////////////////////////////////////////////////////////////////////////////////
testCommonNeighborsIn: function () {
actual = testGraph._commonNeighbors({} , {}, {direction : 'inbound'}, {direction : 'inbound'});
assertEqual(actual.length, 5 );
actual = testGraph._countCommonNeighbors({} , {}, {direction : 'inbound'}, {direction : 'inbound'});
assertEqual(actual.length, 5 );
},
////////////////////////////////////////////////////////////////////////////////
/// @brief checks GRAPH_COMMON_NEIGHBORS()
////////////////////////////////////////////////////////////////////////////////
testCommonNeighborsOut: function () {
actual = testGraph._commonNeighbors(
{hugo: true}, {heinz: 1},
{direction: 'outbound', minDepth: 1, maxDepth: 3},
{direction: 'outbound', minDepth: 1, maxDepth: 3}
);
assertEqual(Object.keys(actual[1])[0], v2);
assertEqual(Object.keys(actual[1][Object.keys(actual[1])[0]]), [v8, v3]);
assertEqual(actual[1][Object.keys(actual[1])[0]][v8].length, 3);
assertEqual(actual[1][Object.keys(actual[1])[0]][v3].length, 4);
assertEqual(Object.keys(actual[0])[0], v1);
assertEqual(Object.keys(actual[0][Object.keys(actual[0])[0]]), [v8, v3]);
assertEqual(actual[0][Object.keys(actual[0])[0]][v3].length, 4);
assertEqual(actual[0][Object.keys(actual[0])[0]][v8].length, 3);
actual = testGraph._countCommonNeighbors(
{hugo: true }, {heinz: 1},
{direction: 'outbound', minDepth: 1, maxDepth: 3},
{direction: 'outbound', minDepth: 1, maxDepth: 3}
);
assertEqual(actual[0][v1][0][v8], 3);
assertEqual(actual[0][v1][1][v3], 4);
assertEqual(actual[1][v2][0][v8], 3);
assertEqual(actual[1][v2][1][v3], 4);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief checks GRAPH_COMMON_PROPERTIES()
////////////////////////////////////////////////////////////////////////////////
testCommonProperties: function () {
actual = testGraph._commonProperties({} ,{} ,{});
assertEqual(actual.length, 8 );
actual = testGraph._countCommonProperties({} ,{} ,{});
assertEqual(actual, [
createKeyValueObject(v1, 1),
createKeyValueObject(v2, 1),
createKeyValueObject(v3, 1),
createKeyValueObject(v4, 3),
createKeyValueObject(v5, 1),
createKeyValueObject(v6, 4),
createKeyValueObject(v7, 3),
createKeyValueObject(v8, 4)
]);
},
testCommonPropertiesWithFilters: function () {
actual = testGraph._commonProperties({ageing : true} , {harald : 'meier'}, {});
assertEqual(actual[0][v5][0]._id , v6);
assertEqual(actual[1][v6][0]._id , v4);
assertEqual(actual[1][v6][1]._id , v8);
assertEqual(actual[1][v6][2]._id , v7);
actual = testGraph._countCommonProperties({ageing : true} , {harald : 'meier'}, {});
assertEqual(actual, [
createKeyValueObject(v5, 1),
createKeyValueObject(v6, 3)
]);
},
testCommonPropertiesWithFiltersAndIgnoringKeyHarald: function () {
actual = testGraph._commonProperties( {} , {}, {ignoreProperties : 'harald'});
assertEqual(actual[0][v1][0]._id , v2);
assertEqual(actual[1][v2][0]._id , v1);
assertEqual(actual[2][v3][0]._id , v8);
assertEqual(actual[3][v5][0]._id , v6);
assertEqual(actual[4][v6][0]._id , v5);
assertEqual(actual[5][v8][0]._id , v3);
actual = testGraph._countCommonProperties({} , {}, {ignoreProperties : 'harald'});
assertEqual(actual, [
createKeyValueObject(v1, 1),
createKeyValueObject(v2, 1),
createKeyValueObject(v3, 1),
createKeyValueObject(v5, 1),
createKeyValueObject(v6, 1),
createKeyValueObject(v8, 1)
]);
}
};
}
function OrphanCollectionSuite() {
var prefix = "UnitTestGraphVertexCollection",
g1,
g2,
gN1 = prefix + "Graph1",
gN2 = prefix + "Graph2",
eC1 = prefix + "EdgeCollection1",
eC2 = prefix + "EdgeCollection2",
vC1 = prefix + "VertexCollection1",
vC2 = prefix + "VertexCollection2",
vC3 = prefix + "VertexCollection3",
vC4 = prefix + "VertexCollection4",
vC5 = prefix + "VertexCollection5";
return {
setUp : function() {
try {
arangodb.db._collection("_graphs").remove(gN1);
} catch (ignore) {
}
try {
arangodb.db._collection("_graphs").remove(gN2);
} catch (ignore) {
}
g1 = graph._create(
gN1,
graph._edgeDefinitions(
graph._directedRelation(
eC1, [vC1], [vC1, vC2]
)
)
);
g2 = graph._create(
gN2,
graph._edgeDefinitions(
graph._directedRelation(
eC2, [vC3], [vC1]
)
)
);
},
tearDown : function() {
try {
graph._drop(gN1, true);
} catch(ignore) { }
try {
graph._drop(gN2, true);
} catch(ignore) { }
try {
db[vC1].drop();
} catch (ignore) {}
try {
db[vC4].drop();
} catch (ignore) {}
},
test_getOrphanCollection: function() {
assertEqual(g1._orphanCollections(), []);
},
test_addVertexCollection1: function() {
g1._addVertexCollection(vC5, true);
assertEqual(g1._orphanCollections(), [vC5]);
},
test_addVertexCollection2: function() {
try {
g1._addVertexCollection(vC4, false);
} catch (e) {
assertEqual(e.errorNum, ERRORS.ERROR_GRAPH_VERTEX_COL_DOES_NOT_EXIST.code);
assertEqual(e.errorMessage, vC4 + ERRORS.ERROR_GRAPH_VERTEX_COL_DOES_NOT_EXIST.message);
}
assertTrue(db._collection(vC4) === null);
assertEqual(g1._orphanCollections(), []);
},
test_addVertexCollection3: function() {
try {
g1._addVertexCollection(eC1, false);
} catch (e) {
assertEqual(e.errorNum, ERRORS.ERROR_GRAPH_WRONG_COLLECTION_TYPE_VERTEX.code);
assertEqual(e.errorMessage, ERRORS.ERROR_GRAPH_WRONG_COLLECTION_TYPE_VERTEX.message);
}
assertTrue(db._collection(vC4) === null);
assertEqual(g1._orphanCollections(), []);
},
test_addVertexCollection4: function() {
try {
g1._addVertexCollection(vC1);
} catch (e) {
assertEqual(e.errorNum, ERRORS.ERROR_GRAPH_COLLECTION_USED_IN_EDGE_DEF.code);
assertEqual(e.errorMessage, ERRORS.ERROR_GRAPH_COLLECTION_USED_IN_EDGE_DEF.message);
}
},
test_removeVertexCollection1: function() {
var name = "completelyNonsenseNameForACollectionBLUBBBBB"
try {
g1._removeVertexCollection(name);
} catch (e) {
assertEqual(e.errorNum, ERRORS.ERROR_GRAPH_VERTEX_COL_DOES_NOT_EXIST.code);
assertEqual(e.errorMessage, ERRORS.ERROR_GRAPH_VERTEX_COL_DOES_NOT_EXIST.message);
}
},
test_removeVertexCollection2: function() {
g1._addVertexCollection(vC4, true);
g1._addVertexCollection(vC5, true);
assertEqual(g1._orphanCollections(), [vC4, vC5]);
g1._removeVertexCollection(vC4, false);
assertTrue(db._collection(vC4) !== null);
assertEqual(g1._orphanCollections(), [vC5]);
try {
g1._removeVertexCollection(vC4, true);
} catch (e) {
assertEqual(e.errorNum, ERRORS.ERROR_GRAPH_NOT_IN_ORPHAN_COLLECTION.code);
assertEqual(e.errorMessage, ERRORS.ERROR_GRAPH_NOT_IN_ORPHAN_COLLECTION.message);
}
},
test_doNotDropOrphanCollectionsUsedInOtherEdgedefinitions: function() {
assertTrue(db._collection(vC3) !== null);
g1._addVertexCollection(vC3, true);
assertTrue(db._collection(vC3) !== null);
graph._drop(gN1, true);
assertTrue(db._collection(vC3) !== null);
graph._drop(gN2, true);
assertTrue(db._collection(vC3) === null);
},
test_doNotDropCollectionsIfUsedAsOrphansInOtherGraphs: function() {
assertTrue(db._collection(vC3) !== null);
g1._addVertexCollection(vC3, true);
assertTrue(db._collection(vC3) !== null);
graph._drop(gN2, true);
assertTrue(db._collection(vC3) !== null);
graph._drop(gN1, true);
assertTrue(db._collection(vC3) === null);
},
test_doNotDropOrphanCollectionsUsedAsOrphansInOtherGraphs: function() {
assertTrue(db._collection(vC4) === null);
g1._addVertexCollection(vC4, true);
g2._addVertexCollection(vC4, true);
assertTrue(db._collection(vC4) !== null);
graph._drop(gN1, true);
assertTrue(db._collection(vC4) !== null);
graph._drop(gN2, true);
assertTrue(db._collection(vC4) === null);
},
test_doNotAddTheSameOrphanCollectionMultipleTimes: function() {
g1._addVertexCollection(vC4, true);
try {
g1._addVertexCollection(vC4, true);
fail();
} catch(err) {
assertEqual(err.errorNum, arangodb.errors.ERROR_GRAPH_COLLECTION_USED_IN_ORPHANS.code);
assertEqual(err.errorMessage,
arangodb.errors.ERROR_GRAPH_COLLECTION_USED_IN_ORPHANS.message);
}
}
};
}
function MeasurementsSuite() {
var g;
var vertexId1, vertexId2;
var unitTestGraphName = "unitTestGraph";
var ec1 = "unitTestEdgeCollection1";
var ec2 = "unitTestEdgeCollection2";
var vc1 = "unitTestVertexCollection1";
var vc2 = "unitTestVertexCollection2";
var vc3 = "unitTestVertexCollection3";
var vc4 = "unitTestVertexCollection4";
var fillCollections = function() {
var ids = {};
var vertex = g[vc1].save({first_name: "Tam"});
ids.vId11 = vertex._id;
vertex = g[vc1].save({first_name: "Tem", age : 20});
ids.vId12 = vertex._id;
vertex = g[vc1].save({first_name: "Tim"});
ids.vId13 = vertex._id;
vertex = g[vc1].save({first_name: "Tom"});
ids.vId14 = vertex._id;
vertex = g[vc1].save({first_name: "Tum"});
ids.vId15 = vertex._id;
vertex = g[vc3].save({first_name: "Tam"});
ids.vId31 = vertex._id;
vertex = g[vc3].save({first_name: "Tem"});
ids.vId32 = vertex._id;
vertex = g[vc3].save({first_name: "Tim", age : 24});
ids.vId33 = vertex._id;
vertex = g[vc3].save({first_name: "Tom"});
ids.vId34 = vertex._id;
vertex = g[vc3].save({first_name: "Tum"});
ids.vId35 = vertex._id;
var edge = g[ec1].save(ids.vId11, ids.vId12, {});
ids.eId11 = edge._id;
edge = g[ec1].save(ids.vId11, ids.vId13, {});
ids.eId12 = edge._id;
edge = g[ec1].save(ids.vId11, ids.vId14, {});
ids.eId13 = edge._id;
edge = g[ec1].save(ids.vId11, ids.vId15, {});
ids.eId14 = edge._id;
edge = g[ec1].save(ids.vId12, ids.vId11, {});
ids.eId15 = edge._id;
edge = g[ec1].save(ids.vId13, ids.vId11, {});
ids.eId16 = edge._id;
edge = g[ec1].save(ids.vId14, ids.vId11, {});
ids.eId17 = edge._id;
edge = g[ec1].save(ids.vId15, ids.vId11, {});
ids.eId18 = edge._id;
edge = g[ec2].save(ids.vId11, ids.vId31, {});
ids.eId21 = edge._id;
edge = g[ec2].save(ids.vId11, ids.vId32, {});
ids.eId22 = edge._id;
edge = g[ec2].save(ids.vId11, ids.vId33, {});
ids.eId23 = edge._id;
edge = g[ec2].save(ids.vId11, ids.vId34, {});
ids.eId24 = edge._id;
edge = g[ec2].save(ids.vId11, ids.vId35, {});
ids.eId25 = edge._id;
return ids;
};
return {
setUp : function() {
g = graph._create(
unitTestGraphName,
graph._edgeDefinitions(
graph._undirectedRelation(ec1, vc1),
graph._directedRelation(ec2,
[vc1, vc2], [vc3, vc4]
)
)
);
fillCollections();
},
tearDown : function() {
try {
graph._drop(unitTestGraphName, true);
} catch (e) {
}
},
test_absoluteEccentricity : function () {
var a = g._absoluteEccentricity({});
assertEqual(Object.keys(a[0]).length , 10);
},
test_eccentricity : function () {
var a = g._eccentricity({});
assertEqual(Object.keys(a[0]).length , 10);
},
test_absoluteCloseness : function () {
var a = g._absoluteCloseness({});
assertEqual(Object.keys(a[0]).length , 10);
},
test_closeness : function () {
var a = g._closeness({});
assertEqual(Object.keys(a[0]).length , 10);
},
test_absoluteBetweenness : function () {
var a = g._absoluteBetweenness({});
assertEqual(Object.keys(a[0]).length , 10);
},
test_betweenness : function () {
var a = g._betweenness({});
assertEqual(Object.keys(a[0]).length , 10);
},
test_radius : function () {
var a = g._radius({});
assertEqual(a[0] , 1);
},
test_diameter : function () {
var a = g._diameter({});
assertEqual(a[0] , 2);
},
test_paths : function () {
var a = g._paths({maxLength : 2});
assertEqual(a[0].length , 50);
},
test_shortestPaths : function () {
var a = g._shortestPath([{first_name: 'Tim',age : 24}, {first_name: 'Tom'}], [{first_name: 'Tam'}, {first_name: 'Tem',age : 20}]);
assertEqual(a[0].length , 9);
},
test_distanceTo : function () {
var a = g._distanceTo([{first_name: 'Tim',age : 24}, {first_name: 'Tom'}], [{first_name: 'Tam'}, {first_name: 'Tem' ,age : 20}]);
assertEqual(a[0].length , 9);
}
};
}
// -----------------------------------------------------------------------------
// --SECTION-- main
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////
jsunity.run(GeneralGraphCommonNeighborsSuite);
jsunity.run(GeneralGraphAQLQueriesSuite);
jsunity.run(EdgesAndVerticesSuite);
jsunity.run(GeneralGraphCreationSuite);
jsunity.run(ChainedFluentAQLResultsSuite);
jsunity.run(OrphanCollectionSuite);
jsunity.run(MeasurementsSuite);
return jsunity.done();
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
|
masgyw/individual-study
|
glearn/algorithm/src/main/java/cn/gyw/glearn/algorithm/arrays/UpsetAnArray.java
|
<filename>glearn/algorithm/src/main/java/cn/gyw/glearn/algorithm/arrays/UpsetAnArray.java
package cn.gyw.glearn.algorithm.arrays;
/**
* 打乱一个数组
*
*/
public class UpsetAnArray {
}
|
mtunganati/oneops
|
display/app/models/transistor.rb
|
<filename>display/app/models/transistor.rb
class Transistor < ActiveResource::Base
self.site = Settings.transistor_site
self.prefix = '/transistor/rest'
self.element_name = ''
self.include_format_in_path = false
self.timeout = Settings.transistor_http_timeout
def self.export_design(assembly, platform_ids = nil)
begin
return get("assemblies/#{assembly.ciId}/export#{"?#{platform_ids.map {|i| "platformIds=#{i}"}.join('&')}" if platform_ids.present?}")
rescue Exception => e
return nil, handle_exception(e, "Failed to export design for assembly #{assembly.ciId} :")
end
end
def self.import_design(assembly, design)
begin
return JSON.parse(post("assemblies/#{assembly.ciId}/import", {}, design.to_json).body)['result'] == 'success'
rescue Exception => e
return false, handle_exception(e, 'Failed to import design:')
end
end
def self.export_environment(env, platform_ids = nil)
begin
return get("environments/#{env.ciId}/export#{"?#{platform_ids.map {|i| "platformIds=#{i}"}.join('&')}" if platform_ids.present?}")
rescue Exception => e
return nil, handle_exception(e, "Failed to export environment #{env.ciId} :")
end
end
def self.import_environment(env, data)
begin
return JSON.parse(post("environments/#{env.ciId}/import", {}, data.to_json).body)['result'] == 'success'
rescue Exception => e
return false, handle_exception(e, 'Failed to import environment:')
end
end
def self.export_catalog(design_id)
get("catalogs/#{design_id}/export")
end
def self.import_catalog(data)
id = nil
begin
id = JSON.parse(post('catalogs/import', {}, data.to_json).body)['catalogCiId']
rescue Exception => e
handle_exception e, 'Failed to import catalog:'
end
return id
end
def self.create_assembly_from_catalog(design_id, assembly_ci)
id = nil
begin
id = JSON.parse(post("catalogs/#{design_id}/assemblies", {}, assembly_ci.to_json).body)['resultCiId']
rescue Exception => e
handle_exception e, "Failed to create assembly [#{assembly_ci}] from catalog '#{design_id}'"
end
return id
end
def self.clone_assembly(assembly_id, ci)
id = nil
begin
id = JSON.parse(post("assemblies/#{assembly_id}/clone", {}, ci.attributes.to_json).body)['resultCiId']
rescue Exception => e
message = handle_exception e, "Failed to clone assembly '#{assembly_id}'"
return nil, message
end
return id
end
def self.design_platform_rfcs(platform_id, opts = {})
begin
rfcs = get("platforms/#{platform_id}/rfcs", opts)
rfcs['cis'] = rfcs['cis'].map {|rfc| Cms::RfcCi.new(rfc, true)}
rfcs['relations'] = rfcs['relations'].map {|rfc| Cms::RfcRelation.new(rfc, true)}
return rfcs
rescue Exception => e
message = handle_exception(e, "Failed to fetch platform RFCs in design for '#{platform_id}'.")
return nil, message
end
end
def self.commit_design_platform_rfcs(platform_id, desc = '')
begin
return JSON.parse(put("platforms/#{platform_id}/rfcs/commit", {}, {:desc => desc}.to_json).body)['releaseId']
rescue Exception => e
message = handle_exception(e, "Failed to commit platform RFCs in design for '#{platform_id}'.")
return nil, message
end
end
def self.discard_design_platform_rfcs(platform_id)
begin
return JSON.parse(put("platforms/#{platform_id}/rfcs/discard", {}).body)['releaseId']
rescue Exception => e
message = handle_exception(e, "Failed to discard platform RFCs in design for '#{platform_id}'.")
return nil, message
end
end
def self.pack_refresh(platform_id)
begin
return JSON.parse(put("platforms/#{platform_id}/pack_refresh", {}).body)['releaseId']
rescue Exception => e
message = handle_exception(e, "Failed to peform pack refresh for platform '#{platform_id}'.")
return nil, message
end
end
def self.pack_update(platform_id, version)
begin
return JSON.parse(put("platforms/#{platform_id}/packs/versions/#{version}", {}).body)['releaseId']
rescue Exception => e
message = handle_exception(e, "Failed to peform pack update for platform '#{platform_id}', version '#{version}'.")
return nil, message
end
end
def self.pull_design(environent_id, platform_availability = {})
begin
return JSON.parse(put("environments/#{environent_id}", {}, platform_availability.to_json).body)['releaseId']
rescue Exception => e
message = handle_exception(e, "Failed to pull design for environment '#{environent_id}'")
return nil, message
end
end
def self.generate_bom(environent_id, description, commit, exclude = '')
begin
params = {:description => description}
params[:exclude] = exclude if exclude.present?
params[:commit] = 'false' unless commit
exit_code = JSON.parse(post("environments/#{environent_id}/deployments", {}, params.to_json).body)['exit_code']
return exit_code == 0
rescue Exception => e
message = handle_exception(e, "Failed to commmit for environment '#{environent_id}'")
return nil, message
end
end
def self.deploy(environent_id, deployment, exclude)
begin
params = {:deployment => deployment, :exclude => exclude}
exit_code = JSON.parse(post("environments/#{environent_id}/deploy", {}, params.to_json).body)['exit_code']
return exit_code == 0
rescue Exception => e
message = handle_exception(e, "Failed to deploy environment '#{environent_id}' with #{deployment}.")
return nil, message
end
end
def self.preview_bom(environent_id, opts = {:commit => false})
begin
data = JSON.parse(post("environments/#{environent_id}/deployments/preview", {}, opts.to_json).body)
release = data['release']
data['release'] = Cms::ReleaseBom.new(release) if release
rfcs = data['rfcs']
if rfcs
cis = rfcs['cis']
rfcs['cis'] = cis ? cis.map {|rfc| Cms::RfcCi.new(rfc, true)} : []
relations = rfcs['relations']
rfcs['relations'] = relations ? relations.map {|rfc| Cms::RfcRelation.new(rfc, true)} : []
else
data['rfcs'] = {'cis' => [], 'relations' => []}
end
return data, nil
rescue Exception => e
message = handle_exception(e, "Failed to preview bom for environment '#{environent_id}'")
return nil, message
end
end
def self.discard_manifest(environent_id)
begin
return JSON.parse(put("environments/#{environent_id}/manifest/discard", {}, {}.to_json).body)['releaseId']
rescue Exception => e
message = handle_exception(e, "Failed to discard manifest release for environment '#{environent_id}'")
return nil, message
end
end
def self.discard_bom(environent_id)
begin
return JSON.parse(put("environments/#{environent_id}/bom/discard", {}, {}.to_json).body)['releaseId']
rescue Exception => e
message = handle_exception(e, "Failed to discard bom for environment '#{environent_id}'")
return nil, message
end
end
def self.create_platform(assembly_id, platform_ci)
platform = platform_ci
if platform_ci.valid?
begin
platform_id = JSON.parse(post("assemblies/#{assembly_id}/platforms", {}, platform_ci.to_json).body)['platformCiId']
platform = Cms::DjCi.find(platform_id)
rescue Exception => e
error = handle_exception(e, "Failed to create platform [#{platform_ci.inspect}] for assembly '#{assembly_id}'")
platform_ci.errors.add(:base, error)
end
end
return platform
end
def self.create_component(platform_id, requires_rel)
result = requires_rel
if requires_rel.valid?
begin
data = JSON.parse(post("platforms/#{platform_id}/components", {}, requires_rel.to_json).body)
result = Cms::DjRelation.new(data, true)
rescue Exception => e
error = handle_exception(e, "Failed to create component [#{requires_rel.inspect}] for platform '#{platform_id}'.")
result.errors.add(:base, error)
result.toCi.errors.add(:base, error)
end
else
Rails.logger.info "Create component validation failed: #{requires_rel.errors.full_messages}; #{requires_rel.toCi.errors.full_messages}"
end
return result
end
def self.clone_platform(platform_id, platform_ci)
new_platform_id = nil
begin
new_platform_id = JSON.parse(post("platforms/#{platform_id}/clone", {}, platform_ci.to_json).body)['platformCiId']
rescue Exception => e
handle_exception e, "Failed to clone platform '#{platform_id}' to new platform [#{platform_ci}]"
end
return new_platform_id
end
def self.delete_platform(assembly_id, platform_ci)
deleted_platform_id = nil
begin
deleted_platform_id = JSON.parse(delete("assemblies/#{assembly_id}/platforms/#{platform_ci.ciId}", {}).body)['platformCiId']
rescue Exception => e
error = handle_exception e, "Failed to delete platform [#{platform_ci.inspect}] for assembly '#{assembly_id}'"
platform_ci.errors.add(:base, error)
end
return deleted_platform_id
end
def self.activate_platform(platform_id)
id = nil
begin
id = JSON.parse(put("platforms/#{platform_id}/activate", {}).body)['releaseId']
rescue Exception => e
handle_exception e, "Failed to activate platform '#{platform_id}'"
end
return id
end
def self.toggle_platforms(platform_ids, enable)
action = enable ? 'enable' : 'disable'
payload = { platforms: platform_ids.join(",") }
begin
release_id = JSON.parse(put("platforms/#{action}", {}, payload.to_json ).body)['releaseId']
rescue Exception => e
message = handle_exception e, "Failed to #{enable} platforms #{payload[:platforms]}"
return nil, message
end
return release_id
end
def self.toggle_platform(platform, enable)
id = nil
platform_id = platform.ciId
action = enable ? 'enable' : 'disable'
begin
id = JSON.parse(put("platforms/#{platform_id}/#{action}", {}).body)['releaseId']
rescue Exception => e
platform.errors.add(:base, handle_exception(e, "Failed to #{action} platform '#{platform_id}'"))
end
return id
end
def self.set_environment_clouds(environment_id, cloud_rels)
release_id = nil
begin
release_id = JSON.parse(put("environments/#{environment_id}/clouds", {}, cloud_rels.to_json).body)['releaseId']
rescue Exception => e
message = handle_exception e, "Failed to set clouds for environment: '#{environment_id}'"
return nil, message
end
return release_id
end
def self.update_platform_cloud(platform_id, cloud_rel)
result = nil
begin
result = JSON.parse(put("platforms/#{platform_id}/clouds", {}, cloud_rel.to_json).body)['result']
rescue Exception => e
handle_exception e, "Failed to update cloud for platform: '#{platform_id}'"
end
return result
end
def self.restore_release(snapshot, release_id)
begin
response = JSON.parse(post('snapshot/import', {:release => release_id}, snapshot.to_json).body)
return response['result'] == 'success', response['errors']
rescue Exception => e
return false, handle_exception(e, "Failed to restore release #{release_id} for '#{snapshot['namespace'] if snapshot}':")
end
end
def self.environment_cost(env, pending = false, details = false)
begin
return get("environments/#{env.respond_to?(:ciId) ? env.ciId : env}/#{'estimated_' if pending}cost#{'_data' if details}"), nil
rescue Exception => e
return nil, handle_exception(e, "Failed to get cost for environment #{env.ciId} :")
end
end
private
def self.handle_exception(exception, message)
body = nil
error_message = exception.message
if exception.respond_to?(:response) && exception.response.body
begin
body = JSON.parse(exception.response.body)
error_message = body['message']
Rails.logger.warn "#{message}: #{"[#{body['code']} - #{error_message}]"}"
rescue Exception => e
Rails.logger.warn "#{message}: #{error_message}"
end
else
Rails.logger.warn "#{message}: #{error_message}"
end
return error_message
end
end
|
SonicRoshan/Velocity
|
global/clients/email_verification_client.go
|
<gh_stars>1-10
package clients
import (
"context"
"github.com/SonicRoshan/Velocity/global/config"
proto "github.com/SonicRoshan/Velocity/services/email-verification-srv/proto"
micro "github.com/micro/go-micro"
"github.com/pkg/errors"
)
//NewEmailVerificationClient is used to make a email verification Client
func NewEmailVerificationClient(service micro.Service) EmailVerificationClient {
client := EmailVerificationClient{}
client.Init(service)
return client
}
//EmailVerificationClient is jwt service client
type EmailVerificationClient struct {
client proto.EmailVerificationService
}
//Init initializes cliet
func (emailVerificationClient *EmailVerificationClient) Init(service micro.Service) {
emailVerificationClient.client = proto.NewEmailVerificationService(config.EmailVerificationSrv, service.Client())
}
//SendVerification is used to send verification email to a user
func (emailVerificationClient EmailVerificationClient) SendVerification(email string) error {
request := proto.SendVerificationRequest{
Email: email,
}
_, err := emailVerificationClient.client.SendVerification(context.TODO(), &request)
if err != nil {
return errors.Wrap(err, "Error While Sending Verification Through Client")
}
return nil
}
//Verify is used to verify verification code
func (emailVerificationClient EmailVerificationClient) Verify(code string) (string, error) {
request := proto.VerifyRequest{
VerificationCode: code,
}
response, err := emailVerificationClient.client.Verify(context.TODO(), &request)
if err != nil {
return "", errors.Wrap(err, "Error While Verifying Code Through Client")
}
return response.Email, nil
}
|
efiring/GSW-C
|
toolbox/gsw_t_freezing_first_derivatives_poly.c
|
/*
!==========================================================================
elemental subroutine gsw_t_freezing_first_derivatives_poly (sa, p, &
saturation_fraction, tfreezing_sa, tfreezing_p)
!==========================================================================
!
! Calculates the first derivatives of the in-situ temperature at which
! seawater freezes with respect to Absolute Salinity SA and pressure P (in
! Pa). These expressions come from differentiating the expression that
! defines the freezing temperature, namely the equality between the
! chemical potentials of water in seawater and in ice.
!
! SA = Absolute Salinity [ g/kg ]
! p = sea pressure [ dbar ]
! ( i.e. absolute pressure - 10.1325 dbar )
! saturation_fraction = the saturation fraction of dissolved air in
! seawater
!
! tfreezing_SA = the derivative of the in-situ freezing temperature
! (ITS-90) with respect to Absolute Salinity at fixed
! pressure [ K/(g/kg) ] i.e. [ K kg/g ]
!
! tfreezing_P = the derivative of the in-situ freezing temperature
! (ITS-90) with respect to pressure (in Pa) at fixed
! Absolute Salinity [ K/Pa ]
!--------------------------------------------------------------------------
*/
void
gsw_t_freezing_first_derivatives_poly(double sa, double p,
double saturation_fraction, double *tfreezing_sa, double *tfreezing_p)
{
GSW_TEOS10_CONSTANTS;
GSW_FREEZING_POLY_COEFFICIENTS;
double p_r, sa_r, x, c = 1e-3/(2.0*gsw_sso);
sa_r = sa*1e-2;
x = sqrt(sa_r);
p_r = p*1e-4;
if (tfreezing_sa != NULL)
*tfreezing_sa =
(t1 + x*(1.5*t2 + x*(2.0*t3 + x*(2.5*t4 + x*(3.0*t5
+ 3.5*t6*x)))) + p_r*(t10 + x*(1.5*t11 + x*(2.0*t13
+ x*(2.5*t16 + x*(3.0*t19 + 3.5*t22*x))))
+ p_r*(t12 + x*(1.5*t14 + x*(2.0*t17 + 2.5*t20*x))
+ p_r*(t15 + x*(1.5*t18 + 2.0*t21*x)))))*1e-2
+ saturation_fraction*c;
if (tfreezing_p != NULL)
*tfreezing_p =
(t7 + sa_r*(t10 + x*(t11 + x*(t13 + x*(t16 + x*(t19 + t22*x)))))
+ p_r*(2.0*t8 + sa_r*(2.0*t12 + x*(2.0*t14 + x*(2.0*t17
+ 2.0*t20*x))) + p_r*(3.0*t9 + sa_r*(3.0*t15 + x*(3.0*t18
+ 3.0*t21*x)))))*1e-8;
return;
}
|
AaronFriel/pulumi-google-native
|
sdk/python/pulumi_google_native/websecurityscanner/v1/_inputs.py
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from ._enums import *
__all__ = [
'AuthenticationArgs',
'CustomAccountArgs',
'GoogleAccountArgs',
'IapCredentialArgs',
'IapTestServiceAccountInfoArgs',
'ScheduleArgs',
]
@pulumi.input_type
class AuthenticationArgs:
def __init__(__self__, *,
custom_account: Optional[pulumi.Input['CustomAccountArgs']] = None,
google_account: Optional[pulumi.Input['GoogleAccountArgs']] = None,
iap_credential: Optional[pulumi.Input['IapCredentialArgs']] = None):
"""
Scan authentication configuration.
:param pulumi.Input['CustomAccountArgs'] custom_account: Authentication using a custom account.
:param pulumi.Input['GoogleAccountArgs'] google_account: Authentication using a Google account.
:param pulumi.Input['IapCredentialArgs'] iap_credential: Authentication using Identity-Aware-Proxy (IAP).
"""
if custom_account is not None:
pulumi.set(__self__, "custom_account", custom_account)
if google_account is not None:
pulumi.set(__self__, "google_account", google_account)
if iap_credential is not None:
pulumi.set(__self__, "iap_credential", iap_credential)
@property
@pulumi.getter(name="customAccount")
def custom_account(self) -> Optional[pulumi.Input['CustomAccountArgs']]:
"""
Authentication using a custom account.
"""
return pulumi.get(self, "custom_account")
@custom_account.setter
def custom_account(self, value: Optional[pulumi.Input['CustomAccountArgs']]):
pulumi.set(self, "custom_account", value)
@property
@pulumi.getter(name="googleAccount")
def google_account(self) -> Optional[pulumi.Input['GoogleAccountArgs']]:
"""
Authentication using a Google account.
"""
return pulumi.get(self, "google_account")
@google_account.setter
def google_account(self, value: Optional[pulumi.Input['GoogleAccountArgs']]):
pulumi.set(self, "google_account", value)
@property
@pulumi.getter(name="iapCredential")
def iap_credential(self) -> Optional[pulumi.Input['IapCredentialArgs']]:
"""
Authentication using Identity-Aware-Proxy (IAP).
"""
return pulumi.get(self, "iap_credential")
@iap_credential.setter
def iap_credential(self, value: Optional[pulumi.Input['IapCredentialArgs']]):
pulumi.set(self, "iap_credential", value)
@pulumi.input_type
class CustomAccountArgs:
def __init__(__self__, *,
login_url: pulumi.Input[str],
password: <PASSWORD>[str],
username: pulumi.Input[str]):
"""
Describes authentication configuration that uses a custom account.
:param pulumi.Input[str] login_url: The login form URL of the website.
:param pulumi.Input[str] password: Input only. The password of the custom account. The credential is stored encrypted and not returned in any response nor included in audit logs.
:param pulumi.Input[str] username: The user name of the custom account.
"""
pulumi.set(__self__, "login_url", login_url)
pulumi.set(__self__, "password", password)
pulumi.set(__self__, "username", username)
@property
@pulumi.getter(name="loginUrl")
def login_url(self) -> pulumi.Input[str]:
"""
The login form URL of the website.
"""
return pulumi.get(self, "login_url")
@login_url.setter
def login_url(self, value: pulumi.Input[str]):
pulumi.set(self, "login_url", value)
@property
@pulumi.getter
def password(self) -> pulumi.Input[str]:
"""
Input only. The password of the custom account. The credential is stored encrypted and not returned in any response nor included in audit logs.
"""
return pulumi.get(self, "password")
@password.setter
def password(self, value: pulumi.Input[str]):
pulumi.set(self, "password", value)
@property
@pulumi.getter
def username(self) -> pulumi.Input[str]:
"""
The user name of the custom account.
"""
return pulumi.get(self, "username")
@username.setter
def username(self, value: pulumi.Input[str]):
pulumi.set(self, "username", value)
@pulumi.input_type
class GoogleAccountArgs:
def __init__(__self__, *,
password: pulumi.Input[str],
username: pulumi.Input[str]):
"""
Describes authentication configuration that uses a Google account.
:param pulumi.Input[str] password: Input only. The password of the Google account. The credential is stored encrypted and not returned in any response nor included in audit logs.
:param pulumi.Input[str] username: The user name of the Google account.
"""
pulumi.set(__self__, "password", password)
pulumi.set(__self__, "username", username)
@property
@pulumi.getter
def password(self) -> pulumi.Input[str]:
"""
Input only. The password of the Google account. The credential is stored encrypted and not returned in any response nor included in audit logs.
"""
return pulumi.get(self, "password")
@password.setter
def password(self, value: pulumi.Input[str]):
pulumi.set(self, "password", value)
@property
@pulumi.getter
def username(self) -> pulumi.Input[str]:
"""
The user name of the Google account.
"""
return pulumi.get(self, "username")
@username.setter
def username(self, value: pulumi.Input[str]):
pulumi.set(self, "username", value)
@pulumi.input_type
class IapCredentialArgs:
def __init__(__self__, *,
iap_test_service_account_info: Optional[pulumi.Input['IapTestServiceAccountInfoArgs']] = None):
"""
Describes authentication configuration for Identity-Aware-Proxy (IAP).
:param pulumi.Input['IapTestServiceAccountInfoArgs'] iap_test_service_account_info: Authentication configuration when Web-Security-Scanner service account is added in Identity-Aware-Proxy (IAP) access policies.
"""
if iap_test_service_account_info is not None:
pulumi.set(__self__, "iap_test_service_account_info", iap_test_service_account_info)
@property
@pulumi.getter(name="iapTestServiceAccountInfo")
def iap_test_service_account_info(self) -> Optional[pulumi.Input['IapTestServiceAccountInfoArgs']]:
"""
Authentication configuration when Web-Security-Scanner service account is added in Identity-Aware-Proxy (IAP) access policies.
"""
return pulumi.get(self, "iap_test_service_account_info")
@iap_test_service_account_info.setter
def iap_test_service_account_info(self, value: Optional[pulumi.Input['IapTestServiceAccountInfoArgs']]):
pulumi.set(self, "iap_test_service_account_info", value)
@pulumi.input_type
class IapTestServiceAccountInfoArgs:
def __init__(__self__, *,
target_audience_client_id: pulumi.Input[str]):
"""
Describes authentication configuration when Web-Security-Scanner service account is added in Identity-Aware-Proxy (IAP) access policies.
:param pulumi.Input[str] target_audience_client_id: Describes OAuth2 client id of resources protected by Identity-Aware-Proxy (IAP).
"""
pulumi.set(__self__, "target_audience_client_id", target_audience_client_id)
@property
@pulumi.getter(name="targetAudienceClientId")
def target_audience_client_id(self) -> pulumi.Input[str]:
"""
Describes OAuth2 client id of resources protected by Identity-Aware-Proxy (IAP).
"""
return pulumi.get(self, "target_audience_client_id")
@target_audience_client_id.setter
def target_audience_client_id(self, value: pulumi.Input[str]):
pulumi.set(self, "target_audience_client_id", value)
@pulumi.input_type
class ScheduleArgs:
def __init__(__self__, *,
interval_duration_days: pulumi.Input[int],
schedule_time: Optional[pulumi.Input[str]] = None):
"""
Scan schedule configuration.
:param pulumi.Input[int] interval_duration_days: The duration of time between executions in days.
:param pulumi.Input[str] schedule_time: A timestamp indicates when the next run will be scheduled. The value is refreshed by the server after each run. If unspecified, it will default to current server time, which means the scan will be scheduled to start immediately.
"""
pulumi.set(__self__, "interval_duration_days", interval_duration_days)
if schedule_time is not None:
pulumi.set(__self__, "schedule_time", schedule_time)
@property
@pulumi.getter(name="intervalDurationDays")
def interval_duration_days(self) -> pulumi.Input[int]:
"""
The duration of time between executions in days.
"""
return pulumi.get(self, "interval_duration_days")
@interval_duration_days.setter
def interval_duration_days(self, value: pulumi.Input[int]):
pulumi.set(self, "interval_duration_days", value)
@property
@pulumi.getter(name="scheduleTime")
def schedule_time(self) -> Optional[pulumi.Input[str]]:
"""
A timestamp indicates when the next run will be scheduled. The value is refreshed by the server after each run. If unspecified, it will default to current server time, which means the scan will be scheduled to start immediately.
"""
return pulumi.get(self, "schedule_time")
@schedule_time.setter
def schedule_time(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "schedule_time", value)
|
wandora-team/zmpp-wandora
|
src/org/zmpp/encoding/AlphabetTableV2.java
|
/*
* $Id: AlphabetTableV2.java 536 2008-02-19 06:03:27Z weiju $
*
* Created on 2006/01/18
* Copyright 2005-2008 by <NAME>
* This file is part of The Z-machine Preservation Project (ZMPP).
*
* ZMPP 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.
*
* ZMPP 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 ZMPP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.zmpp.encoding;
/**
* An alphabet table in a V2 story file behaves "almost like" the default
* alphabet table, in that they have the same characters in the alphabets. There
* are however two differences: It only supports one abbreviation code and it
* supports shift-lock.
*
* @author <NAME>
* @version 1.0
*/
public class AlphabetTableV2 extends DefaultAlphabetTable {
/**
* {@inheritDoc}
*/
public boolean isAbbreviation(final char zchar) {
return zchar == 1;
}
/**
* {@inheritDoc}
*/
public boolean isShift1(final char zchar) {
return zchar == SHIFT_2 || zchar == SHIFT_4;
}
/**
* {@inheritDoc}
*/
public boolean isShift2(final char zchar) {
return zchar == SHIFT_3 || zchar == SHIFT_5;
}
/**
* {@inheritDoc}
*/
public boolean isShiftLock(final char zchar) {
return zchar == SHIFT_4 || zchar == SHIFT_5;
}
}
|
ChanTerelLy/partnerweb3
|
tickets_handler/management/commands/show_sessions.py
|
<gh_stars>0
from django.contrib.sessions.models import Session
from django.core.management.base import BaseCommand, CommandError
from urllib.parse import unquote
class Command(BaseCommand):
help = 'Decode all active sessions'
def handle(self, *args, **options):
sessions = Session.objects.all()
for session in sessions:
uid = unquote(str(session.get_decoded()))
self.stdout.write(self.style.SUCCESS(uid))
|
iliacimpoes/aws-sdk-go-v2
|
service/efs/api_op_CreateFileSystem.go
|
<filename>service/efs/api_op_CreateFileSystem.go
// Code generated by smithy-go-codegen DO NOT EDIT.
package efs
import (
"context"
"fmt"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/service/efs/types"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
"time"
)
// Creates a new, empty file system. The operation requires a creation token in the
// request that Amazon EFS uses to ensure idempotent creation (calling the
// operation with same creation token has no effect). If a file system does not
// currently exist that is owned by the caller's AWS account with the specified
// creation token, this operation does the following:
//
// * Creates a new, empty file
// system. The file system will have an Amazon EFS assigned ID, and an initial
// lifecycle state creating.
//
// * Returns with the description of the created file
// system.
//
// Otherwise, this operation returns a FileSystemAlreadyExists error with
// the ID of the existing file system. For basic use cases, you can use a randomly
// generated UUID for the creation token. The idempotent operation allows you to
// retry a CreateFileSystem call without risk of creating an extra file system.
// This can happen when an initial call fails in a way that leaves it uncertain
// whether or not a file system was actually created. An example might be that a
// transport level timeout occurred or your connection was reset. As long as you
// use the same creation token, if the initial call had succeeded in creating a
// file system, the client can learn of its existence from the
// FileSystemAlreadyExists error. For more information, see Creating a file system
// (https://docs.aws.amazon.com/efs/latest/ug/creating-using-create-fs.html#creating-using-create-fs-part1)
// in the Amazon EFS User Guide. The CreateFileSystem call returns while the file
// system's lifecycle state is still creating. You can check the file system
// creation status by calling the DescribeFileSystems operation, which among other
// things returns the file system state. This operation accepts an optional
// PerformanceMode parameter that you choose for your file system. We recommend
// generalPurpose performance mode for most file systems. File systems using the
// maxIO performance mode can scale to higher levels of aggregate throughput and
// operations per second with a tradeoff of slightly higher latencies for most file
// operations. The performance mode can't be changed after the file system has been
// created. For more information, see Amazon EFS performance modes
// (https://docs.aws.amazon.com/efs/latest/ug/performance.html#performancemodes.html).
// You can set the throughput mode for the file system using the ThroughputMode
// parameter. After the file system is fully created, Amazon EFS sets its lifecycle
// state to available, at which point you can create one or more mount targets for
// the file system in your VPC. For more information, see CreateMountTarget. You
// mount your Amazon EFS file system on an EC2 instances in your VPC by using the
// mount target. For more information, see Amazon EFS: How it Works
// (https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html). This operation
// requires permissions for the elasticfilesystem:CreateFileSystem action.
func (c *Client) CreateFileSystem(ctx context.Context, params *CreateFileSystemInput, optFns ...func(*Options)) (*CreateFileSystemOutput, error) {
if params == nil {
params = &CreateFileSystemInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateFileSystem", params, optFns, addOperationCreateFileSystemMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateFileSystemOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateFileSystemInput struct {
// A string of up to 64 ASCII characters. Amazon EFS uses this to ensure idempotent
// creation.
//
// This member is required.
CreationToken *string
// Used to create a file system that uses One Zone storage classes. It specifies
// the AWS Availability Zone in which to create the file system. Use the format
// us-east-1a to specify the Availability Zone. For more information about One Zone
// storage classes, see Using EFS storage classes
// (https://docs.aws.amazon.com/efs/latest/ug/storage-classes.html) in the Amazon
// EFS User Guide. One Zone storage classes are not available in all Availability
// Zones in AWS Regions where Amazon EFS is available.
AvailabilityZoneName *string
// Specifies whether automatic backups are enabled on the file system that you are
// creating. Set the value to true to enable automatic backups. If you are creating
// a file system that uses One Zone storage classes, automatic backups are enabled
// by default. For more information, see Automatic backups
// (https://docs.aws.amazon.com/efs/latest/ug/awsbackup.html#automatic-backups) in
// the Amazon EFS User Guide. Default is false. However, if you specify an
// AvailabilityZoneName, the default is true. AWS Backup is not available in all
// AWS Regions where Amazon EFS is available.
Backup *bool
// A Boolean value that, if true, creates an encrypted file system. When creating
// an encrypted file system, you have the option of specifying
// CreateFileSystemRequest$KmsKeyId for an existing AWS Key Management Service (AWS
// KMS) customer master key (CMK). If you don't specify a CMK, then the default CMK
// for Amazon EFS, /aws/elasticfilesystem, is used to protect the encrypted file
// system.
Encrypted *bool
// The ID of the AWS KMS CMK that you want to use to protect the encrypted file
// system. This parameter is only required if you want to use a non-default KMS
// key. If this parameter is not specified, the default CMK for Amazon EFS is used.
// This ID can be in one of the following formats:
//
// * Key ID - A unique identifier
// of the key, for example 1234abcd-12ab-34cd-56ef-1234567890ab.
//
// * ARN - An Amazon
// Resource Name (ARN) for the key, for example
// arn:aws:kms:us-west-2:111122223333:key/<KEY>.
//
// *
// Key alias - A previously created display name for a key, for example
// alias/projectKey1.
//
// * Key alias ARN - An ARN for a key alias, for example
// arn:aws:kms:us-west-2:444455556666:alias/projectKey1.
//
// If KmsKeyId is specified,
// the CreateFileSystemRequest$Encrypted parameter must be set to true. EFS accepts
// only symmetric KMS keys. You cannot use asymmetric KMS keys with EFS file
// systems.
KmsKeyId *string
// The performance mode of the file system. We recommend generalPurpose performance
// mode for most file systems. File systems using the maxIO performance mode can
// scale to higher levels of aggregate throughput and operations per second with a
// tradeoff of slightly higher latencies for most file operations. The performance
// mode can't be changed after the file system has been created. The maxIO mode is
// not supported on file systems using One Zone storage classes.
PerformanceMode types.PerformanceMode
// The throughput, measured in MiB/s, that you want to provision for a file system
// that you're creating. Valid values are 1-1024. Required if ThroughputMode is set
// to provisioned. The upper limit for throughput is 1024 MiB/s. To increase this
// limit, contact AWS Support. For more information, see Amazon EFS quotas that you
// can increase (https://docs.aws.amazon.com/efs/latest/ug/limits.html#soft-limits)
// in the Amazon EFS User Guide.
ProvisionedThroughputInMibps *float64
// A value that specifies to create one or more tags associated with the file
// system. Each tag is a user-defined key-value pair. Name your file system on
// creation by including a "Key":"Name","Value":"{value}" key-value pair.
Tags []types.Tag
// Specifies the throughput mode for the file system, either bursting or
// provisioned. If you set ThroughputMode to provisioned, you must also set a value
// for ProvisionedThroughputInMibps. After you create the file system, you can
// decrease your file system's throughput in Provisioned Throughput mode or change
// between the throughput modes, as long as it’s been more than 24 hours since the
// last decrease or throughput mode change. For more information, see Specifying
// throughput with provisioned mode
// (https://docs.aws.amazon.com/efs/latest/ug/performance.html#provisioned-throughput)
// in the Amazon EFS User Guide. Default is bursting.
ThroughputMode types.ThroughputMode
}
// A description of the file system.
type CreateFileSystemOutput struct {
// The time that the file system was created, in seconds (since
// 1970-01-01T00:00:00Z).
//
// This member is required.
CreationTime *time.Time
// The opaque string specified in the request.
//
// This member is required.
CreationToken *string
// The ID of the file system, assigned by Amazon EFS.
//
// This member is required.
FileSystemId *string
// The lifecycle phase of the file system.
//
// This member is required.
LifeCycleState types.LifeCycleState
// The current number of mount targets that the file system has. For more
// information, see CreateMountTarget.
//
// This member is required.
NumberOfMountTargets int32
// The AWS account that created the file system. If the file system was created by
// an IAM user, the parent account to which the user belongs is the owner.
//
// This member is required.
OwnerId *string
// The performance mode of the file system.
//
// This member is required.
PerformanceMode types.PerformanceMode
// The latest known metered size (in bytes) of data stored in the file system, in
// its Value field, and the time at which that size was determined in its Timestamp
// field. The Timestamp value is the integer number of seconds since
// 1970-01-01T00:00:00Z. The SizeInBytes value doesn't represent the size of a
// consistent snapshot of the file system, but it is eventually consistent when
// there are no writes to the file system. That is, SizeInBytes represents actual
// size only if the file system is not modified for a period longer than a couple
// of hours. Otherwise, the value is not the exact size that the file system was at
// any point in time.
//
// This member is required.
SizeInBytes *types.FileSystemSize
// The tags associated with the file system, presented as an array of Tag objects.
//
// This member is required.
Tags []types.Tag
// The unique and consistent identifier of the Availability Zone in which the file
// system's One Zone storage classes exist. For example, use1-az1 is an
// Availability Zone ID for the us-east-1 AWS Region, and it has the same location
// in every AWS account.
AvailabilityZoneId *string
// Describes the AWS Availability Zone in which the file system is located, and is
// valid only for file systems using One Zone storage classes. For more
// information, see Using EFS storage classes
// (https://docs.aws.amazon.com/efs/latest/ug/storage-classes.html) in the Amazon
// EFS User Guide.
AvailabilityZoneName *string
// A Boolean value that, if true, indicates that the file system is encrypted.
Encrypted *bool
// The Amazon Resource Name (ARN) for the EFS file system, in the format
// arn:aws:elasticfilesystem:region:account-id:file-system/file-system-id . Example
// with sample data:
// arn:aws:elasticfilesystem:us-west-2:1111333322228888:file-system/fs-01234567
FileSystemArn *string
// The ID of an AWS Key Management Service (AWS KMS) customer master key (CMK) that
// was used to protect the encrypted file system.
KmsKeyId *string
// You can add tags to a file system, including a Name tag. For more information,
// see CreateFileSystem. If the file system has a Name tag, Amazon EFS returns the
// value in this field.
Name *string
// The amount of provisioned throughput, measured in MiB/s, for the file system.
// Valid for file systems using ThroughputMode set to provisioned.
ProvisionedThroughputInMibps *float64
// Displays the file system's throughput mode. For more information, see Throughput
// modes
// (https://docs.aws.amazon.com/efs/latest/ug/performance.html#throughput-modes) in
// the Amazon EFS User Guide.
ThroughputMode types.ThroughputMode
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
}
func addOperationCreateFileSystemMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateFileSystem{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateFileSystem{}, middleware.After)
if err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addIdempotencyToken_opCreateFileSystemMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateFileSystemValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateFileSystem(options.Region), middleware.Before); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateFileSystem struct {
tokenProvider IdempotencyTokenProvider
}
func (*idempotencyToken_initializeOpCreateFileSystem) ID() string {
return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateFileSystem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateFileSystemInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateFileSystemInput ")
}
if input.CreationToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.CreationToken = &t
}
return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateFileSystemMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateFileSystem{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateFileSystem(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "elasticfilesystem",
OperationName: "CreateFileSystem",
}
}
|
DamieFC/chromium
|
components/favicon_base/select_favicon_frames.cc
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/favicon_base/select_favicon_frames.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <utility>
#include "base/containers/contains.h"
#include "base/macros.h"
#include "components/favicon_base/favicon_util.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkImage.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_source.h"
namespace {
size_t BiggestCandidate(const std::vector<gfx::Size>& candidate_sizes) {
size_t max_index = 0;
int max_area = candidate_sizes[0].GetArea();
for (size_t i = 1; i < candidate_sizes.size(); ++i) {
int area = candidate_sizes[i].GetArea();
if (area > max_area) {
max_area = area;
max_index = i;
}
}
return max_index;
}
SkBitmap SampleNearestNeighbor(const SkBitmap& contents, int desired_size) {
SkBitmap bitmap;
bitmap.allocN32Pixels(desired_size, desired_size);
if (!contents.isOpaque())
bitmap.eraseARGB(0, 0, 0, 0);
{
SkCanvas canvas(bitmap, SkSurfaceProps{});
canvas.drawImageRect(contents.asImage(),
SkRect::MakeIWH(desired_size, desired_size),
SkSamplingOptions());
}
return bitmap;
}
size_t GetCandidateIndexWithBestScore(
const std::vector<gfx::Size>& candidate_sizes,
int desired_size,
float* score) {
DCHECK_NE(desired_size, 0);
// Try to find an exact match.
for (size_t i = 0; i < candidate_sizes.size(); ++i) {
if (candidate_sizes[i].width() == desired_size &&
candidate_sizes[i].height() == desired_size) {
*score = 1;
return i;
}
}
// Huge favicon bitmaps often have a completely different visual style from
// smaller favicon bitmaps. Avoid them.
const int kHugeEdgeSize = desired_size * 8;
// Order of preference:
// 1) Bitmaps with width and height smaller than |kHugeEdgeSize|.
// 2) Bitmaps which need to be scaled down instead of up.
// 3) Bitmaps which do not need to be scaled as much.
size_t candidate_index = std::numeric_limits<size_t>::max();
float candidate_score = 0;
for (size_t i = 0; i < candidate_sizes.size(); ++i) {
float average_edge =
(candidate_sizes[i].width() + candidate_sizes[i].height()) / 2.0f;
float score = 0;
if (candidate_sizes[i].width() >= kHugeEdgeSize ||
candidate_sizes[i].height() >= kHugeEdgeSize) {
score = std::min(1.0f, desired_size / average_edge) * 0.01f;
} else if (candidate_sizes[i].width() >= desired_size &&
candidate_sizes[i].height() >= desired_size) {
score = desired_size / average_edge * 0.01f + 0.15f;
} else {
score = std::min(1.0f, average_edge / desired_size) * 0.01f + 0.1f;
}
if (candidate_index == std::numeric_limits<size_t>::max() ||
score > candidate_score) {
candidate_index = i;
candidate_score = score;
}
}
*score = candidate_score;
return candidate_index;
}
// Represents the index of the best candidate for |desired_size| from the
// |candidate_sizes| passed into GetCandidateIndicesWithBestScores().
struct SelectionResult {
// index in |candidate_sizes| of the best candidate.
size_t index;
// The desired size for which |index| is the best candidate.
int desired_size;
};
void GetCandidateIndicesWithBestScores(
const std::vector<gfx::Size>& candidate_sizes,
const std::vector<int>& desired_sizes,
float* match_score,
std::vector<SelectionResult>* results) {
if (candidate_sizes.empty() || desired_sizes.empty()) {
if (match_score)
*match_score = 0.0f;
return;
}
if (base::Contains(desired_sizes, 0)) {
// Just return the biggest image available.
SelectionResult result;
result.index = BiggestCandidate(candidate_sizes);
result.desired_size = 0;
results->push_back(result);
if (match_score)
*match_score = 1.0f;
return;
}
float total_score = 0;
for (size_t i = 0; i < desired_sizes.size(); ++i) {
float score;
SelectionResult result;
result.desired_size = desired_sizes[i];
result.index = GetCandidateIndexWithBestScore(
candidate_sizes, result.desired_size, &score);
results->push_back(result);
total_score += score;
}
if (match_score)
*match_score = total_score / desired_sizes.size();
}
// Resize |source_bitmap|
SkBitmap GetResizedBitmap(const SkBitmap& source_bitmap,
gfx::Size original_size,
int desired_size_in_pixel) {
if (desired_size_in_pixel == 0 ||
(original_size.width() == desired_size_in_pixel &&
original_size.height() == desired_size_in_pixel)) {
return source_bitmap;
}
if (desired_size_in_pixel % original_size.width() == 0 &&
desired_size_in_pixel % original_size.height() == 0) {
return SampleNearestNeighbor(source_bitmap, desired_size_in_pixel);
}
return skia::ImageOperations::Resize(source_bitmap,
skia::ImageOperations::RESIZE_LANCZOS3,
desired_size_in_pixel,
desired_size_in_pixel);
}
class FaviconImageSource : public gfx::ImageSkiaSource {
public:
FaviconImageSource() {}
~FaviconImageSource() override {}
// gfx::ImageSkiaSource:
gfx::ImageSkiaRep GetImageForScale(float scale) override {
const gfx::ImageSkiaRep* rep = nullptr;
// gfx::ImageSkia passes one of the resource scale factors. The source
// should return:
// 1) The ImageSkiaRep with the highest scale if all available
// scales are smaller than |scale|.
// 2) The ImageSkiaRep with the smallest one that is larger than |scale|.
// Note: Keep this logic consistent with the PNGImageSource in
// ui/gfx/image.cc.
// TODO(oshima): consolidate these logic into one place.
for (std::vector<gfx::ImageSkiaRep>::const_iterator iter =
image_skia_reps_.begin();
iter != image_skia_reps_.end(); ++iter) {
if ((*iter).scale() == scale)
return (*iter);
if (!rep || rep->scale() < (*iter).scale())
rep = &(*iter);
if (rep->scale() >= scale)
break;
}
DCHECK(rep);
return rep ? *rep : gfx::ImageSkiaRep();
}
void AddImageSkiaRep(const gfx::ImageSkiaRep& rep) {
image_skia_reps_.push_back(rep);
}
private:
std::vector<gfx::ImageSkiaRep> image_skia_reps_;
DISALLOW_COPY_AND_ASSIGN(FaviconImageSource);
};
} // namespace
const float kSelectFaviconFramesInvalidScore = -1.0f;
gfx::ImageSkia CreateFaviconImageSkia(
const std::vector<SkBitmap>& bitmaps,
const std::vector<gfx::Size>& original_sizes,
int desired_size_in_dip,
float* score) {
DCHECK_EQ(bitmaps.size(), original_sizes.size());
const std::vector<float>& favicon_scales = favicon_base::GetFaviconScales();
std::vector<int> desired_sizes;
if (desired_size_in_dip == 0) {
desired_sizes.push_back(0);
} else {
for (auto iter = favicon_scales.begin(); iter != favicon_scales.end();
++iter) {
desired_sizes.push_back(
static_cast<int>(ceil(desired_size_in_dip * (*iter))));
}
}
std::vector<SelectionResult> results;
GetCandidateIndicesWithBestScores(original_sizes,
desired_sizes,
score,
&results);
if (results.size() == 0)
return gfx::ImageSkia();
if (desired_size_in_dip == 0) {
size_t index = results[0].index;
return gfx::ImageSkia::CreateFromBitmap(bitmaps[index], 1.0f);
}
auto image_source = std::make_unique<FaviconImageSource>();
for (size_t i = 0; i < results.size(); ++i) {
size_t index = results[i].index;
image_source->AddImageSkiaRep(
gfx::ImageSkiaRep(GetResizedBitmap(bitmaps[index],
original_sizes[index],
desired_sizes[i]),
favicon_scales[i]));
}
return gfx::ImageSkia(std::move(image_source),
gfx::Size(desired_size_in_dip, desired_size_in_dip));
}
void SelectFaviconFrameIndices(const std::vector<gfx::Size>& frame_pixel_sizes,
const std::vector<int>& desired_sizes,
std::vector<size_t>* best_indices,
float* match_score) {
std::vector<SelectionResult> results;
GetCandidateIndicesWithBestScores(
frame_pixel_sizes, desired_sizes, match_score, &results);
if (!best_indices)
return;
std::set<size_t> already_added;
for (size_t i = 0; i < results.size(); ++i) {
size_t index = results[i].index;
// GetCandidateIndicesWithBestScores() will return duplicate indices if the
// bitmap data with |frame_pixel_sizes[index]| should be used for multiple
// scale factors. Remove duplicates here such that |best_indices| contains
// no duplicates.
if (already_added.find(index) == already_added.end()) {
already_added.insert(index);
best_indices->push_back(index);
}
}
}
|
jdurand/Montreal.rb
|
spec/controllers/members_controller_spec.rb
|
# frozen_string_literal: true
require "rails_helper"
RSpec.describe MembersController, type: :controller do
let(:user) { create(:user) }
let(:member) { user.member }
describe "#edit" do
subject { get :edit }
context "user is authenticated" do
before { sign_in user }
it { is_expected.to have_http_status(200) }
it { is_expected.to render_template :edit }
end
context "user is a guest" do
it { is_expected.to have_http_status(302) }
end
end
describe "#update" do
subject { post :update, params: { member: { twitter_handle: "RailsbridgeMTL" } } }
context "user is authenticated" do
before { sign_in user }
it { is_expected.to redirect_to edit_member_path }
it "updates the member" do
expect { subject }.to(change { member.reload.twitter_handle })
end
context "with invalid attributes" do
subject { post :update, params: { member: { name: nil } } }
it { is_expected.to render_template :edit }
it "updates the member" do
expect { subject }.to_not(change { member.reload.twitter_handle })
end
end
end
context "user is a guest" do
it { is_expected.to have_http_status(302) }
end
end
end
|
avigoldman/codsen
|
packages/easy-replace/dist/easy-replace.esm.js
|
/**
* @name easy-replace
* @fileoverview Replace strings with optional lookarounds, but without regexes
* @version 5.0.5
* @author <NAME>, Codsen Ltd
* @license MIT
* {@link https://codsen.com/os/easy-replace/}
*/
var version$1 = "5.0.5";
const version = version$1;
function astralAwareSearch(whereToLook, whatToLookFor, opts) {
function existy(something) {
return something != null;
}
if (typeof whereToLook !== "string" || whereToLook.length === 0 || typeof whatToLookFor !== "string" || whatToLookFor.length === 0) {
return [];
}
const foundIndexArray = [];
const arrWhereToLook = Array.from(whereToLook);
const arrWhatToLookFor = Array.from(whatToLookFor);
let found;
for (let i = 0; i < arrWhereToLook.length; i++) {
if (opts && opts.i) {
if (arrWhereToLook[i].toLowerCase() === arrWhatToLookFor[0].toLowerCase()) {
found = true;
for (let i2 = 0; i2 < arrWhatToLookFor.length; i2++) {
if (!existy(arrWhereToLook[i + i2]) || !existy(arrWhatToLookFor[i2]) || arrWhereToLook[i + i2].toLowerCase() !== arrWhatToLookFor[i2].toLowerCase()) {
found = false;
break;
}
}
if (found) {
foundIndexArray.push(i);
}
}
} else if (arrWhereToLook[i] === arrWhatToLookFor[0]) {
found = true;
for (let i2 = 0; i2 < arrWhatToLookFor.length; i2++) {
if (arrWhereToLook[i + i2] !== arrWhatToLookFor[i2]) {
found = false;
break;
}
}
if (found) {
foundIndexArray.push(i);
}
}
}
return foundIndexArray;
}
function stringise(incoming) {
function existy(something) {
return something != null;
}
if (!existy(incoming) || typeof incoming === "boolean") {
return [""];
}
if (Array.isArray(incoming)) {
return incoming.filter(el => existy(el) && typeof el !== "boolean").map(el => String(el)).filter(el => el.length > 0);
}
return [String(incoming)];
}
function iterateLeft(elem, arrSource, foundBeginningIndex, i) {
let matched = true;
const charsArray = Array.from(elem);
for (let i2 = 0, len = charsArray.length; i2 < len; i2++) {
if (i) {
if (charsArray[i2].toLowerCase() !== arrSource[foundBeginningIndex - Array.from(elem).length + i2].toLowerCase()) {
matched = false;
break;
}
} else if (charsArray[i2] !== arrSource[foundBeginningIndex - Array.from(elem).length + i2]) {
matched = false;
break;
}
}
return matched;
}
function iterateRight(elem, arrSource, foundEndingIndex, i) {
let matched = true;
const charsArray = Array.from(elem);
for (let i2 = 0, len = charsArray.length; i2 < len; i2++) {
if (i) {
if (charsArray[i2].toLowerCase() !== arrSource[foundEndingIndex + i2].toLowerCase()) {
matched = false;
break;
}
} else if (charsArray[i2] !== arrSource[foundEndingIndex + i2]) {
matched = false;
break;
}
}
return matched;
}
function er(originalSource, options, originalReplacement) {
const defaults = {
i: {
leftOutsideNot: false,
leftOutside: false,
leftMaybe: false,
searchFor: false,
rightMaybe: false,
rightOutside: false,
rightOutsideNot: false
}
};
const opts = { ...defaults,
...options
};
const source = stringise(originalSource);
opts.leftOutsideNot = stringise(opts.leftOutsideNot);
opts.leftOutside = stringise(opts.leftOutside);
opts.leftMaybe = stringise(opts.leftMaybe);
opts.searchFor = String(opts.searchFor);
opts.rightMaybe = stringise(opts.rightMaybe);
opts.rightOutside = stringise(opts.rightOutside);
opts.rightOutsideNot = stringise(opts.rightOutsideNot);
const replacement = stringise(originalReplacement);
const arrSource = Array.from(source[0]);
let foundBeginningIndex;
let foundEndingIndex;
let matched;
let found;
const replacementRecipe = [];
let result = "";
const allResults = astralAwareSearch(source[0], opts.searchFor, {
i: opts.i.searchFor
});
for (let resIndex = 0, resLen = allResults.length; resIndex < resLen; resIndex++) {
const oneOfFoundIndexes = allResults[resIndex];
foundBeginningIndex = oneOfFoundIndexes;
foundEndingIndex = oneOfFoundIndexes + Array.from(opts.searchFor).length;
/* istanbul ignore else */
if (opts.leftMaybe.length > 0) {
for (let i = 0, len = opts.leftMaybe.length; i < len; i++) {
matched = true;
const splitLeftMaybe = Array.from(opts.leftMaybe[i]);
for (let i2 = 0, len2 = splitLeftMaybe.length; i2 < len2; i2++) {
if (opts.i.leftMaybe) {
if (splitLeftMaybe[i2].toLowerCase() !== arrSource[oneOfFoundIndexes - splitLeftMaybe.length + i2].toLowerCase()) {
matched = false;
break;
}
} else if (splitLeftMaybe[i2] !== arrSource[oneOfFoundIndexes - splitLeftMaybe.length + i2]) {
matched = false;
break;
}
}
if (matched && oneOfFoundIndexes - splitLeftMaybe.length < foundBeginningIndex) {
foundBeginningIndex = oneOfFoundIndexes - splitLeftMaybe.length;
}
}
}
/* istanbul ignore else */
if (opts.rightMaybe.length > 0) {
for (let i = 0, len = opts.rightMaybe.length; i < len; i++) {
matched = true;
const splitRightMaybe = Array.from(opts.rightMaybe[i]);
for (let i2 = 0, len2 = splitRightMaybe.length; i2 < len2; i2++) {
if (opts.i.rightMaybe) {
if (splitRightMaybe[i2].toLowerCase() !== arrSource[oneOfFoundIndexes + Array.from(opts.searchFor).length + i2].toLowerCase()) {
matched = false;
break;
}
} else if (splitRightMaybe[i2] !== arrSource[oneOfFoundIndexes + Array.from(opts.searchFor).length + i2]) {
matched = false;
break;
}
}
if (matched && foundEndingIndex < oneOfFoundIndexes + Array.from(opts.searchFor).length + splitRightMaybe.length) {
foundEndingIndex = oneOfFoundIndexes + Array.from(opts.searchFor).length + splitRightMaybe.length;
}
}
}
if (opts.leftOutside[0] !== "") {
found = false;
for (let i = 0, len = opts.leftOutside.length; i < len; i++) {
matched = iterateLeft(opts.leftOutside[i], arrSource, foundBeginningIndex, opts.i.leftOutside);
if (matched) {
found = true;
}
}
if (!found) {
continue;
}
}
if (opts.rightOutside[0] !== "") {
found = false;
for (let i = 0, len = opts.rightOutside.length; i < len; i++) {
matched = iterateRight(opts.rightOutside[i], arrSource, foundEndingIndex, opts.i.rightOutside);
if (matched) {
found = true;
}
}
if (!found) {
continue;
}
}
if (opts.leftOutsideNot[0] !== "") {
for (let i = 0, len = opts.leftOutsideNot.length; i < len; i++) {
matched = iterateLeft(opts.leftOutsideNot[i], arrSource, foundBeginningIndex, opts.i.leftOutsideNot);
if (matched) {
foundBeginningIndex = -1;
foundEndingIndex = -1;
break;
}
}
if (foundBeginningIndex === -1) {
continue;
}
}
if (opts.rightOutsideNot[0] !== "") {
for (let i = 0, len = opts.rightOutsideNot.length; i < len; i++) {
matched = iterateRight(opts.rightOutsideNot[i], arrSource, foundEndingIndex, opts.i.rightOutsideNot);
if (matched) {
foundBeginningIndex = -1;
foundEndingIndex = -1;
break;
}
}
if (foundBeginningIndex === -1) {
continue;
}
}
replacementRecipe.push([foundBeginningIndex, foundEndingIndex]);
}
if (replacementRecipe.length > 0) {
replacementRecipe.forEach((_elem, i) => {
if (replacementRecipe[i + 1] !== undefined && replacementRecipe[i][1] > replacementRecipe[i + 1][0]) {
replacementRecipe[i + 1][0] = replacementRecipe[i][1];
}
});
replacementRecipe.forEach((elem, i) => {
if (elem[0] === elem[1]) {
replacementRecipe.splice(i, 1);
}
});
} else {
return source.join("");
}
if (replacementRecipe.length > 0 && replacementRecipe[0][0] !== 0) {
result += arrSource.slice(0, replacementRecipe[0][0]).join("");
}
replacementRecipe.forEach((_elem, i) => {
result += replacement.join("");
if (replacementRecipe[i + 1] !== undefined) {
result += arrSource.slice(replacementRecipe[i][1], replacementRecipe[i + 1][0]).join("");
} else {
result += arrSource.slice(replacementRecipe[i][1]).join("");
}
});
return result;
}
export { er, version };
|
Tobias-Werner/GStream
|
src/operator/windows/TiltingWindow.cpp
|
<filename>src/operator/windows/TiltingWindow.cpp
//
// Created by tobias on 29.08.18.
//
#include <operator/windows/TiltingWindow.h>
#include <data_container/ListContainer.h>
#include <iostream>
#include "operator/windows/TiltingWindow.h"
using namespace std;
using namespace STREAM;
using namespace chrono;
STREAM::TiltingWindow::TiltingWindow(std::chrono::milliseconds duration) : buffer(make_shared<ListContainer>()),
duration(duration),
begin(high_resolution_clock::now()) {
}
void STREAM::TiltingWindow::onDataUpdate() {
auto now = high_resolution_clock().now();
if ((now - begin) > duration) {
resultSet = buffer;
buffer = make_shared<ListContainer>();
begin = now;
}
for (auto newTupleIterator = primaryInput.pop()->getIterator(); !newTupleIterator->end(); newTupleIterator->next())
buffer->pushBack(newTupleIterator->get());
publish(resultSet);
}
STREAM::TiltingWindow::~TiltingWindow() {
}
|
madogiwa/skaffold
|
pkg/skaffold/instrumentation/trace_test.go
|
<reponame>madogiwa/skaffold
/*
Copyright 2021 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instrumentation
import (
"bytes"
"context"
"encoding/json"
"os"
"strings"
"testing"
"time"
"github.com/GoogleContainerTools/skaffold/testutil"
)
func TestInitCloudTrace(t *testing.T) {
tests := []struct {
shouldError bool
traceProviderIsNil bool
isConcurrentTrace bool
name string
traceEnvVar string
parentSpans []string
childSpans []string
}{
{
name: "SKAFFOLD_TRACE=stdout, verify spans output to stdout and spans are sequential",
traceEnvVar: "stdout",
parentSpans: []string{"SequentialSpanOne", "SequentialSpanTwo"},
},
{
name: "SKAFFOLD_TRACE=stdout, verify spans output to stdout and spans are concurrent",
traceEnvVar: "stdout",
parentSpans: []string{"ConcurrentSpanOne", "ConcurrentSpanTwo"},
isConcurrentTrace: true,
},
{
name: "SKAFFOLD_TRACE=stdout, verify spans output to stdout and parent/child relationship exists spans",
traceEnvVar: "stdout",
parentSpans: []string{"ParentSpanOne"},
childSpans: []string{"ChildSpanOne"},
isConcurrentTrace: true,
},
}
for _, test := range tests {
testutil.Run(t, test.name, func(t *testutil.T) {
if len(test.traceEnvVar) > 0 {
os.Setenv("SKAFFOLD_TRACE", test.traceEnvVar)
defer os.Unsetenv(("SKAFFOLD_TRACE"))
}
var b bytes.Buffer
func() {
ctx := context.Background()
tp, _, err := InitTraceFromEnvVar(WithWriter(&b))
t.CheckErrorAndDeepEqual(test.shouldError, err, test.traceProviderIsNil || test.shouldError, tp == nil)
defer func() { _ = TracerShutdown(ctx) }()
for _, pName := range test.parentSpans {
ctx, endTrace := StartTrace(ctx, pName)
for _, cName := range test.childSpans {
_, endTrace := StartTrace(ctx, cName)
if test.isConcurrentTrace {
defer endTrace()
} else {
endTrace()
}
}
if test.isConcurrentTrace {
defer endTrace()
} else {
endTrace()
}
time.Sleep(1 * time.Millisecond)
}
}()
if len(test.parentSpans) > 0 {
var spans SpanArray
err := json.Unmarshal(b.Bytes(), &spans)
if err != nil {
t.Errorf("unexpected error occurred unmarshalling trace spans %v: %v", b.String(), err)
}
t.CheckTrue(len(spans) == len(test.parentSpans)+len(test.childSpans))
for i := range spans {
if strings.Contains(spans[i].Name, "Parent") {
t.CheckTrue(spans[i].Childspancount > 0)
}
if strings.Contains(spans[i].Name, "Child") {
// 0000000000000000 value for Spanid means parent does not exist for a span. Should be set to parent Spanid if
// span is a child span
t.CheckTrue(spans[i].Parent.Spanid != "0000000000000000")
}
if i == 0 {
continue
} // skipping first span for comparing spans for sequential/concurrent tests
lastEndtime, err := time.Parse(time.RFC3339, spans[i-1].Endtime)
if err != nil {
t.Errorf("unexpected error occurred parsing trace span Endtime %v: %v", b.String(), err)
}
startime, err := time.Parse(time.RFC3339, spans[i].Starttime)
if err != nil {
t.Errorf("unexpected error occurred parsing trace span Endtime %v: %v", b.String(), err)
}
if test.isConcurrentTrace {
t.CheckTrue(!lastEndtime.Before(startime))
} else {
// sequential ordering of traces
t.CheckTrue(lastEndtime.Before(startime))
}
}
}
})
}
}
type SpanArray []struct {
Spancontext Spancontext `json:"SpanContext"`
Parent Parent `json:"Parent"`
Spankind int `json:"SpanKind"`
Name string `json:"Name"`
Starttime string `json:"StartTime"`
Endtime string `json:"EndTime"`
Attributes interface{} `json:"Attributes"`
Messageevents interface{} `json:"MessageEvents"`
Links interface{} `json:"Links"`
Statuscode string `json:"StatusCode"`
Statusmessage string `json:"StatusMessage"`
Droppedattributecount int `json:"DroppedAttributeCount"`
Droppedmessageeventcount int `json:"DroppedMessageEventCount"`
Droppedlinkcount int `json:"DroppedLinkCount"`
Childspancount int `json:"ChildSpanCount"`
Resource []Resource `json:"Resource"`
Instrumentationlibrary Instrumentationlibrary `json:"InstrumentationLibrary"`
}
type Spancontext struct {
Traceid string `json:"TraceID"`
Spanid string `json:"SpanID"`
Traceflags string `json:"TraceFlags"`
Tracestate interface{} `json:"TraceState"`
Remote bool `json:"Remote"`
}
type Parent struct {
Traceid string `json:"TraceID"`
Spanid string `json:"SpanID"`
Traceflags string `json:"TraceFlags"`
Tracestate interface{} `json:"TraceState"`
Remote bool `json:"Remote"`
}
type Value struct {
Type string `json:"Type"`
Value string `json:"Value"`
}
type Resource struct {
Key string `json:"Key"`
Value Value `json:"Value"`
}
type Instrumentationlibrary struct {
Name string `json:"Name"`
Version string `json:"Version"`
}
|
VersiraSec/epsilon-cfw
|
poincare/include/poincare/binomial_coefficient.h
|
<filename>poincare/include/poincare/binomial_coefficient.h
#ifndef POINCARE_BINOMIAL_COEFFICIENT_H
#define POINCARE_BINOMIAL_COEFFICIENT_H
#include <poincare/approximation_helper.h>
#include <poincare/expression.h>
namespace Poincare {
class BinomialCoefficientNode final : public ExpressionNode {
public:
// TreeNode
size_t size() const override { return sizeof(BinomialCoefficientNode); }
int numberOfChildren() const override;
#if POINCARE_TREE_LOG
void logNodeName(std::ostream & stream) const override {
stream << "BinomialCoefficient";
}
#endif
// Properties
Type type() const override{ return Type::BinomialCoefficient; }
template<typename T> static T compute(T k, T n);
private:
// Layout
Layout createLayout(Preferences::PrintFloatMode floatDisplayMode, int numberOfSignificantDigits) const override;
int serialize(char * buffer, int bufferSize, Preferences::PrintFloatMode floatDisplayMode, int numberOfSignificantDigits) const override;
// Simplification
Expression shallowReduce(ReductionContext reductionContext) override;
LayoutShape leftLayoutShape() const override { return LayoutShape::BoundaryPunctuation; };
// Evaluation
Evaluation<float> approximate(SinglePrecision p, ApproximationContext approximationContext) const override { return templatedApproximate<float>(approximationContext); }
Evaluation<double> approximate(DoublePrecision p, ApproximationContext approximationContext) const override { return templatedApproximate<double>(approximationContext); }
template<typename T> Complex<T> templatedApproximate(ApproximationContext approximationContext) const;
};
class BinomialCoefficient final : public Expression {
public:
BinomialCoefficient(const BinomialCoefficientNode * n) : Expression(n) {}
static BinomialCoefficient Builder(Expression child0, Expression child1) { return TreeHandle::FixedArityBuilder<BinomialCoefficient, BinomialCoefficientNode>({child0, child1}); }
static constexpr Expression::FunctionHelper s_functionHelper = Expression::FunctionHelper("binomial", 2, &UntypedBuilderTwoChildren<BinomialCoefficient>);
// Expression
Expression shallowReduce(Context * context);
private:
constexpr static int k_maxNValue = 300;
};
}
#endif
|
antony-jekov/Nevix
|
Source/Android/Nevix/nevix/src/main/java/com/antonyjekov/nevix/player/buttons/PointingUpButton.java
|
package com.antonyjekov.nevix.player.buttons;
import android.graphics.Path;
import android.graphics.Rect;
import com.antonyjekov.nevix.constants.PlayerCommand;
/**
* Created by <NAME> on 3/27/2014.
*/
public class PointingUpButton extends SphericalButton {
public PointingUpButton(Rect button, int strokeWidth, int padding) {
super(button, strokeWidth, padding);
}
@Override
protected void prepareShape(Path shape) {
super.prepareShape(shape);
int x = button.centerX();
int y = button.top + padding;
int halfLen = (button.width() - (padding << 1)) >> 1;
shape.moveTo(x, y);
shape.lineTo(x - halfLen, button.centerY());
shape.lineTo(x + halfLen, button.centerY());
shape.lineTo(x, y);
shape.close();
}
@Override
public String command() {
return PlayerCommand.BROWSE_CMD;
}
}
|
slusek/OG-Platform
|
projects/OG-Analytics/src/test/java/com/opengamma/analytics/financial/model/volatility/smile/fitting/SABRSurfaceFittingTest.java
|
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.model.volatility.smile.fitting;
import java.util.BitSet;
import org.apache.commons.lang.Validate;
import org.testng.annotations.Test;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.BlackFunctionData;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.EuropeanVanillaOption;
import com.opengamma.analytics.financial.model.volatility.smile.function.SABRHaganVolatilityFunction;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.statistics.leastsquare.LeastSquareResultsWithTransform;
/**
* @deprecated This class tests deprecated functionality
*/
@Deprecated
public class SABRSurfaceFittingTest {
private static final SABRNonLinearLeastSquareFitter FITTER = new SABRNonLinearLeastSquareFitter(new SABRHaganVolatilityFunction());
@Test
public void doIt() {
final double[] maturities = new double[] {5, 1, 10, 15, 1, 5 };
final double[] tenors = new double[] {5, 5, 10, 15, 1, 10 };
final double[] forwards = new double[] {0.0424, 0.025513, 0.046213, 0.04405, 0.010482, 0.04443 };
final double[] atmVols = new double[] {0.23845, 0.36995, 0.18745, 0.162, 0.7332, 0.2177 };
final int n = maturities.length;
Validate.isTrue(n == tenors.length && n == forwards.length && n == atmVols.length);
final double[] moneynessSigma = new double[] {-2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2 };
final double[][] vols = new double[n][];
vols[0] = new double[] {0, 0.27, 0.253, 0.247, 0.23845, 0.238, 0.236, 0.233, 0.226 };
vols[1] = new double[] {0.653, 0.442, 0.396, 0.382, 0.36995, 0.367, 0.363, 0.363, 0.36 };
vols[2] = new double[] {0.25, 0.214, 0.2, 0.194, 0.18745, 0.186, 0.183, 0.179, 0.171 };
vols[3] = new double[] {0.224, 0.19, 0.175, 0.17, 0.162, 0.161, 0.158, 0.154, 0.15 };
vols[4] = new double[] {0, 0, 0.847, 0.776, 0.7332, 0.718, 0.707, 0.702, 0.701 };
vols[5] = new double[] {0.284, 0.247, 0.231, 0.225, 0.2177, 0.217, 0.213, 0.209, 0.207 };
final double[] alpha = new double[n];
final double[] beta = new double[n];
final double[] nu = new double[n];
final double[] rho = new double[n];
final double[] start = new double[] {0.3, 0.9, 0.3, 0.0 };
for (int i = 0; i < n; i++) {
int m = 0;
for (int j = 0; j < vols[i].length; j++) {
if (vols[i][j] > 0.0) {
m++;
}
}
final EuropeanVanillaOption[] options = new EuropeanVanillaOption[m];
final BlackFunctionData[] data = new BlackFunctionData[m];
final double[] errors = new double[m];
int p = 0;
for (int j = 0; j < vols[i].length; j++) {
if (vols[i][j] > 0.0) {
options[p] = new EuropeanVanillaOption(forwards[i] * Math.exp(atmVols[i] * Math.sqrt(maturities[i]) * moneynessSigma[j]), maturities[i], true);
data[p] = new BlackFunctionData(forwards[i], 1, vols[i][j]);
errors[p] = 0.001;
p++;
}
}
final LeastSquareResultsWithTransform result = FITTER.getFitResult(options, data, errors, start, new BitSet(4));
final DoubleMatrix1D params = result.getModelParameters();
alpha[i] = params.getEntry(0);
beta[i] = params.getEntry(1);
nu[i] = params.getEntry(2);
rho[i] = params.getEntry(3);
// System.out.print(alpha[i] + "\t" + beta[i] + "\t" + nu[i] + "\t" + rho[i] + "\t");
// for (int j = 0; j < m; j++) {
// System.out.print("\t" + strikes[j]);
// }
// System.out.print("\n");
// System.out.print("\t\t\t\t");
// for (int j = 0; j < m; j++) {
// double sabrVol = sabr.impliedVolatility(forwards[i], alpha[i], beta[i], nu[i], rho[i], strikes[j], maturities[i]);
// System.out.print("\t" + sabrVol);
// }
// System.out.print("\n");
}
}
}
|
jeikabu/lumberyard
|
dev/Code/Deprecated/Sandbox/Editor/FacialEditor/FacialSlidersDialog.h
|
<filename>dev/Code/Deprecated/Sandbox/Editor/FacialEditor/FacialSlidersDialog.h
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_EDITOR_FACIALEDITOR_FACIALSLIDERSDIALOG_H
#define CRYINCLUDE_EDITOR_FACIALEDITOR_FACIALSLIDERSDIALOG_H
#pragma once
#include "FacialSlidersCtrl.h"
//////////////////////////////////////////////////////////////////////////
class CFacialSlidersDialog : public CDialog
{
DECLARE_DYNAMIC(CFacialSlidersDialog)
public:
static void RegisterViewClass();
CFacialSlidersDialog();
~CFacialSlidersDialog();
enum { IDD = IDD_DATABASE };
void SetContext( CFacialEdContext *pContext );
void SetMorphWeight(IFacialEffector* pEffector, float fWeight);
void ClearAllMorphs();
protected:
virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual void OnOK() {};
virtual void OnCancel() {};
virtual BOOL OnInitDialog();
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnTabSelect(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnClearAllSliders();
afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt);
void RecalcLayout();
private:
CXTPToolBar m_wndToolBar;
CFacialSlidersCtrl m_slidersCtrl[2];
CTabCtrl m_tabCtrl;
CFacialEdContext *m_pContext;
HACCEL m_hAccelerators;
};
#endif // CRYINCLUDE_EDITOR_FACIALEDITOR_FACIALSLIDERSDIALOG_H
|
antoniodourado/sphinxbase
|
doc/html/structnoise__stats__s.js
|
var structnoise__stats__s =
[
[ "comp_lambda_a", "structnoise__stats__s.html#a047be8fb044da7e3a3f45b78e9d5de23", null ],
[ "comp_lambda_b", "structnoise__stats__s.html#ac3317afbf629cadc04b41c5657f0140d", null ],
[ "comp_lambda_power", "structnoise__stats__s.html#a7d2228c947b372142346861adbf16acb", null ],
[ "floor", "structnoise__stats__s.html#aea4aaa0528b85a2989743afee3f21964", null ],
[ "inv_max_gain", "structnoise__stats__s.html#ab6b62f1324e05bafa461bdcab8bc1bf3", null ],
[ "lambda_a", "structnoise__stats__s.html#a804b3c775a7d80c95a2a53e9eb0d6b3a", null ],
[ "lambda_b", "structnoise__stats__s.html#a56527a4cfd15aac96133ed20989c89c7", null ],
[ "lambda_power", "structnoise__stats__s.html#aae414a12fd0b4b8be3a61468fe15f3de", null ],
[ "lambda_t", "structnoise__stats__s.html#a94d5961c9df8d3345821c2f6c4358514", null ],
[ "max_gain", "structnoise__stats__s.html#afeda1bf01ce753f6b3e4fb89279cfc63", null ],
[ "mu_t", "structnoise__stats__s.html#ad5cc76a830669ea5fbf0b8f4e4f80652", null ],
[ "noise", "structnoise__stats__s.html#ab21b71b8202302859b120b08b42bb4bb", null ],
[ "num_filters", "structnoise__stats__s.html#ad5b17abb96cc825153b41f1506018c3c", null ],
[ "peak", "structnoise__stats__s.html#a36e6b3a83014d30755b763fa8575a35d", null ],
[ "power", "structnoise__stats__s.html#a3352c66489d54b578e5f43cc646951dc", null ],
[ "slow_peak_sum", "structnoise__stats__s.html#a9038ab6afc8ff2df63952cc16d032f0d", null ],
[ "smooth_scaling", "structnoise__stats__s.html#a4bc8cd91479f20703fdf82251ba90e6e", null ],
[ "undefined", "structnoise__stats__s.html#a84138e0f5dd6bc3c8049cce8ea815678", null ]
];
|
lathspell/java_test
|
java_test_springboot_jpa_multiple/src/main/java/de/lathspell/test/h2/H2PersonRepository.java
|
<gh_stars>1-10
package de.lathspell.test.h2;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface H2PersonRepository extends JpaRepository<H2Person, Long> {
}
|
Naniroisprogrammingnow/Java-OOP-Exam-Prep
|
MotorcycleChampionship/src/motocrossWorldChampionship/entities/RaceImpl.java
|
<filename>MotorcycleChampionship/src/motocrossWorldChampionship/entities/RaceImpl.java
package motocrossWorldChampionship.entities;
import motocrossWorldChampionship.common.ExceptionMessages;
import motocrossWorldChampionship.entities.interfaces.Race;
import motocrossWorldChampionship.entities.interfaces.Rider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class RaceImpl implements Race {
private String name;
private int laps;
private Collection<Rider> riders;
public RaceImpl(String name, int laps) {
setName(name);
setLaps(laps);
this.riders = new ArrayList<>();
}
private void setName(String name){
if (name==null|| name.trim().equals("") || name.length()<5){
throw new IllegalArgumentException(String.format(ExceptionMessages.INVALID_NAME, name, 5));
}
this.name = name;
}
private void setLaps(int laps) {
if (laps<1){
throw new IllegalArgumentException(String.format(ExceptionMessages.INVALID_NUMBER_OF_LAPS, 1));
}
this.laps = laps;
}
@Override
public String getName() {
return this.name;
}
@Override
public int getLaps() {
return this.laps;
}
@Override
public Collection<Rider> getRiders() {
return this.riders;
}
@Override
public void addRider(Rider rider) {
if (rider==null){
throw new NullPointerException(ExceptionMessages.RIDER_INVALID);
}
if (!rider.getCanParticipate()){
throw new IllegalArgumentException(String.format(ExceptionMessages.RIDER_NOT_PARTICIPATE, rider.getName()));
}
if (alreadyParticipates(rider.getName())){
throw new IllegalArgumentException(String.format(ExceptionMessages.RIDER_ALREADY_ADDED, rider.getName(), this.name));
}
this.riders.add(rider);
}
private boolean alreadyParticipates(String name) {
for (Rider rider : this.riders) {
if (rider.getName().equals(name)){
return true;
}
}
return false;
}
}
|
Knutakir/KTT
|
source/compute_engine/vulkan/vulkan_buffer.h
|
<reponame>Knutakir/KTT
#pragma once
#include <cstring>
#include <vulkan/vulkan.h>
#include <compute_engine/vulkan/vulkan_physical_device.h>
#include <compute_engine/vulkan/vulkan_utility.h>
#include <kernel_argument/kernel_argument.h>
namespace ktt
{
class VulkanBuffer
{
public:
explicit VulkanBuffer(const VulkanBuffer& source, VkDevice device, const VulkanPhysicalDevice& physicalDevice,
const VkBufferUsageFlags usageFlags, const VkDeviceSize bufferSize) :
device(device),
physicalDevice(&physicalDevice),
bufferMemory(nullptr),
bufferSize(bufferSize),
usageFlags(usageFlags),
elementSize(source.getElementSize()),
kernelArgumentId(source.getKernelArgumentId()),
dataType(source.getDataType()),
memoryLocation(ArgumentMemoryLocation::Host),
accessType(source.getAccessType())
{
const VkBufferCreateInfo bufferCreateInfo =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
nullptr,
0,
bufferSize,
usageFlags,
VK_SHARING_MODE_EXCLUSIVE,
0,
nullptr
};
checkVulkanError(vkCreateBuffer(device, &bufferCreateInfo, nullptr, &buffer), "vkCreateBuffer");
}
explicit VulkanBuffer(KernelArgument& kernelArgument, VkDevice device, const VulkanPhysicalDevice& physicalDevice,
const VkBufferUsageFlags usageFlags) :
device(device),
physicalDevice(&physicalDevice),
bufferMemory(nullptr),
bufferSize(static_cast<VkDeviceSize>(kernelArgument.getDataSizeInBytes())),
usageFlags(usageFlags),
elementSize(kernelArgument.getElementSizeInBytes()),
kernelArgumentId(kernelArgument.getId()),
dataType(kernelArgument.getDataType()),
memoryLocation(kernelArgument.getMemoryLocation()),
accessType(kernelArgument.getAccessType())
{
const VkBufferCreateInfo bufferCreateInfo =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
nullptr,
0,
bufferSize,
usageFlags,
VK_SHARING_MODE_EXCLUSIVE,
0,
nullptr
};
checkVulkanError(vkCreateBuffer(device, &bufferCreateInfo, nullptr, &buffer), "vkCreateBuffer");
}
~VulkanBuffer()
{
vkDestroyBuffer(device, buffer, nullptr);
if (bufferMemory != nullptr)
{
vkFreeMemory(device, bufferMemory, nullptr);
}
}
VkMemoryRequirements getMemoryRequirements() const
{
VkMemoryRequirements requirements;
vkGetBufferMemoryRequirements(device, buffer, &requirements);
return requirements;
}
void allocateMemory(const VkMemoryPropertyFlags properties)
{
VkMemoryRequirements memoryRequirements = getMemoryRequirements();
uint32_t memoryTypeIndex = physicalDevice->getCompatibleMemoryTypeIndex(memoryRequirements.memoryTypeBits, properties);
const VkMemoryAllocateInfo memoryAllocateInfo =
{
VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
nullptr,
memoryRequirements.size,
memoryTypeIndex
};
checkVulkanError(vkAllocateMemory(device, &memoryAllocateInfo, nullptr, &bufferMemory), "vkAllocateMemory");
checkVulkanError(vkBindBufferMemory(device, buffer, bufferMemory, 0), "vkBindBufferMemory");
}
void uploadData(const void* source, const VkDeviceSize dataSize)
{
void* data;
checkVulkanError(vkMapMemory(device, bufferMemory, 0, dataSize, 0, &data), "vkMapMemory");
std::memcpy(data, source, static_cast<size_t>(dataSize));
vkUnmapMemory(device, bufferMemory);
}
void downloadData(void* target, const VkDeviceSize dataSize)
{
void* data;
checkVulkanError(vkMapMemory(device, bufferMemory, 0, dataSize, 0, &data), "vkMapMemory");
std::memcpy(target, data, static_cast<size_t>(dataSize));
vkUnmapMemory(device, bufferMemory);
}
void recordCopyDataCommand(VkCommandBuffer commandBuffer, VkBuffer sourceBuffer, const VkDeviceSize dataSize)
{
const VkCommandBufferBeginInfo commandBufferBeginInfo =
{
VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
nullptr,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
nullptr
};
const VkBufferCopy copyRegion =
{
0,
0,
dataSize
};
checkVulkanError(vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo), "vkBeginCommandBuffer");
vkCmdCopyBuffer(commandBuffer, sourceBuffer, buffer, 1, ©Region);
checkVulkanError(vkEndCommandBuffer(commandBuffer), "vkEndCommandBuffer");
}
VkDevice getDevice() const
{
return device;
}
const VulkanPhysicalDevice& getPhysicalDevice() const
{
return *physicalDevice;
}
VkBuffer getBuffer() const
{
return buffer;
}
VkDeviceSize getBufferSize() const
{
return bufferSize;
}
VkBufferUsageFlags getUsageFlags() const
{
return usageFlags;
}
size_t getElementSize() const
{
return elementSize;
}
ArgumentId getKernelArgumentId() const
{
return kernelArgumentId;
}
ArgumentDataType getDataType() const
{
return dataType;
}
ArgumentMemoryLocation getMemoryLocation() const
{
return memoryLocation;
}
ArgumentAccessType getAccessType() const
{
return accessType;
}
private:
VkDevice device;
const VulkanPhysicalDevice* physicalDevice;
VkBuffer buffer;
VkDeviceMemory bufferMemory;
VkDeviceSize bufferSize;
VkBufferUsageFlags usageFlags;
size_t elementSize;
ArgumentId kernelArgumentId;
ArgumentDataType dataType;
ArgumentMemoryLocation memoryLocation;
ArgumentAccessType accessType;
};
} // namespace ktt
|
panosdim/autotag
|
libs/tagparser/mp4/mp4tag.h
|
#ifndef TAG_PARSER_MP4TAG_H
#define TAG_PARSER_MP4TAG_H
#include "./mp4tagfield.h"
#include "../fieldbasedtag.h"
namespace TagParser {
class Mp4Atom;
class Mp4Tag;
struct TAG_PARSER_EXPORT Mp4ExtendedFieldId {
Mp4ExtendedFieldId(const char *mean = nullptr, const char *name = nullptr, bool updateOnly = false);
Mp4ExtendedFieldId(KnownField field);
operator bool() const;
bool matches(const Mp4TagField &field) const;
/// \brief mean parameter, usually Mp4TagExtendedMeanIds::iTunes
const char *mean;
/// \brief name parameter
const char *name;
/// \brief Whether only existing fields should be updated but *no* new extended field should be created
bool updateOnly;
};
/*!
* \brief Constructs a new instance with the specified parameter.
*/
inline Mp4ExtendedFieldId::Mp4ExtendedFieldId(const char *mean, const char *name, bool updateOnly)
: mean(mean)
, name(name)
, updateOnly(updateOnly)
{
}
/*!
* \brief Returns whether valid parameter are assigned.
*/
inline Mp4ExtendedFieldId::operator bool() const
{
return mean && name;
}
/*!
* \brief Returns whether the current parameter match the specified \a field.
*/
inline bool Mp4ExtendedFieldId::matches(const Mp4TagField &field) const
{
return field.mean() == mean && field.name() == name;
}
class TAG_PARSER_EXPORT Mp4TagMaker {
friend class Mp4Tag;
public:
void make(std::ostream &stream, Diagnostics &diag);
const Mp4Tag &tag() const;
std::uint64_t requiredSize() const;
private:
Mp4TagMaker(Mp4Tag &tag, Diagnostics &diag);
Mp4Tag &m_tag;
std::vector<Mp4TagFieldMaker> m_maker;
std::uint64_t m_metaSize;
std::uint64_t m_ilstSize;
bool m_omitPreDefinedGenre;
};
/*!
* \brief Returns the associated tag.
*/
inline const Mp4Tag &Mp4TagMaker::tag() const
{
return m_tag;
}
/*!
* \brief Returns the number of bytes which will be written when making the tag.
*/
inline std::uint64_t Mp4TagMaker::requiredSize() const
{
return m_metaSize;
}
/*!
* \brief Defines traits for the TagField implementation of the Mp4Tag class.
*/
template <> class TAG_PARSER_EXPORT FieldMapBasedTagTraits<Mp4Tag> {
public:
using FieldType = Mp4TagField;
using Compare = std::less<typename FieldType::IdentifierType>;
};
class TAG_PARSER_EXPORT Mp4Tag : public FieldMapBasedTag<Mp4Tag> {
friend class FieldMapBasedTag<Mp4Tag>;
public:
Mp4Tag();
static constexpr TagType tagType = TagType::Mp4Tag;
static constexpr const char *tagName = "MP4/iTunes tag";
static constexpr TagTextEncoding defaultTextEncoding = TagTextEncoding::Utf8;
bool canEncodingBeUsed(TagTextEncoding encoding) const override;
bool supportsField(KnownField field) const override;
using FieldMapBasedTag<Mp4Tag>::value;
const TagValue &value(KnownField value) const override;
using FieldMapBasedTag<Mp4Tag>::values;
std::vector<const TagValue *> values(KnownField field) const override;
const TagValue &value(const std::string &mean, const std::string &name) const;
const TagValue &value(const char *mean, const char *name) const;
using FieldMapBasedTag<Mp4Tag>::setValue;
bool setValue(KnownField field, const TagValue &value) override;
using FieldMapBasedTag<Mp4Tag>::setValues;
bool setValues(KnownField field, const std::vector<TagValue> &values) override;
bool setValue(const std::string &mean, const std::string &name, const TagValue &value);
bool setValue(const char *mean, const char *name, const TagValue &value);
using FieldMapBasedTag<Mp4Tag>::hasField;
bool hasField(KnownField value) const override;
bool supportsMultipleValues(KnownField) const override;
void parse(Mp4Atom &metaAtom, Diagnostics &diag);
Mp4TagMaker prepareMaking(Diagnostics &diag);
void make(std::ostream &stream, Diagnostics &diag);
protected:
IdentifierType internallyGetFieldId(KnownField field) const;
KnownField internallyGetKnownField(const IdentifierType &id) const;
};
/*!
* \brief Constructs a new tag.
*/
inline Mp4Tag::Mp4Tag()
{
}
inline bool Mp4Tag::supportsField(KnownField field) const
{
switch (field) {
case KnownField::EncoderSettings:
return true;
default:
return FieldMapBasedTag<Mp4Tag>::supportsField(field);
}
}
/*!
* \brief Returns the value of the field with the specified \a mean and \a name attributes.
*/
inline const TagValue &Mp4Tag::value(const std::string &mean, const std::string &name) const
{
return value(mean.data(), name.data());
}
/*!
* \brief Assigns the given \a value to the field with the specified \a mean and \a name attributes.
*/
inline bool Mp4Tag::setValue(const std::string &mean, const std::string &name, const TagValue &value)
{
return setValue(mean.data(), name.data(), value);
}
/*!
* \brief Returns false for all fields (for now).
* \remarks Not sure whether iTunes-style MP4 tags allow this. Let's return false for now.
* \todo Do some research whether it is supported or not.
*/
inline bool Mp4Tag::supportsMultipleValues(KnownField) const
{
return false;
}
} // namespace TagParser
#endif // TAG_PARSER_MP4TAG_H
|
JoseGarciaM/TC3049
|
studio/node_modules/@sanity/cli/lib/util/getUpgradeCommand.js
|
<reponame>JoseGarciaM/TC3049
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _path = _interopRequireDefault(require("path"));
var _which = _interopRequireDefault(require("which"));
var _isInstalledGlobally = _interopRequireDefault(require("is-installed-globally"));
var _debug = _interopRequireDefault(require("../debug"));
var _package = require("../../package.json");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getUpgradeCommand(options = {}) {
let {
cwd,
workDir
} = options;
cwd = cwd || process.cwd();
workDir = workDir || cwd;
if (_isInstalledGlobally.default && isInstalledUsingYarn()) {
(0, _debug.default)('CLI is installed globally with yarn');
return `yarn global add ${_package.name}`;
}
if (_isInstalledGlobally.default) {
(0, _debug.default)('CLI is installed globally with npm');
return `npm install -g ${_package.name}`;
}
const cmds = cwd === workDir ? [] : [`cd ${_path.default.relative(cwd, workDir)}`];
const hasGlobalYarn = Boolean(_which.default.sync('yarn', {
nothrow: true
}));
if (hasGlobalYarn) {
cmds.push(`yarn upgrade ${_package.name}`);
} else {
cmds.push(`./node_modules/.bin/sanity upgrade ${_package.name}`);
}
return cmds.join(' && ');
}
function isInstalledUsingYarn() {
const isWindows = process.platform === 'win32';
const yarnPath = isWindows ? _path.default.join('Yarn', 'config', 'global') : _path.default.join('.config', 'yarn', 'global');
return __dirname.includes(yarnPath);
}
var _default = getUpgradeCommand;
exports.default = _default;
|
gdefias/learn-java
|
java-basic/javalibs/src/main/java/apache_httpcomponents/asyncclient/AsynHttpClientDemo1.java
|
package apache_httpcomponents.asyncclient;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Defias
* Date: 2018-06
*
* AsynHttpClient
*/
import org.apache.http.client.fluent.Async;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.concurrent.FutureCallback;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AsynHttpClientDemo1 {
//异步get请求
public void doGetAsyn() throws InterruptedException, ExecutionException {
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
httpclient.start(); //开启httpclient
HttpGet httpGet = new HttpGet("http://www.baidu.com"); //开始执行
Future<HttpResponse> future = httpclient.execute(httpGet, null);
HttpResponse httpResponse = future.get();
System.out.println(httpResponse.getStatusLine()+"==="+httpGet.getRequestLine());
}
//异步的post方式请求
public static void doPostAsyn(String url,String outStr) throws ParseException, IOException, InterruptedException, ExecutionException {
CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.createDefault();
httpAsyncClient.start(); //开启httpclient
HttpPost httpost = new HttpPost(url);
httpost.addHeader(HTTP.CONTENT_TYPE, "application/json");
StringEntity se = new StringEntity(outStr,"UTF-8");
se.setContentType("application/json");
se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
httpost.setEntity(se);
//发送请求
Future<HttpResponse> future = httpAsyncClient.execute(httpost,null); //设置回调为空
System.out.println(future.get().toString());
}
//在后台线程中异步执行多个请求
public static void testFluentAsyn() {
Request[] requests = new Request[]{
Request.Get("http://www.baidu.com/"),
Request.Get("http://www.yahoo.com/"),
Request.Get("http://www.apache.com/"),
Request.Get("http://www.apple.com/")
};
Queue<Future<Content>> queue = new LinkedList<>();
/**
* 异步执行GET请求
*/
ExecutorService es = Executors.newFixedThreadPool(4);
Async async = Async.newInstance().use(es);
for (final Request request : requests) {
Future<Content> future = async.execute(request, new FutureCallback<Content>() {
@Override
public void completed(Content content) {
System.out.println(System.currentTimeMillis() + " Request completed: " + request);
}
@Override
public void failed(Exception e) {
System.out.println(e.getMessage() + ": " + request);
}
@Override
public void cancelled() {
System.out.println("Request cancelled: " + request);
}
});
queue.add(future);
}
Future<Content> future;
while ((future = queue.poll()) != null) {
if (future.isDone()) {
if (!future.isCancelled()) {
try {
future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
future.cancel(true);
} catch (ExecutionException e) {
System.out.println(e.getMessage());
}
}
} else {
queue.add(future);
}
}
System.out.println("done");
es.shutdown();
}
}
|
qwe321q3/jvm
|
web-servlet3/src/main/java/servlet3/UserSerlvet.java
|
package servlet3;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author tianshuo
*/
@WebServlet(urlPatterns = "/user")
public class UserSerlvet extends HttpServlet {
private static final long serialVersionUID = 9078228534910617681L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletOutputStream outputStream = resp.getOutputStream();
outputStream.write("aaa".getBytes());
}
}
|
ClarkResearchGroup/tensor-tools
|
qtensor/qtensor_op.h
|
/*
* Copyright 2020 <NAME>, <NAME>, and <NAME>
*
* 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.
*/
#ifndef QUANTUM_NUMBERED_TENSOR_OPERATIONS_HEADER
#define QUANTUM_NUMBERED_TENSOR_OPERATIONS_HEADER
#include "../util/types_and_headers.h"
#include "../linalg/lapack_wrapper.h"
#include "qtensor_index.h"
#include "qtensor_index_op.h"
#include "qtensor.h"
#define MoveFromLeft 0
#define MoveFromRight 1
template <typename T>
void qr(qtensor<T>& A,
vector<qtensor_index>& left, vector<qtensor_index>& right,
qtensor<T>& Q, qtensor<T>& R);
/*template <typename T>
void svd(qtensor<T>& A,
vector<qtensor_index>& left, vector<qtensor_index>& right,
qtensor<T>& U, qtensor<T>& V, vector<double>& S,
int direction);
template <typename T>
void svd(qtensor<T>& A,
vector<qtensor_index>& left, vector<qtensor_index>& right,
qtensor<T>& U, qtensor<T>& V, vector<double>& S,
int direction, double cutoff);*/
template <typename T>
void svd(qtensor<T>& A,
vector<qtensor_index>& left, vector<qtensor_index>& right,
qtensor<T>& U, qtensor<T>& V, qtensor<T>& S,
int direction, double cutoff=0, unsigned K=0);
/*template <typename T>
void svd_bond(qtensor<T>& A_left, qtensor<T>& A_right,
qtensor_index& mid, vector<double>& S,
int direction);*/
template <typename T>
void svd_bond(qtensor<T>& A_left, qtensor<T>& A_right,
qtensor_index& mid, qtensor<T>& S,
int direction, double cutoff=0, long unsigned K=0);
template <typename T>
void svd_bond(qtensor<T>& combined, qtensor<T>& A_left, qtensor<T>& A_right,
qtensor_index& mid, qtensor<T>& S,
int direction, double cutoff=0, long unsigned K=0);
#endif
|
michal55/WebX
|
app/controllers/projects_controller.rb
|
class ProjectsController < ApplicationController
load_and_authorize_resource :except => [:create]
# skip_authorize_resource :only => [:new, :index, :create]
def index
@project_new = Project.new
@projects = Project.where(user_id: current_user.id)
end
def create
@project_new = Project.new
@project_new.assign_attributes({name: params[:project][:name], user_id: current_user.id})
@project_new.save!
flash[:notice] = I18n.t('projects.flash_create', project_name: @project_new.name)
redirect_to projects_path
end
def new
@project_new = Project.new
end
def edit
@project = Project.find(params[:id])
end
def show
@project = Project.find(params[:id])
@scripts = Script.where(project_id: params[:id])
@data_field = DataField.where(project: @project)
@data_field_new = DataField.new
@data_field_new.project = @project
@script_new = Script.new
@script_new.project_id = params[:project_id]
authorize! :read, @project
end
def update
@project = Project.find(params[:id])
@project.name = params[:project][:name]
@project.save!
respond_to do |format|
format.text { render(nothing: true, status: 200, content_type: "text/html") }
format.js { render :js => "flash(\"#{ I18n.t('projects.flash_update', project_name: @project.name)}\");" }
end
end
def destroy
@project = Project.find(params[:id])
flash[:notice] = I18n.t('projects.flash_delete', project_name: @project.name)
@project.destroy!
redirect_to projects_path
end
end
|
csiro-wsn/freertos
|
core_csiro/libraries/inc/address.h
|
/*
* Copyright (c) 2020, Commonwealth Scientific and Industrial Research
* Organisation (CSIRO) ABN 41 687 119 230.
*
* Filename: address.h
* Creation_Date: 18/06/2019
* Author: <NAME> <<EMAIL>>
*
* Common Address and Address related functionality for core libraries
*
*/
#ifndef __CSIRO_CORE_ADDRESS
#define __CSIRO_CORE_ADDRESS
/* Includes -------------------------------------------------*/
#include <stdbool.h>
#include <stdint.h>
#include "memory_operations.h"
/* Module Defines -------------------------------------------*/
// clang-format off
#define MAC_ADDRESS_LENGTH 6
#define BASE_ADDRESS 0x000000000000
#define BROADCAST_ADDRESS 0xFFFFFFFFFFFF
#define LOCAL_ADDRESS xLocalAddress
#define ADDRESS_FMT "%012llX"
// clang-format on
/* Type Definitions -----------------------------------------*/
typedef uint64_t xAddress_t;
extern xAddress_t xLocalAddress;
/* Function Declarations ------------------------------------*/
static inline void vAddressPack( uint8_t pucAddress[MAC_ADDRESS_LENGTH], xAddress_t xAddress )
{
LE_U48_PACK( pucAddress, xAddress );
}
static inline xAddress_t xAddressUnpack( const uint8_t pucAddress[MAC_ADDRESS_LENGTH] )
{
return (xAddress_t) LE_U48_EXTRACT( pucAddress );
}
static inline bool bIsLocalAddress( xAddress_t xAddress )
{
return xAddress == LOCAL_ADDRESS;
}
static inline bool bIsBroadcastAddress( xAddress_t xAddress )
{
return xAddress == BROADCAST_ADDRESS;
}
static inline bool bIsBaseAddress( xAddress_t xAddress )
{
return xAddress == BASE_ADDRESS;
}
static inline bool bAddressesMatch( xAddress_t xAddressA, xAddress_t xAddressB )
{
return xAddressA == xAddressB;
}
static inline bool bAddressesU24Match( xAddress_t xAddressA, xAddress_t xAddressB )
{
return ( xAddressA & 0xFFFFFF000000 ) == ( xAddressB & 0xFFFFFF000000 );
}
#endif /* __CSIRO_CORE_ADDRESS */
|
candidomorantepelaez/ari-electron
|
electron/app/client/module.js
|
<gh_stars>0
const routes = include("app/client/routes");
module.exports = {
name: "clients",
routes,
tables: ["clients"]
}
|
isabella232/wireless-media-drive
|
linux-2.6.35.3/drivers/mxc/security/sahara2/sah_driver_interface.c
|
<filename>linux-2.6.35.3/drivers/mxc/security/sahara2/sah_driver_interface.c
/*
* Copyright (C) 2004-2011 Freescale Semiconductor, Inc. All Rights Reserved.
*/
/*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
/*!
* @file sah_driver_interface.c
*
* @brief Provides a Linux Kernel Module interface to the SAHARA h/w device.
*
*/
/* SAHARA Includes */
#include <sah_driver_common.h>
#include <sah_kernel.h>
#include <sah_memory_mapper.h>
#include <sah_queue_manager.h>
#include <sah_status_manager.h>
#include <sah_interrupt_handler.h>
#include <sah_hardware_interface.h>
#include <fsl_shw_keystore.h>
#include <adaptor.h>
#ifdef FSL_HAVE_SCC
#include <linux/mxc_scc_driver.h>
#else
#include <linux/mxc_scc2_driver.h>
#endif
#ifdef DIAG_DRV_IF
#include <diagnostic.h>
#endif
#if defined(CONFIG_DEVFS_FS) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0))
#include <linux/devfs_fs_kernel.h>
#else
#include <linux/proc_fs.h>
#endif
#ifdef PERF_TEST
#define interruptible_sleep_on(x) sah_Handle_Interrupt()
#endif
#define TEST_MODE_OFF 1
#define TEST_MODE_ON 2
/*! Version register on first deployments */
#define SAHARA_VERSION2 2
/*! Version register on MX27 */
#define SAHARA_VERSION3 3
/*! Version register on MXC92323 */
#define SAHARA_VERSION4 4
/******************************************************************************
* Module function declarations
******************************************************************************/
OS_DEV_INIT_DCL(sah_init);
OS_DEV_SHUTDOWN_DCL(sah_cleanup);
OS_DEV_OPEN_DCL(sah_open);
OS_DEV_CLOSE_DCL(sah_release);
OS_DEV_IOCTL_DCL(sah_ioctl);
OS_DEV_MMAP_DCL(sah_mmap);
static os_error_code sah_handle_get_capabilities(fsl_shw_uco_t* user_ctx,
uint32_t info);
static void sah_user_callback(fsl_shw_uco_t * user_ctx);
static os_error_code sah_handle_scc_sfree(fsl_shw_uco_t* user_ctx,
uint32_t info);
static os_error_code sah_handle_scc_sstatus(fsl_shw_uco_t* user_ctx,
uint32_t info);
static os_error_code sah_handle_scc_drop_perms(fsl_shw_uco_t* user_ctx,
uint32_t info);
static os_error_code sah_handle_scc_encrypt(fsl_shw_uco_t* user_ctx,
uint32_t info);
static os_error_code sah_handle_scc_decrypt(fsl_shw_uco_t* user_ctx,
uint32_t info);
#ifdef FSL_HAVE_SCC2
static fsl_shw_return_t register_user_partition(fsl_shw_uco_t * user_ctx,
uint32_t user_base,
void *kernel_base);
static fsl_shw_return_t deregister_user_partition(fsl_shw_uco_t * user_ctx,
uint32_t user_base);
#endif
static os_error_code sah_handle_sk_slot_alloc(uint32_t info);
static os_error_code sah_handle_sk_slot_dealloc(uint32_t info);
static os_error_code sah_handle_sk_slot_load(uint32_t info);
static os_error_code sah_handle_sk_slot_read(uint32_t info);
static os_error_code sah_handle_sk_slot_decrypt(uint32_t info);
static os_error_code sah_handle_sk_slot_encrypt(uint32_t info);
/*! Boolean flag for whether interrupt handler needs to be released on exit */
static unsigned interrupt_registered;
static int handle_sah_ioctl_dar(fsl_shw_uco_t * filp, uint32_t user_space_desc);
#if !defined(CONFIG_DEVFS_FS) || (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
static int sah_read_procfs(char *buf,
char **start,
off_t offset, int count, int *eof, void *data);
static int sah_write_procfs(struct file *file, const char __user * buffer,
unsigned long count, void *data);
#endif
#if defined(CONFIG_DEVFS_FS) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0))
/* This is a handle to the sahara DEVFS entry. */
static devfs_handle_t Sahara_devfs_handle;
#else
/* Major number assigned to our device driver */
static int Major;
/* This is a handle to the sahara PROCFS entry */
static struct proc_dir_entry *Sahara_procfs_handle;
#endif
uint32_t sah_hw_version;
extern void *sah_virt_base;
/* This is the wait queue to this driver. Linux declaration. */
DECLARE_WAIT_QUEUE_HEAD(Wait_queue);
/* This is a global variable that is used to track how many times the device
* has been opened simultaneously. */
#ifdef DIAG_DRV_IF
static int Device_in_use = 0;
#endif
/* This is the system keystore object */
fsl_shw_kso_t system_keystore;
/*!
* OS-dependent handle used for registering user interface of a driver.
*/
static os_driver_reg_t reg_handle;
#ifdef DIAG_DRV_IF
/* This is for sprintf() to use when constructing output. */
#define DIAG_MSG_SIZE 1024
static char Diag_msg[DIAG_MSG_SIZE];
#endif
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18))
/** Pointer to Sahara clock information. Initialized during os_dev_init(). */
static struct clk *sah_clk;
#endif
/*!
*******************************************************************************
* This function gets called when the module is inserted (insmod) into the
* running kernel.
*
* @brief SAHARA device initialisation function.
*
* @return 0 on success
* @return -EBUSY if the device or proc file entry cannot be created.
* @return OS_ERROR_NO_MEMORY_S if kernel memory could not be allocated.
* @return OS_ERROR_FAIL_S if initialisation of proc entry failed
*/
OS_DEV_INIT(sah_init)
{
/* Status variable */
int os_error_code = 0;
uint32_t sah_phys_base = SAHARA_BASE_ADDR;
interrupt_registered = 0;
/* Enable the SAHARA Clocks */
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA : Enabling the IPG and AHB clocks\n")
#endif /*DIAG_DRV_IF */
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,18))
mxc_clks_enable(SAHARA2_CLK);
#else
{
sah_clk = clk_get(NULL, "sahara_clk");
if (IS_ERR(sah_clk))
os_error_code = PTR_ERR(sah_clk);
else
clk_enable(sah_clk);
}
#endif
if (cpu_is_mx53())
sah_phys_base -= 0x20000000;
sah_virt_base = (void *)ioremap(sah_phys_base, SZ_16K);
if (sah_virt_base == NULL) {
os_printk(KERN_ERR
"SAHARA: Register mapping failed\n");
os_error_code = OS_ERROR_FAIL_S;
}
if (os_error_code == OS_ERROR_OK_S) {
sah_hw_version = sah_HW_Read_Version();
os_printk("Sahara HW Version is 0x%08x\n", sah_hw_version);
/* verify code and hardware are version compatible */
if ((sah_hw_version != SAHARA_VERSION2)
&& (sah_hw_version != SAHARA_VERSION3)) {
if (((sah_hw_version >> 8) & 0xff) != SAHARA_VERSION4) {
os_printk
("Sahara HW Version was not expected value.\n");
os_error_code = OS_ERROR_FAIL_S;
}
}
}
if (os_error_code == OS_ERROR_OK_S) {
#ifdef DIAG_DRV_IF
LOG_KDIAG("Calling sah_Init_Mem_Map to initialise "
"memory subsystem.");
#endif
/* Do any memory-routine initialization */
os_error_code = sah_Init_Mem_Map();
}
if (os_error_code == OS_ERROR_OK_S) {
#ifdef DIAG_DRV_IF
LOG_KDIAG("Calling sah_HW_Reset() to Initialise the Hardware.");
#endif
/* Initialise the hardware */
os_error_code = sah_HW_Reset();
if (os_error_code != OS_ERROR_OK_S) {
os_printk
("sah_HW_Reset() failed to Initialise the Hardware.\n");
}
}
if (os_error_code == OS_ERROR_OK_S) {
#if defined(CONFIG_DEVFS_FS) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0))
/* Register the DEVFS entry */
Sahara_devfs_handle = devfs_register(NULL,
SAHARA_DEVICE_SHORT,
DEVFS_FL_AUTO_DEVNUM,
0, 0,
SAHARA_DEVICE_MODE,
&Fops, NULL);
if (Sahara_devfs_handle == NULL) {
#ifdef DIAG_DRV_IF
LOG_KDIAG
("Registering the DEVFS character device failed.");
#endif /* DIAG_DRV_IF */
os_error_code = -EBUSY;
}
#else /* CONFIG_DEVFS_FS */
/* Create the PROCFS entry. This is used to report the assigned device
* major number back to user-space. */
#if 1
Sahara_procfs_handle = create_proc_entry(SAHARA_DEVICE_SHORT, 0700, /* default mode */
NULL); /* parent dir */
if (Sahara_procfs_handle == NULL) {
#ifdef DIAG_DRV_IF
LOG_KDIAG("Registering the PROCFS interface failed.");
#endif /* DIAG_DRV_IF */
os_error_code = OS_ERROR_FAIL_S;
} else {
Sahara_procfs_handle->nlink = 1;
Sahara_procfs_handle->data = 0;
Sahara_procfs_handle->read_proc = sah_read_procfs;
Sahara_procfs_handle->write_proc = sah_write_procfs;
}
#endif /* #if 1 */
}
if (os_error_code == OS_ERROR_OK_S) {
#ifdef DIAG_DRV_IF
LOG_KDIAG
("Calling sah_Queue_Manager_Init() to Initialise the Queue "
"Manager.");
#endif
/* Initialise the Queue Manager */
if (sah_Queue_Manager_Init() != FSL_RETURN_OK_S) {
os_error_code = -ENOMEM;
}
}
#ifndef SAHARA_POLL_MODE
if (os_error_code == OS_ERROR_OK_S) {
#ifdef DIAG_DRV_IF
LOG_KDIAG("Calling sah_Intr_Init() to Initialise the Interrupt "
"Handler.");
#endif
/* Initialise the Interrupt Handler */
os_error_code = sah_Intr_Init(&Wait_queue);
if (os_error_code == OS_ERROR_OK_S) {
interrupt_registered = 1;
}
}
#endif /* ifndef SAHARA_POLL_MODE */
#ifdef SAHARA_POWER_MANAGEMENT
if (os_error_code == OS_ERROR_OK_S) {
/* set up dynamic power management (dmp) */
os_error_code = sah_dpm_init();
}
#endif
if (os_error_code == OS_ERROR_OK_S) {
os_driver_init_registration(reg_handle);
os_driver_add_registration(reg_handle, OS_FN_OPEN,
OS_DEV_OPEN_REF(sah_open));
os_driver_add_registration(reg_handle, OS_FN_IOCTL,
OS_DEV_IOCTL_REF(sah_ioctl));
os_driver_add_registration(reg_handle, OS_FN_CLOSE,
OS_DEV_CLOSE_REF(sah_release));
os_driver_add_registration(reg_handle, OS_FN_MMAP,
OS_DEV_MMAP_REF(sah_mmap));
os_error_code =
os_driver_complete_registration(reg_handle, Major,
"sahara");
if (os_error_code < OS_ERROR_OK_S) {
#ifdef DIAG_DRV_IF
snprintf(Diag_msg, DIAG_MSG_SIZE,
"Registering the regular "
"character device failed with error code: %d\n",
os_error_code);
LOG_KDIAG(Diag_msg);
#endif
}
}
#endif /* CONFIG_DEVFS_FS */
if (os_error_code == OS_ERROR_OK_S) {
/* set up the system keystore, using the default keystore handler */
fsl_shw_init_keystore_default(&system_keystore);
if (fsl_shw_establish_keystore(NULL, &system_keystore)
== FSL_RETURN_OK_S) {
os_error_code = OS_ERROR_OK_S;
} else {
os_error_code = OS_ERROR_FAIL_S;
}
if (os_error_code != OS_ERROR_OK_S) {
#ifdef DIAG_DRV_IF
snprintf(Diag_msg, DIAG_MSG_SIZE,
"Registering the system keystore "
"failed with error code: %d\n", os_error_code);
LOG_KDIAG(Diag_msg);
#endif
}
}
if (os_error_code != OS_ERROR_OK_S) {
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0))
cleanup_module();
#else
sah_cleanup();
#endif
}
#ifdef DIAG_DRV_IF
else {
LOG_KDIAG_ARGS("Sahara major node is %d\n", Major);
}
#endif
/* Disabling the Clock after the driver has been registered fine.
This is done to save power when Sahara is not in use.*/
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA : Disabling the clocks\n")
#endif /* DIAG_DRV_IF */
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18))
mxc_clks_disable(SAHARA2_CLK);
#else
{
if (IS_ERR(sah_clk))
os_error_code = PTR_ERR(sah_clk);
else
clk_disable(sah_clk);
}
#endif
os_dev_init_return(os_error_code);
}
/*!
*******************************************************************************
* This function gets called when the module is removed (rmmod) from the running
* kernel.
*
* @brief SAHARA device clean-up function.
*
* @return void
*/
OS_DEV_SHUTDOWN(sah_cleanup)
{
int ret_val = 0;
printk(KERN_ALERT "Sahara going into cleanup\n");
/* clear out the system keystore */
fsl_shw_release_keystore(NULL, &system_keystore);
/* Unregister the device */
#if defined(CONFIG_DEVFS_FS) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0))
devfs_unregister(Sahara_devfs_handle);
#else
if (Sahara_procfs_handle != NULL) {
remove_proc_entry(SAHARA_DEVICE_SHORT, NULL);
}
if (Major >= 0) {
ret_val = os_driver_remove_registration(reg_handle);
}
#ifdef DIAG_DRV_IF
if (ret_val < 0) {
snprintf(Diag_msg, DIAG_MSG_SIZE, "Error while attempting to "
"unregister the device: %d\n", ret_val);
LOG_KDIAG(Diag_msg);
}
#endif
#endif /* CONFIG_DEVFS_FS */
sah_Queue_Manager_Close();
#ifndef SAHARA_POLL_MODE
if (interrupt_registered) {
sah_Intr_Release();
interrupt_registered = 0;
}
#endif
sah_Stop_Mem_Map();
#ifdef SAHARA_POWER_MANAGEMENT
sah_dpm_close();
#endif
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA : Disabling the clocks\n")
#endif /* DIAG_DRV_IF */
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,18))
mxc_clks_disable(SAHARA2_CLK);
#else
{
if (IS_ERR(sah_clk))
ret_val = PTR_ERR(sah_clk);
else
clk_disable(sah_clk);
clk_put(sah_clk);
}
#endif
os_dev_shutdown_return(ret_val);
}
/*!
*******************************************************************************
* This function simply increments the module usage count.
*
* @brief SAHARA device open function.
*
* @param inode Part of the kernel prototype.
* @param file Part of the kernel prototype.
*
* @return 0 - Always returns 0 since any number of calls to this function are
* allowed.
*
*/
OS_DEV_OPEN(sah_open)
{
#if defined(LINUX_VERSION) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,10))
MOD_INC_USE_COUNT;
#endif
#ifdef DIAG_DRV_IF
Device_in_use++;
snprintf(Diag_msg, DIAG_MSG_SIZE,
"Incrementing module use count to: %d ", Device_in_use);
LOG_KDIAG(Diag_msg);
#endif
os_dev_set_user_private(NULL);
/* Return 0 to indicate success */
os_dev_open_return(0);
}
/*!
*******************************************************************************
* This function simply decrements the module usage count.
*
* @brief SAHARA device release function.
*
* @param inode Part of the kernel prototype.
* @param file Part of the kernel prototype.
*
* @return 0 - Always returns 0 since this function does not fail.
*/
OS_DEV_CLOSE(sah_release)
{
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
#if defined(LINUX_VERSION) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,10))
MOD_DEC_USE_COUNT;
#endif
#ifdef DIAG_DRV_IF
Device_in_use--;
snprintf(Diag_msg, DIAG_MSG_SIZE,
"Decrementing module use count to: %d ", Device_in_use);
LOG_KDIAG(Diag_msg);
#endif
if (user_ctx != NULL) {
sah_handle_deregistration(user_ctx);
os_free_memory(user_ctx);
os_dev_set_user_private(NULL);
}
/* Return 0 to indicate success */
os_dev_close_return(OS_ERROR_OK_S);
}
/*!
*******************************************************************************
* This function provides the IO Controls for the SAHARA driver. Three IO
* Controls are supported:
*
* SAHARA_HWRESET and
* SAHARA_SET_HA
* SAHARA_CHK_TEST_MODE
*
* @brief SAHARA device IO Control function.
*
* @param inode Part of the kernel prototype.
* @param filp Part of the kernel prototype.
* @param cmd Part of the kernel prototype.
* @param arg Part of the kernel prototype.
*
* @return 0 on success
* @return -EBUSY if the HA bit could not be set due to busy hardware.
* @return -ENOTTY if an unsupported IOCTL was attempted on the device.
* @return -EFAULT if put_user() fails
*/
OS_DEV_IOCTL(sah_ioctl)
{
int status = 0;
int test_mode;
switch (os_dev_get_ioctl_op()) {
case SAHARA_HWRESET:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_HWRESET IOCTL.");
#endif
/* We need to reset the hardware. */
sah_HW_Reset();
/* Mark all the entries in the Queue Manager's queue with state
* SAH_STATE_RESET.
*/
sah_Queue_Manager_Reset_Entries();
/* Wake up all sleeping write() calls. */
wake_up_interruptible(&Wait_queue);
break;
#ifdef SAHARA_HA_ENABLED
case SAHARA_SET_HA:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SET_HA IOCTL.");
#endif /* DIAG_DRV_IF */
if (sah_HW_Set_HA() == ERR_INTERNAL) {
status = -EBUSY;
}
break;
#endif /* SAHARA_HA_ENABLED */
case SAHARA_CHK_TEST_MODE:
/* load test_mode */
test_mode = TEST_MODE_OFF;
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_CHECK_TEST_MODE IOCTL.");
test_mode = TEST_MODE_ON;
#endif /* DIAG_DRV_IF */
#if defined(KERNEL_TEST) || defined(PERF_TEST)
test_mode = TEST_MODE_ON;
#endif /* KERNEL_TEST || PERF_TEST */
/* copy test_mode back to user space. put_user() is Linux fn */
/* compiler warning `register': no problem found so ignored */
status = put_user(test_mode, (int *)os_dev_get_ioctl_arg());
break;
case SAHARA_DAR:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_DAR IOCTL.");
#endif /* DIAG_DRV_IF */
{
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
if (user_ctx != NULL) {
status =
handle_sah_ioctl_dar(user_ctx,
os_dev_get_ioctl_arg
());
} else {
status = OS_ERROR_FAIL_S;
}
}
break;
case SAHARA_GET_RESULTS:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_GET_RESULTS IOCTL.");
#endif /* DIAG_DRV_IF */
{
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
if (user_ctx != NULL) {
status =
sah_get_results_pointers(user_ctx,
os_dev_get_ioctl_arg
());
} else {
status = OS_ERROR_FAIL_S;
}
}
break;
case SAHARA_REGISTER:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_REGISTER IOCTL.");
#endif /* DIAG_DRV_IF */
{
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
if (user_ctx != NULL) {
status = OS_ERROR_FAIL_S; /* already registered */
} else {
user_ctx =
os_alloc_memory(sizeof(fsl_shw_uco_t),
GFP_KERNEL);
if (user_ctx == NULL) {
status = OS_ERROR_NO_MEMORY_S;
} else {
/* Copy UCO from user, but only as big as the common UCO */
if (os_copy_from_user(user_ctx,
(void *)
os_dev_get_ioctl_arg
(),
offsetof
(fsl_shw_uco_t,
result_pool))) {
status = OS_ERROR_FAIL_S;
} else {
os_dev_set_user_private
(user_ctx);
status =
sah_handle_registration
(user_ctx);
}
}
}
}
break;
/* This ioctl cmd should disappear in favor of a close() routine. */
case SAHARA_DEREGISTER:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_DEREGISTER IOCTL.");
#endif /* DIAG_DRV_IF */
{
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
if (user_ctx == NULL) {
status = OS_ERROR_FAIL_S;
} else {
status = sah_handle_deregistration(user_ctx);
os_free_memory(user_ctx);
os_dev_set_user_private(NULL);
}
}
break;
case SAHARA_SCC_DROP_PERMS:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SCC_DROP_PERMS IOCTL.");
#endif /* DIAG_DRV_IF */
{
/* drop permissions on the specified partition */
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
status =
sah_handle_scc_drop_perms(user_ctx,
os_dev_get_ioctl_arg());
}
break;
case SAHARA_SCC_SFREE:
/* Unmap the specified partition from the users space, and then
* free it for use by someone else.
*/
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SCC_SFREE IOCTL.");
#endif /* DIAG_DRV_IF */
{
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
status =
sah_handle_scc_sfree(user_ctx,
os_dev_get_ioctl_arg());
}
break;
case SAHARA_SCC_SSTATUS:
/* Unmap the specified partition from the users space, and then
* free it for use by someone else.
*/
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SCC_SSTATUS IOCTL.");
#endif /* DIAG_DRV_IF */
{
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
status =
sah_handle_scc_sstatus(user_ctx,
os_dev_get_ioctl_arg());
}
break;
case SAHARA_SCC_ENCRYPT:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SCC_ENCRYPT IOCTL.");
#endif /* DIAG_DRV_IF */
{
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
status =
sah_handle_scc_encrypt(user_ctx,
os_dev_get_ioctl_arg());
}
break;
case SAHARA_SCC_DECRYPT:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SCC_DECRYPT IOCTL.");
#endif /* DIAG_DRV_IF */
{
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
status =
sah_handle_scc_decrypt(user_ctx,
os_dev_get_ioctl_arg());
}
break;
case SAHARA_SK_ALLOC:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SK_ALLOC IOCTL.");
#endif /* DIAG_DRV_IF */
status = sah_handle_sk_slot_alloc(os_dev_get_ioctl_arg());
break;
case SAHARA_SK_DEALLOC:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SK_DEALLOC IOCTL.");
#endif /* DIAG_DRV_IF */
status = sah_handle_sk_slot_dealloc(os_dev_get_ioctl_arg());
break;
case SAHARA_SK_LOAD:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SK_LOAD IOCTL.");
#endif /* DIAG_DRV_IF */
status = sah_handle_sk_slot_load(os_dev_get_ioctl_arg());
break;
case SAHARA_SK_READ:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SK_READ IOCTL.");
#endif /* DIAG_DRV_IF */
status = sah_handle_sk_slot_read(os_dev_get_ioctl_arg());
break;
case SAHARA_SK_SLOT_DEC:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SK_SLOT_DECRYPT IOCTL.");
#endif /* DIAG_DRV_IF */
status = sah_handle_sk_slot_decrypt(os_dev_get_ioctl_arg());
break;
case SAHARA_SK_SLOT_ENC:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_SK_SLOT_ENCRYPT IOCTL.");
#endif /* DIAG_DRV_IF */
status = sah_handle_sk_slot_encrypt(os_dev_get_ioctl_arg());
break;
case SAHARA_GET_CAPS:
#ifdef DIAG_DRV_IF
LOG_KDIAG("SAHARA_GET_CAPS IOCTL.");
#endif /* DIAG_DRV_IF */
{
fsl_shw_uco_t *user_ctx = os_dev_get_user_private();
status =
sah_handle_get_capabilities(user_ctx,
os_dev_get_ioctl_arg());
}
break;
default:
#ifdef DIAG_DRV_IF
LOG_KDIAG("Unknown SAHARA IOCTL.");
#endif /* DIAG_DRV_IF */
status = OS_ERROR_FAIL_S;
}
os_dev_ioctl_return(status);
}
/* Fill in the user's capabilities structure */
static os_error_code sah_handle_get_capabilities(fsl_shw_uco_t * user_ctx,
uint32_t info)
{
os_error_code status = OS_ERROR_FAIL_S;
fsl_shw_pco_t capabilities;
status = os_copy_from_user(&capabilities, (void *)info,
sizeof(fsl_shw_pco_t));
if (status != OS_ERROR_OK_S) {
goto out;
}
if (get_capabilities(user_ctx, &capabilities) == FSL_RETURN_OK_S) {
status = os_copy_to_user((void *)info, &capabilities,
sizeof(fsl_shw_pco_t));
}
out:
return status;
}
#ifdef FSL_HAVE_SCC2
/* Find the kernel-mode address of the partition.
* This can then be passed to the SCC functions.
*/
void *lookup_user_partition(fsl_shw_uco_t * user_ctx, uint32_t user_base)
{
/* search through the partition chain to find one that matches the user base
* address.
*/
fsl_shw_spo_t *curr = (fsl_shw_spo_t *) user_ctx->partition;
while (curr != NULL) {
if (curr->user_base == user_base) {
return curr->kernel_base;
}
curr = (fsl_shw_spo_t *) curr->next;
}
return NULL;
}
/* user_base: userspace base address of the partition
* kernel_base: kernel mode base address of the partition
*/
static fsl_shw_return_t register_user_partition(fsl_shw_uco_t * user_ctx,
uint32_t user_base,
void *kernel_base)
{
fsl_shw_spo_t *partition_info;
fsl_shw_return_t ret = FSL_RETURN_ERROR_S;
if (user_ctx == NULL) {
goto out;
}
partition_info = os_alloc_memory(sizeof(fsl_shw_spo_t), GFP_KERNEL);
if (partition_info == NULL) {
goto out;
}
/* stuff the partition info, then put it at the front of the chain */
partition_info->user_base = user_base;
partition_info->kernel_base = kernel_base;
partition_info->next = user_ctx->partition;
user_ctx->partition = (struct fsl_shw_spo_t *)partition_info;
#ifdef DIAG_DRV_IF
LOG_KDIAG_ARGS
("partition with user_base=%p, kernel_base=%p registered.",
(void *)user_base, kernel_base);
#endif
ret = FSL_RETURN_OK_S;
out:
return ret;
}
/* if the partition is in the users list, remove it */
static fsl_shw_return_t deregister_user_partition(fsl_shw_uco_t * user_ctx,
uint32_t user_base)
{
fsl_shw_spo_t *curr = (fsl_shw_spo_t *) user_ctx->partition;
fsl_shw_spo_t *last = (fsl_shw_spo_t *) user_ctx->partition;
while (curr != NULL) {
if (curr->user_base == user_base) {
#ifdef DIAG_DRV_IF
LOG_KDIAG_ARGS
("deregister_user_partition: partition with "
"user_base=%p, kernel_base=%p deregistered.\n",
(void *)curr->user_base, curr->kernel_base);
#endif
if (last == curr) {
user_ctx->partition = curr->next;
os_free_memory(curr);
return FSL_RETURN_OK_S;
} else {
last->next = curr->next;
os_free_memory(curr);
return FSL_RETURN_OK_S;
}
}
last = curr;
curr = (fsl_shw_spo_t *) curr->next;
}
return FSL_RETURN_ERROR_S;
}
#endif /* FSL_HAVE_SCC2 */
static os_error_code sah_handle_scc_drop_perms(fsl_shw_uco_t * user_ctx,
uint32_t info)
{
os_error_code status = OS_ERROR_NO_MEMORY_S;
#ifdef FSL_HAVE_SCC2
scc_return_t scc_ret;
scc_partition_info_t partition_info;
void *kernel_base;
status =
os_copy_from_user(&partition_info, (void *)info,
sizeof(partition_info));
if (status != OS_ERROR_OK_S) {
goto out;
}
/* validate that the user owns this partition, and look up its handle */
kernel_base = lookup_user_partition(user_ctx, partition_info.user_base);
if (kernel_base == NULL) {
status = OS_ERROR_FAIL_S;
#ifdef DIAG_DRV_IF
LOG_KDIAG("_scc_drop_perms(): failed to find partition\n");
#endif
goto out;
}
/* call scc driver to perform the drop */
scc_ret = scc_diminish_permissions(kernel_base,
partition_info.permissions);
if (scc_ret == SCC_RET_OK) {
status = OS_ERROR_OK_S;
} else {
status = OS_ERROR_FAIL_S;
}
out:
#endif /* FSL_HAVE_SCC2 */
return status;
}
static os_error_code sah_handle_scc_sfree(fsl_shw_uco_t * user_ctx,
uint32_t info)
{
os_error_code status = OS_ERROR_NO_MEMORY_S;
#ifdef FSL_HAVE_SCC2
{
scc_partition_info_t partition_info;
void *kernel_base;
int ret;
status =
os_copy_from_user(&partition_info, (void *)info,
sizeof(partition_info));
/* check that the copy was successful */
if (status != OS_ERROR_OK_S) {
goto out;
}
/* validate that the user owns this partition, and look up its handle */
kernel_base =
lookup_user_partition(user_ctx, partition_info.user_base);
if (kernel_base == NULL) {
status = OS_ERROR_FAIL_S;
#ifdef DIAG_DRV_IF
LOG_KDIAG("failed to find partition\n");
#endif /*DIAG_DRV_IF */
goto out;
}
/* Unmap the memory region (see sys_munmap in mmap.c) */
ret = unmap_user_memory(partition_info.user_base, 8192);
/* If the memory was successfully released */
if (ret == OS_ERROR_OK_S) {
/* release the partition */
scc_release_partition(kernel_base);
/* and remove it from the users context */
deregister_user_partition(user_ctx,
partition_info.user_base);
status = OS_ERROR_OK_S;
}
}
out:
#endif /* FSL_HAVE_SCC2 */
return status;
}
static os_error_code sah_handle_scc_sstatus(fsl_shw_uco_t * user_ctx,
uint32_t info)
{
os_error_code status = OS_ERROR_NO_MEMORY_S;
#ifdef FSL_HAVE_SCC2
{
scc_partition_info_t partition_info;
void *kernel_base;
status =
os_copy_from_user(&partition_info, (void *)info,
sizeof(partition_info));
/* check that the copy was successful */
if (status != OS_ERROR_OK_S) {
goto out;
}
/* validate that the user owns this partition, and look up its handle */
kernel_base =
lookup_user_partition(user_ctx, partition_info.user_base);
if (kernel_base == NULL) {
status = OS_ERROR_FAIL_S;
#ifdef DIAG_DRV_IF
LOG_KDIAG("failed to find partition\n");
#endif /*DIAG_DRV_IF */
goto out;
}
partition_info.status = scc_partition_status(kernel_base);
status =
os_copy_to_user((void *)info, &partition_info,
sizeof(partition_info));
}
out:
#endif /* FSL_HAVE_SCC2 */
return status;
}
static os_error_code sah_handle_scc_encrypt(fsl_shw_uco_t * user_ctx,
uint32_t info)
{
os_error_code os_err = OS_ERROR_FAIL_S;
#ifdef FSL_HAVE_SCC2
{
fsl_shw_return_t retval;
scc_region_t region_info;
void *page_ctx = NULL;
void *black_addr = NULL;
void *partition_base = NULL;
scc_config_t *scc_configuration;
os_err =
os_copy_from_user(®ion_info, (void *)info,
sizeof(region_info));
if (os_err != OS_ERROR_OK_S) {
goto out;
}
#ifdef DIAG_DRV_IF
LOG_KDIAG_ARGS
("partition_base: %p, offset: %i, length: %i, black data: %p",
(void *)region_info.partition_base, region_info.offset,
region_info.length, (void *)region_info.black_data);
#endif
/* validate that the user owns this partition, and look up its handle */
partition_base = lookup_user_partition(user_ctx,
region_info.
partition_base);
if (partition_base == NULL) {
retval = FSL_RETURN_ERROR_S;
#ifdef DIAG_DRV_IF
LOG_KDIAG("failed to find secure partition\n");
#endif
goto out;
}
/* Check that the memory size requested is correct */
scc_configuration = scc_get_configuration();
if (region_info.offset + region_info.length >
scc_configuration->partition_size_bytes) {
retval = FSL_RETURN_ERROR_S;
goto out;
}
/* wire down black data */
black_addr = wire_user_memory(region_info.black_data,
region_info.length, &page_ctx);
if (black_addr == NULL) {
retval = FSL_RETURN_ERROR_S;
goto out;
}
retval =
do_scc_encrypt_region(NULL, partition_base,
region_info.offset,
region_info.length, black_addr,
region_info.IV,
region_info.cypher_mode);
/* release black data */
unwire_user_memory(&page_ctx);
out:
if (os_err == OS_ERROR_OK_S) {
/* Return error code */
region_info.code = retval;
os_err =
os_copy_to_user((void *)info, ®ion_info,
sizeof(region_info));
}
}
#endif
return os_err;
}
static os_error_code sah_handle_scc_decrypt(fsl_shw_uco_t * user_ctx,
uint32_t info)
{
os_error_code os_err = OS_ERROR_FAIL_S;
#ifdef FSL_HAVE_SCC2
{
fsl_shw_return_t retval;
scc_region_t region_info;
void *page_ctx = NULL;
void *black_addr;
void *partition_base;
scc_config_t *scc_configuration;
os_err =
os_copy_from_user(®ion_info, (void *)info,
sizeof(region_info));
if (os_err != OS_ERROR_OK_S) {
goto out;
}
#ifdef DIAG_DRV_IF
LOG_KDIAG_ARGS
("partition_base: %p, offset: %i, length: %i, black data: %p",
(void *)region_info.partition_base, region_info.offset,
region_info.length, (void *)region_info.black_data);
#endif
/* validate that the user owns this partition, and look up its handle */
partition_base = lookup_user_partition(user_ctx,
region_info.
partition_base);
if (partition_base == NULL) {
retval = FSL_RETURN_ERROR_S;
#ifdef DIAG_DRV_IF
LOG_KDIAG("failed to find partition\n");
#endif
goto out;
}
/* Check that the memory size requested is correct */
scc_configuration = scc_get_configuration();
if (region_info.offset + region_info.length >
scc_configuration->partition_size_bytes) {
retval = FSL_RETURN_ERROR_S;
goto out;
}
/* wire down black data */
black_addr = wire_user_memory(region_info.black_data,
region_info.length, &page_ctx);
if (black_addr == NULL) {
retval = FSL_RETURN_ERROR_S;
goto out;
}
retval =
do_scc_decrypt_region(NULL, partition_base,
region_info.offset,
region_info.length, black_addr,
region_info.IV,
region_info.cypher_mode);
/* release black data */
unwire_user_memory(&page_ctx);
out:
if (os_err == OS_ERROR_OK_S) {
/* Return error code */
region_info.code = retval;
os_err =
os_copy_to_user((void *)info, ®ion_info,
sizeof(region_info));
}
}
#endif /* FSL_HAVE_SCC2 */
return os_err;
}
/*****************************************************************************/
/* fn get_user_smid() */
/*****************************************************************************/
uint32_t get_user_smid(void *proc)
{
/*
* A real implementation would have some way to handle signed applications
* which wouild be assigned distinct SMIDs. For the reference
* implementation, we show where this would be determined (here), but
* always provide a fixed answer, thus not separating users at all.
*/
return 0x42eaae42;
}
/*!
*******************************************************************************
* This function implements the smalloc() function for userspace programs, by
* making a call to the SCC2 mmap() function that acquires a region of secure
* memory on behalf of the user, and then maps it into the users memory space.
* Currently, the only memory size supported is that of a single SCC2 partition.
* Requests for other sized memory regions will fail.
*/
OS_DEV_MMAP(sah_mmap)
{
os_error_code status = OS_ERROR_NO_MEMORY_S;
#ifdef FSL_HAVE_SCC2
{
scc_return_t scc_ret;
fsl_shw_return_t fsl_ret;
uint32_t partition_registered = FALSE;
uint32_t user_base;
void *partition_base;
uint32_t smid;
scc_config_t *scc_configuration;
int part_no = -1;
uint32_t part_phys;
fsl_shw_uco_t *user_ctx =
(fsl_shw_uco_t *) os_dev_get_user_private();
/* Make sure that the user context is valid */
if (user_ctx == NULL) {
user_ctx =
os_alloc_memory(sizeof(*user_ctx), GFP_KERNEL);
if (user_ctx == NULL) {
status = OS_ERROR_NO_MEMORY_S;
goto out;
}
sah_handle_registration(user_ctx);
os_dev_set_user_private(user_ctx);
}
/* Determine the size of a secure partition */
scc_configuration = scc_get_configuration();
/* Check that the memory size requested is equal to the partition
* size, and that the requested destination is on a page boundary.
*/
if (((os_mmap_user_base() % PAGE_SIZE) != 0) ||
(os_mmap_memory_size() !=
scc_configuration->partition_size_bytes)) {
status = OS_ERROR_BAD_ARG_S;
goto out;
}
/* Retrieve the SMID associated with the user */
smid = get_user_smid(user_ctx->process);
/* Attempt to allocate a secure partition */
scc_ret =
scc_allocate_partition(smid, &part_no, &partition_base,
&part_phys);
if (scc_ret != SCC_RET_OK) {
pr_debug
("SCC mmap() request failed to allocate partition;"
" error %d\n", status);
status = OS_ERROR_FAIL_S;
goto out;
}
pr_debug("scc_mmap() acquired partition %d at %08x\n",
part_no, part_phys);
/* Record partition info in the user context */
user_base = os_mmap_user_base();
fsl_ret =
register_user_partition(user_ctx, user_base,
partition_base);
if (fsl_ret != FSL_RETURN_OK_S) {
pr_debug
("SCC mmap() request failed to register partition with user"
" context, error: %d\n", fsl_ret);
status = OS_ERROR_FAIL_S;
}
partition_registered = TRUE;
status = map_user_memory(os_mmap_memory_ctx(), part_phys,
os_mmap_memory_size());
#ifdef SHW_DEBUG
if (status == OS_ERROR_OK_S) {
LOG_KDIAG_ARGS
("Partition allocated: user_base=%p, partition_base=%p.",
(void *)user_base, partition_base);
}
#endif
out:
/* If there is an error it has to be handled here */
if (status != OS_ERROR_OK_S) {
/* if the partition was registered with the user, unregister it. */
if (partition_registered == TRUE) {
deregister_user_partition(user_ctx, user_base);
}
/* if the partition was allocated, deallocate it */
if (partition_base != NULL) {
scc_release_partition(partition_base);
}
}
}
#endif /* FSL_HAVE_SCC2 */
return status;
}
/* Find the physical address of a key stored in the system keystore */
fsl_shw_return_t
system_keystore_get_slot_info(uint64_t owner_id, uint32_t slot,
uint32_t * address, uint32_t * slot_size_bytes)
{
fsl_shw_return_t retval;
void *kernel_address;
/* First verify that the key access is valid */
retval = system_keystore.slot_verify_access(system_keystore.user_data,
owner_id, slot);
if (retval != FSL_RETURN_OK_S) {
#ifdef DIAG_DRV_IF
LOG_KDIAG("verification failed");
#endif
return retval;
}
if (address != NULL) {
#ifdef FSL_HAVE_SCC2
kernel_address =
system_keystore.slot_get_address(system_keystore.user_data,
slot);
(*address) = scc_virt_to_phys(kernel_address);
#else
kernel_address =
system_keystore.slot_get_address((void *)&owner_id, slot);
(*address) = (uint32_t) kernel_address;
#endif
}
if (slot_size_bytes != NULL) {
#ifdef FSL_HAVE_SCC2
*slot_size_bytes =
system_keystore.slot_get_slot_size(system_keystore.
user_data, slot);
#else
*slot_size_bytes =
system_keystore.slot_get_slot_size((void *)&owner_id, slot);
#endif
}
return retval;
}
static os_error_code sah_handle_sk_slot_alloc(uint32_t info)
{
scc_slot_t slot_info;
os_error_code os_err;
scc_return_t scc_ret;
os_err = os_copy_from_user(&slot_info, (void *)info, sizeof(slot_info));
if (os_err == OS_ERROR_OK_S) {
scc_ret = keystore_slot_alloc(&system_keystore,
slot_info.key_length,
slot_info.ownerid,
&slot_info.slot);
if (scc_ret == SCC_RET_OK) {
slot_info.code = FSL_RETURN_OK_S;
} else if (scc_ret == SCC_RET_INSUFFICIENT_SPACE) {
slot_info.code = FSL_RETURN_NO_RESOURCE_S;
} else {
slot_info.code = FSL_RETURN_ERROR_S;
}
#ifdef DIAG_DRV_IF
LOG_KDIAG_ARGS("key length: %i, handle: %i\n",
slot_info.key_length, slot_info.slot);
#endif
/* Return error code and slot info */
os_err =
os_copy_to_user((void *)info, &slot_info,
sizeof(slot_info));
if (os_err != OS_ERROR_OK_S) {
(void)keystore_slot_dealloc(&system_keystore,
slot_info.ownerid,
slot_info.slot);
}
}
return os_err;
}
static os_error_code sah_handle_sk_slot_dealloc(uint32_t info)
{
fsl_shw_return_t ret = FSL_RETURN_INTERNAL_ERROR_S;
scc_slot_t slot_info;
os_error_code os_err;
scc_return_t scc_ret;
os_err = os_copy_from_user(&slot_info, (void *)info, sizeof(slot_info));
if (os_err == OS_ERROR_OK_S) {
scc_ret = keystore_slot_dealloc(&system_keystore,
slot_info.ownerid,
slot_info.slot);
if (scc_ret == SCC_RET_OK) {
ret = FSL_RETURN_OK_S;
} else {
ret = FSL_RETURN_ERROR_S;
}
slot_info.code = ret;
os_err =
os_copy_to_user((void *)info, &slot_info,
sizeof(slot_info));
}
return os_err;
}
static os_error_code sah_handle_sk_slot_load(uint32_t info)
{
fsl_shw_return_t ret = FSL_RETURN_INTERNAL_ERROR_S;
scc_slot_t slot_info;
os_error_code os_err;
uint8_t *key = NULL;
os_err = os_copy_from_user(&slot_info, (void *)info, sizeof(slot_info));
if (os_err == OS_ERROR_OK_S) {
/* Allow slop in alloc in case we are rounding up to word multiple */
key = os_alloc_memory(slot_info.key_length + 3, GFP_KERNEL);
if (key == NULL) {
ret = FSL_RETURN_NO_RESOURCE_S;
os_err = OS_ERROR_NO_MEMORY_S;
} else {
os_err = os_copy_from_user(key, slot_info.key,
slot_info.key_length);
}
}
if (os_err == OS_ERROR_OK_S) {
unsigned key_length = slot_info.key_length;
/* Round up if necessary, as SCC call wants a multiple of 32-bit
* values for the full object being loaded. */
if ((key_length & 3) != 0) {
key_length += 4 - (key_length & 3);
}
ret = keystore_slot_load(&system_keystore,
slot_info.ownerid, slot_info.slot, key,
key_length);
slot_info.code = ret;
os_err =
os_copy_to_user((void *)info, &slot_info,
sizeof(slot_info));
}
if (key != NULL) {
memset(key, 0, slot_info.key_length);
os_free_memory(key);
}
return os_err;
}
static os_error_code sah_handle_sk_slot_read(uint32_t info)
{
fsl_shw_return_t ret = FSL_RETURN_INTERNAL_ERROR_S;
scc_slot_t slot_info;
os_error_code os_err;
uint8_t *key = NULL;
os_err = os_copy_from_user(&slot_info, (void *)info, sizeof(slot_info));
if (os_err == OS_ERROR_OK_S) {
/* This operation is not allowed for user keys */
slot_info.code = FSL_RETURN_NO_RESOURCE_S;
os_err =
os_copy_to_user((void *)info, &slot_info,
sizeof(slot_info));
return os_err;
}
if (os_err == OS_ERROR_OK_S) {
/* Allow slop in alloc in case we are rounding up to word multiple */
key = os_alloc_memory(slot_info.key_length + 3, GFP_KERNEL);
if (key == NULL) {
ret = FSL_RETURN_NO_RESOURCE_S;
os_err = OS_ERROR_NO_MEMORY_S;
}
}
if (os_err == OS_ERROR_OK_S) {
unsigned key_length = slot_info.key_length;
/* @bug Do some PERMISSIONS checking - make sure this is SW key */
/* Round up if necessary, as SCC call wants a multiple of 32-bit
* values for the full object being loaded. */
if ((key_length & 3) != 0) {
key_length += 4 - (key_length & 3);
}
ret = keystore_slot_read(&system_keystore,
slot_info.ownerid, slot_info.slot,
key_length, key);
/* @bug do some error checking */
/* Send key back to user */
os_err = os_copy_to_user(slot_info.key, key,
slot_info.key_length);
slot_info.code = ret;
os_err =
os_copy_to_user((void *)info, &slot_info,
sizeof(slot_info));
}
if (key != NULL) {
memset(key, 0, slot_info.key_length);
os_free_memory(key);
}
return os_err;
}
static os_error_code sah_handle_sk_slot_encrypt(uint32_t info)
{
fsl_shw_return_t ret = FSL_RETURN_INTERNAL_ERROR_S;
scc_slot_t slot_info;
os_error_code os_err;
scc_return_t scc_ret;
uint8_t *key = NULL;
os_err = os_copy_from_user(&slot_info, (void *)info, sizeof(slot_info));
if (os_err == OS_ERROR_OK_S) {
key = os_alloc_memory(slot_info.key_length, GFP_KERNEL);
if (key == NULL) {
ret = FSL_RETURN_NO_RESOURCE_S;
}
}
if (key != NULL) {
scc_ret = keystore_slot_encrypt(NULL, &system_keystore,
slot_info.ownerid,
slot_info.slot,
slot_info.key_length, key);
if (scc_ret != SCC_RET_OK) {
ret = FSL_RETURN_ERROR_S;
} else {
os_err =
os_copy_to_user(slot_info.key, key,
slot_info.key_length);
if (os_err != OS_ERROR_OK_S) {
ret = FSL_RETURN_INTERNAL_ERROR_S;
} else {
ret = FSL_RETURN_OK_S;
}
}
slot_info.code = ret;
os_err =
os_copy_to_user((void *)info, &slot_info,
sizeof(slot_info));
memset(key, 0, slot_info.key_length);
os_free_memory(key);
}
return os_err;
}
static os_error_code sah_handle_sk_slot_decrypt(uint32_t info)
{
fsl_shw_return_t ret = FSL_RETURN_INTERNAL_ERROR_S;
scc_slot_t slot_info; /*!< decrypt request fields */
os_error_code os_err;
scc_return_t scc_ret;
uint8_t *key = NULL;
os_err = os_copy_from_user(&slot_info, (void *)info, sizeof(slot_info));
if (os_err == OS_ERROR_OK_S) {
key = os_alloc_memory(slot_info.key_length, GFP_KERNEL);
if (key == NULL) {
ret = FSL_RETURN_NO_RESOURCE_S;
os_err = OS_ERROR_OK_S;
} else {
os_err = os_copy_from_user(key, slot_info.key,
slot_info.key_length);
}
}
if (os_err == OS_ERROR_OK_S) {
scc_ret = keystore_slot_decrypt(NULL, &system_keystore,
slot_info.ownerid,
slot_info.slot,
slot_info.key_length, key);
if (scc_ret == SCC_RET_OK) {
ret = FSL_RETURN_OK_S;
} else {
ret = FSL_RETURN_ERROR_S;
}
slot_info.code = ret;
os_err =
os_copy_to_user((void *)info, &slot_info,
sizeof(slot_info));
}
if (key != NULL) {
memset(key, 0, slot_info.key_length);
os_free_memory(key);
}
return os_err;
}
/*!
* Register a user
*
* @brief Register a user
*
* @param user_ctx information about this user
*
* @return status code
*/
fsl_shw_return_t sah_handle_registration(fsl_shw_uco_t * user_ctx)
{
/* Initialize the user's result pool (like sah_Queue_Construct() */
user_ctx->result_pool.head = NULL;
user_ctx->result_pool.tail = NULL;
user_ctx->result_pool.count = 0;
/* initialize the user's partition chain */
user_ctx->partition = NULL;
return FSL_RETURN_OK_S;
}
/*!
* Deregister a user
*
* @brief Deregister a user
*
* @param user_ctx information about this user
*
* @return status code
*/
fsl_shw_return_t sah_handle_deregistration(fsl_shw_uco_t * user_ctx)
{
/* NOTE:
* This will release any secure partitions that are held by the user.
* Encryption keys that were placed in the system keystore by the user
* should not be removed here, because they might have been shared with
* another process. The user must be careful to release any that are no
* longer in use.
*/
fsl_shw_return_t ret = FSL_RETURN_OK_S;
#ifdef FSL_HAVE_SCC2
fsl_shw_spo_t *partition;
struct mm_struct *mm = current->mm;
while ((user_ctx->partition != NULL) && (ret == FSL_RETURN_OK_S)) {
partition = user_ctx->partition;
#ifdef DIAG_DRV_IF
LOG_KDIAG_ARGS
("Found an abandoned secure partition at %p, releasing",
partition);
#endif
/* It appears that current->mm is not valid if this is called from a
* close routine (perhaps only if the program raised an exception that
* caused it to close?) If that is the case, then still free the
* partition, but do not remove it from the memory space (dangerous?)
*/
if (mm == NULL) {
#ifdef DIAG_DRV_IF
LOG_KDIAG
("Warning: no mm structure found, not unmapping "
"partition from user memory\n");
#endif
} else {
/* Unmap the memory region (see sys_munmap in mmap.c) */
/* Note that this assumes a single memory partition */
unmap_user_memory(partition->user_base, 8192);
}
/* If the memory was successfully released */
if (ret == OS_ERROR_OK_S) {
/* release the partition */
scc_release_partition(partition->kernel_base);
/* and remove it from the users context */
deregister_user_partition(user_ctx,
partition->user_base);
ret = FSL_RETURN_OK_S;
} else {
ret = FSL_RETURN_ERROR_S;
goto out;
}
}
out:
#endif /* FSL_HAVE_SCC2 */
return ret;
}
/*!
* Sets up memory to extract results from results pool
*
* @brief Sets up memory to extract results from results pool
*
* @param user_ctx information about this user
* @param[in,out] arg contains input parameters and fields that the driver
* fills in
*
* @return os error code or 0 on success
*/
int sah_get_results_pointers(fsl_shw_uco_t * user_ctx, uint32_t arg)
{
sah_results results_arg; /* kernel mode usable version of 'arg' */
fsl_shw_result_t *user_results; /* user mode address of results */
unsigned *user_actual; /* user mode address of actual number of results */
unsigned actual; /* local memory of actual number of results */
int ret_val = OS_ERROR_FAIL_S;
sah_Head_Desc *finished_request;
unsigned int loop;
/* copy structure from user to kernel space */
if (!os_copy_from_user(&results_arg, (void *)arg, sizeof(sah_results))) {
/* save user space pointers */
user_actual = results_arg.actual; /* where count goes */
user_results = results_arg.results; /* where results goe */
/* Set pointer for actual value to temporary kernel memory location */
results_arg.actual = &actual;
/* Allocate kernel memory to hold temporary copy of the results */
results_arg.results =
os_alloc_memory(sizeof(fsl_shw_result_t) *
results_arg.requested, GFP_KERNEL);
/* if memory allocated, continue */
if (results_arg.results == NULL) {
ret_val = OS_ERROR_NO_MEMORY_S;
} else {
fsl_shw_return_t get_status;
/* get the results */
get_status =
sah_get_results_from_pool(user_ctx, &results_arg);
/* free the copy of the user space descriptor chain */
for (loop = 0; loop < actual; ++loop) {
/* get sah_Head_Desc from results and put user address into
* the return structure */
finished_request =
results_arg.results[loop].user_desc;
results_arg.results[loop].user_desc =
finished_request->user_desc;
/* return the descriptor chain memory to the block free pool */
sah_Free_Chained_Descriptors(finished_request);
}
/* if no errors, copy results and then the actual number of results
* back to user space
*/
if (get_status == FSL_RETURN_OK_S) {
if (os_copy_to_user
(user_results, results_arg.results,
actual * sizeof(fsl_shw_result_t))
|| os_copy_to_user(user_actual, &actual,
sizeof(user_actual))) {
ret_val = OS_ERROR_FAIL_S;
} else {
ret_val = 0; /* no error */
}
}
/* free the allocated memory */
os_free_memory(results_arg.results);
}
}
return ret_val;
}
/*!
* Extracts results from results pool
*
* @brief Extract results from results pool
*
* @param user_ctx information about this user
* @param[in,out] arg contains input parameters and fields that the
* driver fills in
*
* @return status code
*/
fsl_shw_return_t sah_get_results_from_pool(volatile fsl_shw_uco_t * user_ctx,
sah_results * arg)
{
sah_Head_Desc *finished_request;
unsigned int loop = 0;
os_lock_context_t int_flags;
/* Get the number of results requested, up to total number of results
* available
*/
do {
/* Protect state of user's result pool until we have retrieved and
* remove the first entry, or determined that the pool is empty. */
os_lock_save_context(desc_queue_lock, int_flags);
finished_request = user_ctx->result_pool.head;
if (finished_request != NULL) {
sah_Queue_Remove_Entry((sah_Queue *) & user_ctx->
result_pool);
os_unlock_restore_context(desc_queue_lock, int_flags);
/* Prepare to free. */
(void)sah_DePhysicalise_Descriptors(finished_request);
arg->results[loop].user_ref =
finished_request->user_ref;
arg->results[loop].code = finished_request->result;
arg->results[loop].detail1 =
finished_request->fault_address;
arg->results[loop].detail2 = 0;
arg->results[loop].user_desc = finished_request;
loop++;
} else { /* finished_request is NULL */
/* pool is empty */
os_unlock_restore_context(desc_queue_lock, int_flags);
}
} while ((loop < arg->requested) && (finished_request != NULL));
/* record number of results actually obtained */
*arg->actual = loop;
return FSL_RETURN_OK_S;
}
/*!
* Converts descriptor chain to kernel space (from user space) and submits
* chain to Sahara for processing
*
* @brief Submits converted descriptor chain to sahara
*
* @param user_ctx Pointer to Kernel version of user's ctx
* @param user_space_desc user space address of descriptor chain that is
* in user space
*
* @return OS status code
*/
static int handle_sah_ioctl_dar(fsl_shw_uco_t * user_ctx,
uint32_t user_space_desc)
{
int os_error_code = OS_ERROR_FAIL_S;
sah_Head_Desc *desc_chain_head; /* chain in kernel - virtual address */
/* This will re-create the linked list so that the SAHARA hardware can
* DMA on it.
*/
desc_chain_head = sah_Copy_Descriptors(user_ctx,
(sah_Head_Desc *)
user_space_desc);
if (desc_chain_head == NULL) {
/* We may have failed due to a -EFAULT as well, but we will return
* OS_ERROR_NO_MEMORY_S since either way it is a memory related
* failure.
*/
os_error_code = OS_ERROR_NO_MEMORY_S;
} else {
fsl_shw_return_t stat;
desc_chain_head->user_info = user_ctx;
desc_chain_head->user_desc = (sah_Head_Desc *) user_space_desc;
if (desc_chain_head->uco_flags & FSL_UCO_BLOCKING_MODE) {
#ifdef SAHARA_POLL_MODE
sah_Handle_Poll(desc_chain_head);
#else
sah_blocking_mode(desc_chain_head);
#endif
stat = desc_chain_head->result;
/* return the descriptor chain memory to the block free pool */
sah_Free_Chained_Descriptors(desc_chain_head);
/* Tell user how the call turned out */
/* Copy 'result' back up to the result member.
*
* The dereference of the different member will cause correct the
* arithmetic to occur on the user-space address because of the
* missing dma/bus locations in the user mode version of the
* sah_Desc structure. */
os_error_code =
os_copy_to_user((void *)(user_space_desc
+ offsetof(sah_Head_Desc,
uco_flags)),
&stat, sizeof(fsl_shw_return_t));
} else { /* not blocking mode - queue and forget */
if (desc_chain_head->uco_flags & FSL_UCO_CALLBACK_MODE) {
user_ctx->process = os_get_process_handle();
user_ctx->callback = sah_user_callback;
}
#ifdef SAHARA_POLL_MODE
/* will put results in result pool */
sah_Handle_Poll(desc_chain_head);
#else
/* just put someting in the DAR */
sah_Queue_Manager_Append_Entry(desc_chain_head);
#endif
/* assume all went well */
os_error_code = OS_ERROR_OK_S;
}
}
return os_error_code;
}
static void sah_user_callback(fsl_shw_uco_t * user_ctx)
{
os_send_signal(user_ctx->process, SIGUSR2);
}
/*!
* This function is called when a thread attempts to read from the /proc/sahara
* file. Upon read, statistics and information about the state of the driver
* are returned in nthe supplied buffer.
*
* @brief SAHARA PROCFS read function.
*
* @param buf Anything written to this buffer will be returned to the
* user-space process that is reading from this proc entry.
* @param start Part of the kernel prototype.
* @param offset Part of the kernel prototype.
* @param count The size of the buf argument.
* @param eof An integer which is set to one to tell the user-space
* process that there is no more data to read.
* @param data Part of the kernel prototype.
*
* @return The number of bytes written to the proc entry.
*/
#if !defined(CONFIG_DEVFS_FS) || (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
static int sah_read_procfs(char *buf,
char **start,
off_t offset, int count, int *eof, void *data)
{
int output_bytes = 0;
int in_queue_count = 0;
os_lock_context_t lock_context;
os_lock_save_context(desc_queue_lock, lock_context);
in_queue_count = sah_Queue_Manager_Count_Entries(TRUE, 0);
os_unlock_restore_context(desc_queue_lock, lock_context);
output_bytes += snprintf(buf, count - output_bytes, "queued: %d\n",
in_queue_count);
output_bytes += snprintf(buf + output_bytes, count - output_bytes,
"Descriptors: %d, "
"Interrupts %d (%d Done1Done2, %d Done1Busy2, "
" %d Done1)\n",
dar_count, interrupt_count, done1done2_count,
done1busy2_count, done1_count);
output_bytes += snprintf(buf + output_bytes, count - output_bytes,
"Control: %08x\n", sah_HW_Read_Control());
#if !defined(FSL_HAVE_SAHARA4) || defined(SAHARA4_NO_USE_SQUIB)
output_bytes += snprintf(buf + output_bytes, count - output_bytes,
"IDAR: %08x; CDAR: %08x\n",
sah_HW_Read_IDAR(), sah_HW_Read_CDAR());
#endif
#ifdef DIAG_DRV_STATUS
output_bytes += snprintf(buf + output_bytes, count - output_bytes,
"Status: %08x; Error Status: %08x; Op Status: %08x\n",
sah_HW_Read_Status(),
sah_HW_Read_Error_Status(),
sah_HW_Read_Op_Status());
#endif
#ifdef FSL_HAVE_SAHARA4
output_bytes += snprintf(buf + output_bytes, count - output_bytes,
"MMStat: %08x; Config: %08x\n",
sah_HW_Read_MM_Status(), sah_HW_Read_Config());
#endif
/* Signal the end of the file */
*eof = 1;
/* To get rid of the unused parameter warnings */
(void)start;
(void)data;
(void)offset;
return output_bytes;
}
static int sah_write_procfs(struct file *file, const char __user * buffer,
unsigned long count, void *data)
{
/* Any write to this file will reset all counts. */
dar_count = interrupt_count = done1done2_count =
done1busy2_count = done1_count = 0;
(void)file;
(void)buffer;
(void)data;
return count;
}
#endif
#ifndef SAHARA_POLL_MODE
/*!
* Block user call until processing is complete.
*
* @param entry The user's request.
*
* @return An OS error code, or 0 if no error
*/
int sah_blocking_mode(sah_Head_Desc * entry)
{
int os_error_code = 0;
sah_Queue_Status status;
/* queue entry, put something in the DAR, if nothing is there currently */
sah_Queue_Manager_Append_Entry(entry);
/* get this descriptor chain's current status */
status = ((volatile sah_Head_Desc *)entry)->status;
while (!SAH_DESC_PROCESSED(status)) {
extern sah_Queue *main_queue;
DEFINE_WAIT(sahara_wait); /* create a wait queue entry. Linux */
/* enter the wait queue entry into the queue */
prepare_to_wait(&Wait_queue, &sahara_wait, TASK_INTERRUPTIBLE);
/* check if this entry has been processed */
status = ((volatile sah_Head_Desc *)entry)->status;
if (!SAH_DESC_PROCESSED(status)) {
/* go to sleep - Linux */
schedule();
}
/* un-queue the 'prepare to wait' queue? - Linux */
finish_wait(&Wait_queue, &sahara_wait);
/* signal belongs to this thread? */
if (signal_pending(current)) { /* Linux */
os_lock_context_t lock_flags;
/* don't allow access during this check and operation */
os_lock_save_context(desc_queue_lock, lock_flags);
status = ((volatile sah_Head_Desc *)entry)->status;
if (status == SAH_STATE_PENDING) {
sah_Queue_Remove_Any_Entry(main_queue, entry);
entry->result = FSL_RETURN_INTERNAL_ERROR_S;
((volatile sah_Head_Desc *)entry)->status =
SAH_STATE_FAILED;
}
os_unlock_restore_context(desc_queue_lock, lock_flags);
}
status = ((volatile sah_Head_Desc *)entry)->status;
} /* while ... */
/* Do this so that caller can free */
(void)sah_DePhysicalise_Descriptors(entry);
return os_error_code;
}
/*!
* If interrupt does not return in a reasonable time, time out, trigger
* interrupt, and continue with process
*
* @param data ignored
*/
void sahara_timeout_handler(unsigned long data)
{
/* Sahara has not issuing an interrupt, so timed out */
#ifdef DIAG_DRV_IF
LOG_KDIAG("Sahara HW did not respond. Resetting.\n");
#endif
/* assume hardware needs resetting */
sah_Handle_Interrupt(SAH_EXEC_FAULT);
/* wake up sleeping thread to try again */
wake_up_interruptible(&Wait_queue);
}
#endif /* ifndef SAHARA_POLL_MODE */
/* End of sah_driver_interface.c */
|
star-finder/jpf-star
|
expected-output/random/sll/Input_withSin1.java
|
package random.sll;
import common.Utilities;
import org.junit.Test;
import gov.nasa.jpf.util.test.TestJPF;
public class Input_withSin1 extends TestJPF {
@Test
public void test_withSin63() throws Exception {
Input obj = new Input();
Node root = new Node();
Node next_82 = null;
int elem_81 = -8;
root.elem = elem_81;
root.next = next_82;
obj.withSin(root);
}
@Test
public void test_withSin64() throws Exception {
Input obj = new Input();
random.sll.Node root = null;
obj.withSin(root);
}
}
|
hariPrasad525/Nitya_Annaccounting
|
src/com/nitya/accounter/core/reports/generators/EstimatesByJobRG.java
|
package com.nitya.accounter.core.reports.generators;
import com.nitya.accounter.core.FinanceDate;
import com.nitya.accounter.web.client.core.ClientFinanceDate;
import com.nitya.accounter.web.client.ui.serverreports.EstimatesByJobServerReport;
import com.nitya.accounter.web.client.ui.serverreports.ReportGridTemplate;
public class EstimatesByJobRG extends AbstractReportGenerator {
@Override
public int getReportType() {
return REPORT_TYPE_ESTIMATE_BY_JOB;
}
@Override
protected ReportGridTemplate<?> generate() {
EstimatesByJobServerReport estimatesByJobServerReport = new EstimatesByJobServerReport(
this.startDate.getDate(), this.endDate.getDate(),
generationType) {
@Override
public String getDateByCompanyType(ClientFinanceDate date) {
return getDateInDefaultType(date);
}
};
updateReport(estimatesByJobServerReport);
try {
estimatesByJobServerReport
.onResultSuccess(financeTool.getReportManager()
.getEstimatesByJob(
new FinanceDate(startDate.getDate()),
new FinanceDate(endDate.getDate()),
company.getID()));
} catch (Exception e) {
e.printStackTrace();
}
return estimatesByJobServerReport.getGridTemplate();
}
}
|
sunLeung/server
|
server/src/main/java/game/player/PlayerService.java
|
package game.player;
import game.dao.PlayerDao;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import common.utils.HttpUtils;
import common.utils.JsonUtils;
import common.utils.MD5;
import common.utils.SecurityUtils;
import common.utils.StringUtils;
public class PlayerService {
/**
* 验证玩家是否登录
* @param playerid
* @param deviceid
* @param token
* @return
*/
public static boolean authPlayer(int playerid,String deviceid,String token){
boolean result=false;
Player p=PlayerCache.getPlayer(playerid);
if(p!=null&&p.getId()==playerid&&deviceid.equals(p.getDeviceid())&&token.equals(p.getToken())){
result=true;
}
return result;
}
/**
* 登录
* @param identity
* @param password
* @param deviceid
* @return
*/
public static Player login(String identity,String password,String deviceid){
Player p=null;
//使用email登录
if(identity.contains("@")){
PlayerBean bean=PlayerDao.loadByEmail(identity);
if(bean!=null&&password.equals(SecurityUtils.decryptPassword(bean.getPassword()))){
bean.setDeviceid(deviceid);
bean.setToken(SecurityUtils.createUUIDString());
p=PlayerCache.initPlayer(bean);
}
}else{//使用手机登录
PlayerBean bean=PlayerDao.loadByPhone(identity);
if(bean!=null&&password.equals(SecurityUtils.decryptPassword(bean.getPassword()))){
bean.setDeviceid(deviceid);
bean.setToken(SecurityUtils.createUUIDString());
p=PlayerCache.initPlayer(bean);
}
}
return p;
}
/**
* 第三方渠道登陆
* @param deviceid
* @param data
* @return
*/
public static Player thirdPartylogin(String deviceid,String ip,String data){
Player p=null;
JsonNode jsonData=JsonUtils.decode(data);
String unionid=JsonUtils.getString("unionid", jsonData);
if("1".equals(unionid)){//微信登陆
p=weixinLogin(jsonData, deviceid);
}
return p;
}
public static Player weixinLogin(JsonNode jsonData,String deviceid){
Player p=null;
JsonNode identity=jsonData.get("identity");
String openid=identity.get("openid").asText();
String openkey=identity.get("openkey").asText();
if(StringUtils.isBlank(openid)||StringUtils.isBlank(openkey)){
return null;
}
String appid="wxcde873f99466f74a";
String appkey="<KEY>";
String url="http://msdktest.qq.com/auth/check_token/";
String timestamp=System.currentTimeMillis()/1000+"";
Map<String,String> params=new HashMap<String,String>();
params.put("appid", appid+"");
params.put("timestamp", timestamp);
params.put("sig", MD5.encode(appkey+timestamp));
params.put("encode", 1+"");
url=HttpUtils.linkParams(url,params);
Map<String,Object> content=new HashMap<String,Object>();
content.put("accessToken", openkey);
content.put("openid", openid);
String result=HttpUtils.doPost(url, null,JsonUtils.encode2Str(content));
System.out.println("weixin login:"+result);
JsonNode rdata=JsonUtils.decode(result);
int ret=JsonUtils.getInt("ret", rdata);
if(ret==0){
PlayerBean bean=PlayerDao.loadByThirdParty(openid);
if(bean!=null){
bean.setDeviceid(deviceid);
bean.setToken(SecurityUtils.createUUIDString());
p=PlayerCache.initPlayer(bean);
}else{
bean=new PlayerBean();
bean.setDeviceid(deviceid);
bean.setSecret(SecurityUtils.createUUIDString());
int sex=JsonUtils.getInt("sex", jsonData);
bean.setSex(sex);
String name=JsonUtils.getString("name", jsonData);
if(StringUtils.isBlank(name)){
name=StringUtils.randomName();
}
bean.setName(name);
bean.setToken(SecurityUtils.createUUIDString());
bean.setThirdParty(openid);
bean.setMoney(100);
int id=PlayerDao.save(bean);
if(id!=-1){
p=PlayerCache.getPlayer(id);
}
}
}
return p;
}
public static boolean updatePlayer(int playerid,String data){
JsonNode jsonData=JsonUtils.decode(data);
Player p=PlayerCache.getPlayer(playerid);
if(p!=null){
String name=JsonUtils.getString("name", jsonData);
if(StringUtils.isNotBlank(name))
p.getBean().setName(name);
int sex=JsonUtils.getInt("sex", jsonData);
if(sex!=-1)
p.getBean().setSex(sex);
int r=PlayerDao.update(p.getBean());
if(r!=-1){
return true;
}
}
return false;
}
/**
* 检测玩家是否有该歌曲
* @param playerid
* @param songid
* @return
*/
public static boolean hasThisSong(int playerid,int songid){
boolean result=false;
Player p=PlayerCache.getPlayer(playerid);
if(p!=null){
result = p.getSongs().contains(songid);
}
return result;
}
}
|
ScalablyTyped/SlinkyTyped
|
s/serverless/src/main/scala/typingsSlinky/serverless/awsProviderMod/CloudFront.scala
|
<reponame>ScalablyTyped/SlinkyTyped
package typingsSlinky.serverless.awsProviderMod
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait CloudFront extends StObject {
var eventType: String = js.native
var includeBody: Boolean = js.native
var origin: Origin = js.native
var pathPattern: String = js.native
}
object CloudFront {
@scala.inline
def apply(eventType: String, includeBody: Boolean, origin: Origin, pathPattern: String): CloudFront = {
val __obj = js.Dynamic.literal(eventType = eventType.asInstanceOf[js.Any], includeBody = includeBody.asInstanceOf[js.Any], origin = origin.asInstanceOf[js.Any], pathPattern = pathPattern.asInstanceOf[js.Any])
__obj.asInstanceOf[CloudFront]
}
@scala.inline
implicit class CloudFrontMutableBuilder[Self <: CloudFront] (val x: Self) extends AnyVal {
@scala.inline
def setEventType(value: String): Self = StObject.set(x, "eventType", value.asInstanceOf[js.Any])
@scala.inline
def setIncludeBody(value: Boolean): Self = StObject.set(x, "includeBody", value.asInstanceOf[js.Any])
@scala.inline
def setOrigin(value: Origin): Self = StObject.set(x, "origin", value.asInstanceOf[js.Any])
@scala.inline
def setPathPattern(value: String): Self = StObject.set(x, "pathPattern", value.asInstanceOf[js.Any])
}
}
|
octoxalis/progressiVecontent
|
source/make/data/F_o.js
|
<reponame>octoxalis/progressiVecontent<gh_stars>0
/*
* Functions
* Naming scheme: function__s
*/
const A_o = require( './A_o.js' )
const U_o = require( './U_o.js' )
const C_o = require( './C_o.js' )
const OPEN_s = '[=' //: substitute__s function delimiter
const CLOSE_s = '=]' //: idem
module.exports =
{
siteUrl__s:
( file_s, dir_s=`${C_o.SLOTS_s}/` ) => `[${file_s.replace('_', ' ')}]: ${U_o.url_s}${dir_s}${file_s}.html`,
codeUrl__s:
path_s => `<a href="${U_o.GIT_SRC_s}${path_s}" target="_blank">${A_o.ID_s}/${path_s}</a>`,
mediaUrl__s:
() => `${U_o.url_s}${C_o.MEDIA_PATH_s}`,
img1px__s:
() => `${U_o.url_s}${C_o.MEDIA_PATH_s}1px.png`,
eleventyUrl__s:
key_s =>
{
const path_s = U_o[ `ELEVENTY_${key_s}` ]
const anchor_n = path_s.indexOf( '#')
if ( anchor_n === -1 ) //: return a link to 11ty.dev
{
console.log( `ALERT! no anchor found in path: ${path_s}` )
const ref_n = U_o.ELEVENTY_DEV_s.indexOf( ':' )
return { ref: U_o.ELEVENTY_DEV_s.substring( 0, ref_n ), link: U_o.ELEVENTY_DEV_s }
}
const anchor_s = path_s.substring( anchor_n )
const anchorLink_s = U_o.ELEVENTY_DEV_s.replace( ']', `${anchor_s}]`) + path_s
return { ref: anchorLink_s.substring( 0, anchorLink_s.indexOf( ':') ), link: anchorLink_s }
},
tagEscape__s:
content_s => content_s.replace( /</g, '<' ).replace( />/g, '>' ),
substitute__s: ( hay_s, dict_o, open_s=OPEN_s, close_s=CLOSE_s ) =>
{
const open_n = open_s.length
const close_n = close_s.length
let openAt_n,
closeAt_n,
key_s
while ( (openAt_n = hay_s.indexOf( open_s ) ) > -1 )
{
closeAt_n = hay_s.indexOf( close_s )
if ( closeAt_n > -1)
{
closeAt_n += close_n
key_s = hay_s.substring( openAt_n, closeAt_n )
hay_s = hay_s.replace( key_s, dict_o[key_s.slice( open_n, -close_n )] )
}
}
return hay_s
},
Boolean__b:
value_ =>
{
if ( typeof value_ === 'boolean' ) return value_
if (!value_) return false
const value_s = value_.toString().toLowerCase()
switch ( true )
{
case ( value_s in [ 'true', 'yes', '1' ] ) :
return true
case ( value_s in [ 'false', 'no', '0' ] ) :
case null :
return false
default: return Boolean (value_ )
}
},
slotId__s:
permalink_s =>
{
let index_n = permalink_s.lastIndexOf( '/') + 1 //: if ( index_n < 0 ) index_n = 0
return permalink_s.slice( index_n, permalink_s.indexOf( '.html' ) ) //;console.log( `slot: ${id_s}`)
},
till__s:
( days_n=0 ) =>
{
const till_s = new Date()
till_s.setDate( till_s.getDate() + days_n )
return till_s
},
writeFile__v:
(
output_o
) =>
{
if ( output_o ) console.log( output_o ) //: null or error message
}
}
|
Scarinci-Hollenbeck/aphshalloffame.com
|
pages/404.js
|
<filename>pages/404.js
import PageContainer from 'layouts/PageContainer'
const Page404 = () => (
<PageContainer title="404: Page not found">
<p className="m-4">Sorry, the page you are looking for cannot be found.</p>
</PageContainer>
);
export default Page404
|
Marco-Puig/Pokemon-Thunder-Lightning
|
lib/ruby/3.0.0/objspace.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require 'objspace.so'
module ObjectSpace
class << self
private :_dump
private :_dump_all
end
module_function
# call-seq:
# ObjectSpace.dump(obj[, output: :string]) # => "{ ... }"
# ObjectSpace.dump(obj, output: :file) # => #<File:/tmp/rubyobj20131125-88733-1xkfmpv.json>
# ObjectSpace.dump(obj, output: :stdout) # => nil
#
# Dump the contents of a ruby object as JSON.
#
# This method is only expected to work with C Ruby.
# This is an experimental method and is subject to change.
# In particular, the function signature and output format are
# not guaranteed to be compatible in future versions of ruby.
def dump(obj, output: :string)
out = case output
when :file, nil
require 'tempfile'
Tempfile.create(%w(rubyobj .json))
when :stdout
STDOUT
when :string
+''
when IO
output
else
raise ArgumentError, "wrong output option: #{output.inspect}"
end
ret = _dump(obj, out)
return nil if output == :stdout
ret
end
# call-seq:
# ObjectSpace.dump_all([output: :file]) # => #<File:/tmp/rubyheap20131125-88469-laoj3v.json>
# ObjectSpace.dump_all(output: :stdout) # => nil
# ObjectSpace.dump_all(output: :string) # => "{...}\n{...}\n..."
# ObjectSpace.dump_all(output:
# File.open('heap.json','w')) # => #<File:heap.json>
# ObjectSpace.dump_all(output: :string,
# since: 42) # => "{...}\n{...}\n..."
#
# Dump the contents of the ruby heap as JSON.
#
# _since_ must be a non-negative integer or +nil+.
#
# If _since_ is a positive integer, only objects of that generation and
# newer generations are dumped. The current generation can be accessed using
# GC::count.
#
# Objects that were allocated without object allocation tracing enabled
# are ignored. See ::trace_object_allocations for more information and
# examples.
#
# If _since_ is omitted or is +nil+, all objects are dumped.
#
# This method is only expected to work with C Ruby.
# This is an experimental method and is subject to change.
# In particular, the function signature and output format are
# not guaranteed to be compatible in future versions of ruby.
def dump_all(output: :file, full: false, since: nil)
out = case output
when :file, nil
require 'tempfile'
Tempfile.create(%w(rubyheap .json))
when :stdout
STDOUT
when :string
+''
when IO
output
else
raise ArgumentError, "wrong output option: #{output.inspect}"
end
ret = _dump_all(out, full, since)
return nil if output == :stdout
ret
end
end
|
tak2004/RadonFramework
|
src/Memory/HeapAllocator.cpp
|
<gh_stars>1-10
#include "RadonFramework/precompiled.hpp"
#include "RadonFramework/Memory/HeapAllocator.hpp"
#include "RadonFramework/System/Memory.hpp"
namespace RadonFramework::Memory {
HeapAllocator::HeapAllocator()
{
m_BlockSize=RF_SysMem::GetBlockSize();
}
MemoryBlock HeapAllocator::Allocate(const RF_Type::Size Bytes)
{
RF_Type::Size fittingSize = ((Bytes - 1) / m_BlockSize + 1)* m_BlockSize;
return {reinterpret_cast<RF_Type::UInt8*>(RF_SysMem::PageAllocate(fittingSize)), fittingSize};
}
void HeapAllocator::Deallocate(MemoryBlock& Block)
{
RF_SysMem::PageFree(Block.Data);
Block.Data = nullptr;
Block.Bytes = 0;
}
RF_Type::Bool HeapAllocator::Owns(const MemoryBlock& Block) const
{
return RF_SysMem::PageAllocationSize(Block.Data)==Block.Bytes;
}
void HeapAllocator::DeallocateAll()
{
}
MemoryMap HeapAllocator::Map(const RF_Type::Size Bytes)
{
return {RF_SysMem::MapMemory(nullptr, Bytes)};
}
void HeapAllocator::Unmap(MemoryMap& Mapping)
{
RF_SysMem::UnmapMemory(Mapping.Handle);
Mapping.Handle = nullptr;
}
RF_Type::UInt8* HeapAllocator::MapView(const MemoryMap& Map, const RF_Type::Size Bytes, void* View)
{
return reinterpret_cast<RF_Type::UInt8*>(RF_SysMem::MapView(Map.Handle, Bytes, View));
}
RF_Type::Size HeapAllocator::m_BlockSize = 0;
}
|
zachung/game-server
|
src/single/survivor/src/ui/TouchDirectionControlPanel.js
|
import { Container, Graphics } from '../lib/PIXI'
import Vector from '../lib/Vector'
import keyboardJS from 'keyboardjs'
import { LEFT, UP, RIGHT, DOWN } from '../config/control'
const ALL_KEYS = [RIGHT, LEFT, UP, DOWN]
class TouchDirectionControlPanel extends Container {
constructor ({ x, y, radius }) {
super()
this.position.set(x, y)
let touchArea = new Graphics()
touchArea.beginFill(0xF2F2F2, 0.5)
touchArea.drawCircle(0, 0, radius)
touchArea.endFill()
this.addChild(touchArea)
this.radius = radius
this.setupTouch()
}
setupTouch () {
this.interactive = true
let f = this.onTouch.bind(this)
this.on('touchstart', f)
this.on('touchend', f)
this.on('touchmove', f)
this.on('touchendoutside', f)
}
onTouch (e) {
let type = e.type
let propagation = false
switch (type) {
case 'touchstart':
this.drag = e.data.global.clone()
this.createDragPoint()
this.originPosition = {
x: this.x,
y: this.y
}
break
case 'touchend':
case 'touchendoutside':
if (this.drag) {
this.drag = false
this.destroyDragPoint()
this.releaseKeys()
}
break
case 'touchmove':
if (!this.drag) {
propagation = true
break
}
this.pressKeys(e.data.getLocalPosition(this))
break
}
if (!propagation) {
e.stopPropagation()
}
}
createDragPoint () {
let dragPoint = new Graphics()
dragPoint.beginFill(0xF2F2F2, 0.5)
dragPoint.drawCircle(0, 0, 20)
dragPoint.endFill()
this.addChild(dragPoint)
this.dragPoint = dragPoint
}
destroyDragPoint () {
this.removeChild(this.dragPoint)
this.dragPoint.destroy()
}
pressKeys (newPoint) {
this.releaseKeys()
// 感應靈敏度
let threshold = 30
let vector = Vector.fromPoint(newPoint)
let deg = vector.deg
let len = vector.length
if (len < threshold) {
return
}
let degAbs = Math.abs(deg)
let dx = degAbs < 67.5 ? RIGHT : (degAbs > 112.5 ? LEFT : false)
let dy = degAbs < 22.5 || degAbs > 157.5 ? false : (deg < 0 ? UP : DOWN)
if (dx || dy) {
if (dx) {
keyboardJS.pressKey(dx)
}
if (dy) {
keyboardJS.pressKey(dy)
}
vector.multiplyScalar(this.radius / len)
this.dragPoint.position.set(
vector.x,
vector.y
)
}
}
releaseKeys () {
ALL_KEYS.forEach(key => keyboardJS.releaseKey(key))
}
toString () {
return 'TouchDirectionControlPanel'
}
}
export default TouchDirectionControlPanel
|
komamj/Audient
|
storemusic/src/main/java/com/xinshang/store/StoreMusicApplication.java
|
/*
* Copyright 2017 Koma
*
* 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.xinshang.store;
import android.app.Application;
import android.os.StrictMode;
import com.bumptech.glide.Glide;
import com.squareup.leakcanary.LeakCanary;
import com.xinshang.store.data.ApplicationModule;
import com.xinshang.store.data.AudientRepositoryComponent;
import com.xinshang.store.data.AudientRepositoryModule;
import com.xinshang.store.data.DaggerAudientRepositoryComponent;
import com.xinshang.store.utils.LogUtils;
public class StoreMusicApplication extends Application {
private static final String TAG = StoreMusicApplication.class.getSimpleName();
private AudientRepositoryComponent mRepositoryComponent;
@Override
public void onCreate() {
super.onCreate();
mRepositoryComponent = DaggerAudientRepositoryComponent.builder()
.applicationModule(new ApplicationModule(this))
.audientRepositoryModule(new AudientRepositoryModule(BuildConfig.ENDPOINT))
.build();
/*if (BuildConfig.LOG_DEBUG) {
enableStrictMode();
}
*/
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
}
public AudientRepositoryComponent getRepositoryComponent() {
return mRepositoryComponent;
}
@Override
public void onLowMemory() {
super.onLowMemory();
LogUtils.e(TAG, "onLowMemory");
//clear cache
Glide.get(this).clearMemory();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
LogUtils.i(TAG, "onTrimMemory level : " + level);
if (level == TRIM_MEMORY_UI_HIDDEN) {
Glide.get(this).clearMemory();
}
Glide.get(this).trimMemory(level);
}
private void enableStrictMode() {
final StrictMode.ThreadPolicy.Builder threadPolicyBuilder =
new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog();
final StrictMode.VmPolicy.Builder vmPolicyBuilder = new StrictMode.VmPolicy.Builder()
.detectAll().penaltyLog();
threadPolicyBuilder.penaltyFlashScreen();
StrictMode.setThreadPolicy(threadPolicyBuilder.build());
StrictMode.setVmPolicy(vmPolicyBuilder.build());
}
}
|
codacy-acme/spectrum
|
api/test/message/mutations/addMessage.test.js
|
// @flow
import { request } from '../../utils';
import db from 'shared/testing/db';
import data from 'shared/testing/data';
import { fromPlainText, toJSON } from 'shared/draft-utils';
const query = /* GraphQL */ `
mutation sendMessage($message: MessageInput!) {
addMessage(message: $message) {
content {
body
}
}
}
`;
describe('story', () => {
// Find a member of a community
const userCommunity = data.usersCommunities.find(({ isMember }) => isMember);
const user = data.users.find(({ id }) => id === userCommunity.userId);
// Find a thread in the community
const thread = data.threads.find(
({ communityId }) => communityId === userCommunity.communityId
);
const newMessage = {
threadId: thread.id,
threadType: 'story',
messageType: 'draftjs',
content: {
body: JSON.stringify(toJSON(fromPlainText('A new message yayzers'))),
},
};
afterEach(() => {
return Promise.all([
db
.table('messages')
.filter({ content: { body: newMessage.content.body } })
.delete()
.run(),
db
.table('threads')
.get(thread.id)
.update(thread)
.run(),
]);
});
it('should add a new message to the database', async () => {
const context = { user };
const variables = { message: newMessage };
expect.hasAssertions();
const result = await request(query, { context, variables });
expect(result.data.addMessage.content.body).toEqual(
newMessage.content.body
);
});
it("should not allow users who aren't members to send a message", async () => {
const context = { user: null };
const variables = { message: newMessage };
expect.hasAssertions();
const result = await request(query, { context, variables });
expect(result.data.addMessage).toEqual(null);
expect(result.errors.length).toEqual(1);
});
});
describe('directMessageThread', () => {
// Find a member of a dm thread
const userDmThread = data.usersDirectMessageThreads[0];
const user = data.users.find(({ id }) => id === userDmThread.userId);
const dmThread = data.directMessageThreads.find(
({ id }) => id === userDmThread.threadId
);
const newMessage = {
threadId: userDmThread.threadId,
threadType: 'directMessageThread',
messageType: 'draftjs',
content: {
body: JSON.stringify(toJSON(fromPlainText('A new message yayzers'))),
},
};
afterEach(() => {
return Promise.all([
db
.table('messages')
.filter({ content: { body: newMessage.content.body } })
.delete()
.run(),
db
.table('directMessageThreads')
.get(userDmThread.threadId)
.update(dmThread)
.run(),
]);
});
it('should add a new message to the database', async () => {
const context = { user };
const variables = { message: newMessage };
expect.hasAssertions();
const result = await request(query, { context, variables });
expect(result.data.addMessage.content.body).toEqual(
newMessage.content.body
);
});
it("should not allow users who aren't members to send a message", async () => {
const context = { user: null };
const variables = { message: newMessage };
expect.hasAssertions();
const result = await request(query, { context, variables });
expect(result.data.addMessage).toEqual(null);
expect(result.errors.length).toEqual(1);
});
});
|
vjdev/wikipedia-ios
|
Wikipedia/Code/MWKDataObject.h
|
<filename>Wikipedia/Code/MWKDataObject.h
#import <WMF/WMFMTLModel.h>
@interface MWKDataObject : WMFMTLModel
- (id)dataExport;
- (NSString *)optionalString:(NSString *)key dict:(NSDictionary *)dict;
- (NSString *)requiredString:(NSString *)key dict:(NSDictionary *)dict;
- (NSString *)requiredString:(NSString *)key dict:(NSDictionary *)dict allowEmpty:(BOOL)allowEmpty;
- (NSNumber *)optionalNumber:(NSString *)key dict:(NSDictionary *)dict;
- (NSNumber *)requiredNumber:(NSString *)key dict:(NSDictionary *)dict;
- (NSNumber *)numberWithString:(NSString *)str;
- (NSDate *)optionalDate:(NSString *)key dict:(NSDictionary *)dict;
- (NSDate *)requiredDate:(NSString *)key dict:(NSDictionary *)dict;
- (NSDate *)getDateFromIso8601DateString:(NSString *)string;
- (NSString *)iso8601DateString:(NSDate *)date;
- (NSDictionary *)optionalDictionary:(NSString *)key dict:(NSDictionary *)dict;
- (NSDictionary *)requiredDictionary:(NSString *)key dict:(NSDictionary *)dict;
@end
|
rodekruis/digidoc
|
config/strategies/azure.js
|
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
url = require('url'),
AzureStrategy = require('passport-azure-oauth').Strategy,
config = require('../config'),
secrets = require('../secrets'),
users = require('../../app/controllers/users');
module.exports = function() {
// Use facebook strategy
passport.use(new AzureStrategy({
clientId: config.azure.clientID,
clientSecret: config.azure.clientSecret,
tenantId: config.azure.tenantId,
resource: config.azure.resource, // token url
redirectURL: config.usessl ? config.azure.redirectURLSSL : config.azure.redirectURL, // callback
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
var providerData = profile.rawObject;
var domainRegex = /@(.*$)/i;
try {
// get domain from user email address in azure provided data
var matches = providerData.upn.match(domainRegex);
var domain = matches[1].toLowerCase();
// test if email is within valid domain in secrets.json
if (secrets.domains.indexOf(domain) > -1) {
// Set the provider data and include tokens
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;
// Create the user OAuth profile
var providerUserProfile = {
firstName: providerData.given_name,
lastName: providerData.family_name,
displayName: profile.displayname,
email: providerData.upn,
username: profile.username,
provider: 'azure',
providerIdentifierField: 'upn',
providerData: providerData
};
// Save the user OAuth profile
users.saveOAuthUserProfile(req, providerUserProfile, done);
}else{
// fail
done(new Error('Dit is geen geldig @rodekruis.nl account'));
}
}
catch (e) {
console.log(e);
}
}
));
};
|
charmed-kubernetes/autoscaler
|
cluster-autoscaler/vendor/github.com/juju/juju/rpc/params/secrets.go
|
<reponame>charmed-kubernetes/autoscaler<filename>cluster-autoscaler/vendor/github.com/juju/juju/rpc/params/secrets.go
// Copyright 2021 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package params
import (
"time"
)
// CreateSecretArgs holds args for creating secrets.
type CreateSecretArgs struct {
Args []CreateSecretArg `json:"args"`
}
// CreateSecretArg holds the args for creating a secret.
type CreateSecretArg struct {
// Type is "blob" for secrets where the data is passed
// in here; "password" is use for where the actual
// value is generated server side using arguments
// in Params.
Type string `json:"type"`
// Path represents a unique string used to identify a secret.
Path string `json:"path"`
// RotateInterval is how often a secret should be rotated.
RotateInterval time.Duration `json:"rotate-interval"`
// Status represents the secret's status.
Status string `json:"status"`
// Description represents the secret's description.
Description string `json:"description,omitempty"`
// Params are used when generating secrets server side.
// See core/secrets/secret.go.
Params map[string]interface{} `json:"params,omitempty"`
// Tags are the secret tags.
Tags map[string]string `json:"tags,omitempty"`
// Data is the key values of the secret value itself.
Data map[string]string `json:"data,omitempty"`
}
// UpdateSecretArgs holds args for creating secrets.
type UpdateSecretArgs struct {
Args []UpdateSecretArg `json:"args"`
}
// UpdateSecretArg holds the args for creating a secret.
type UpdateSecretArg struct {
// URL identifies the secret to update.
URL string `json:"url"`
// RotateInterval is how often a secret should be rotated.
RotateInterval *time.Duration `json:"rotate-interval"`
// Status represents the secret's status.
Status *string `json:"status"`
// Description represents the secret's description.
Description *string `json:"description,omitempty"`
// Tags are the secret tags.
Tags *map[string]string `json:"tags,omitempty"`
// Params are used when generating secrets server side.
// See core/secrets/secret.go.
Params map[string]interface{} `json:"params,omitempty"`
// Data is the key values of the secret value itself.
// Use an empty value to keep the current value.
Data map[string]string `json:"data,omitempty"`
}
// GetSecretArgs holds the args for getting secrets.
type GetSecretArgs struct {
Args []GetSecretArg `json:"args"`
}
// GetSecretArg holds the args for getting a secret.
// Either specify a URL or ID.
type GetSecretArg struct {
URL string `json:"url,omitempty"`
ID string `json:"id,omitempty"`
}
// SecretValueResults holds secret value results.
type SecretValueResults struct {
Results []SecretValueResult `json:"results"`
}
// SecretValueResult is the result of getting a secret value.
type SecretValueResult struct {
Data map[string]string `json:"data,omitempty"`
Error *Error `json:"error,omitempty"`
}
// ListSecretsArgs holds the args for listing secrets.
type ListSecretsArgs struct {
ShowSecrets bool `json:"show-secrets"`
}
// ListSecretResults holds secret metadata results.
type ListSecretResults struct {
Results []ListSecretResult `json:"results"`
}
// ListSecretResult is the result of getting secret metadata.
type ListSecretResult struct {
URL string `json:"url"`
Path string `json:"path"`
Version int `json:"version"`
RotateInterval time.Duration `json:"rotate-interval"`
Status string `json:"status"`
Description string `json:"description,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
ID int `json:"int"`
Provider string `json:"provider"`
ProviderID string `json:"provider-id,omitempty"`
Revision int `json:"revision"`
CreateTime time.Time `json:"create-time"`
UpdateTime time.Time `json:"update-time"`
Value *SecretValueResult `json:"value,omitempty"`
}
// SecretRotationChange describes a change to a secret rotation config.
type SecretRotationChange struct {
ID int `json:"secret-id"`
URL string `json:"url"`
RotateInterval time.Duration `json:"rotate-interval"`
LastRotateTime time.Time `json:"last-rotate-time"`
}
// SecretRotationWatchResult holds secret rotation change events.
type SecretRotationWatchResult struct {
SecretRotationWatcherId string `json:"watcher-id"`
Changes []SecretRotationChange `json:"changes"`
Error *Error `json:"error,omitempty"`
}
// SecretRotationWatchResults holds the results for any API call which ends up
// returning a list of SecretRotationWatchResult.
type SecretRotationWatchResults struct {
Results []SecretRotationWatchResult `json:"results"`
}
// SecretRotatedArgs holds the args for updating rotated secret info.
type SecretRotatedArgs struct {
Args []SecretRotatedArg `json:"args"`
}
// SecretRotatedArg holds the args for updating rotated secret info.
type SecretRotatedArg struct {
URL string `json:"url"`
When time.Time `json:"when"`
}
|
HuangJie1990/Algorithms
|
src/w11/CourseraServers.java
|
<gh_stars>0
package w11;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
/**
* @author huangjie
* @create 2018-03-20-16:12
**/
public class CourseraServers {
public static void main(String[] args) {
In in = new In(args[0]);
String s = in.readAll();
String[] servers = s.split(",");
for (String server : servers) StdOut.println(server+"\t"+"d3c33hcgiwev3.cloudfront.net");
}
}
|
YuhuRepos/xuanxuan
|
app/utils/debug.js
|
<gh_stars>10-100
const DEBUG = process.env.NODE_ENV === 'development';
global.DEBUG = DEBUG;
if(DEBUG) {
// Mute react warning.
console._error = console.error;
console.error = (errMessage, ...args) => {
if(typeof errMessage === 'string' && errMessage.indexOf('Warning: Unknown prop') === 0) {
return;
}
return console._error(errMessage, ...args);
};
}
export default DEBUG;
|
apache/juneau
|
juneau-rest/juneau-rest-server/src/main/java/org/apache/juneau/rest/RrpcRestOpSession.java
|
// ***************************************************************************************************************************
// * 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.juneau.rest;
import static org.apache.juneau.internal.StringUtils.*;
import static org.apache.juneau.rest.HttpRuntimeException.*;
import java.io.*;
import java.lang.reflect.*;
import org.apache.juneau.http.remote.*;
import org.apache.juneau.http.response.*;
import org.apache.juneau.parser.*;
/**
* A session for a single HTTP request against an RRPC Java method.
*/
public class RrpcRestOpSession extends RestOpSession {
//-----------------------------------------------------------------------------------------------------------------
// Static
//-----------------------------------------------------------------------------------------------------------------
/**
* Static creator.
*
* @param ctx The context of the RRPC Java Method.
* @param session The REST session creating this session.
* @return A new builder.
*/
public static Builder create(RrpcRestOpContext ctx, RestSession session) {
return new Builder(ctx, session);
}
//-----------------------------------------------------------------------------------------------------------------
// Builder
//-----------------------------------------------------------------------------------------------------------------
/**
* Builder class.
*/
public static class Builder extends RestOpSession.Builder {
RrpcRestOpContext ctx;
/**
* Constructor.
*
* @param ctx The context object of the RRPC Java method.
* @param session The REST session.
*/
public Builder(RrpcRestOpContext ctx, RestSession session) {
super(ctx, session);
this.ctx = ctx;
}
@Override
public RrpcRestOpSession build() {
return new RrpcRestOpSession(this);
}
}
//-----------------------------------------------------------------------------------------------------------------
// Instance
//-----------------------------------------------------------------------------------------------------------------
private final RrpcRestOpContext ctx;
/**
* Constructor.
*
* @param builder The builder for this object.
*/
protected RrpcRestOpSession(Builder builder) {
super(builder);
ctx = builder.ctx;
}
@Override
public void run() throws Throwable {
super.run();
RestRequest req = getRequest();
RestResponse res = getResponse();
RestSession session = getRestSession();
final Object o = res.hasOutput() ? res.getOutput(Object.class) : null;
if ("GET".equals(session.getMethod())) {
res.setOutput(ctx.getMeta().getMethodsByPath().keySet());
return;
} else if ("POST".equals(session.getMethod())) {
String pip = session.getUrlPath().getPath();
if (pip.indexOf('/') != -1)
pip = pip.substring(pip.lastIndexOf('/')+1);
pip = urlDecode(pip);
RrpcInterfaceMethodMeta rmm = ctx.getMeta().getMethodMetaByPath(pip);
if (rmm != null) {
Method m = rmm.getJavaMethod();
try {
// Parse the args and invoke the method.
Parser p = req.getBody().getParser();
Object[] args = null;
if (m.getGenericParameterTypes().length == 0)
args = new Object[0];
else {
try (Closeable in = p.isReaderParser() ? req.getReader() : req.getInputStream()) {
args = p.parseArgs(in, m.getGenericParameterTypes());
}
}
res.setOutput(m.invoke(o, args));
return;
} catch (Exception e) {
throw toHttpException(e, InternalServerError.class);
}
}
}
throw new NotFound();
}
}
|
mosarsh/homeschooling
|
app/src/views/sampleViews/extra/forms/ReduxFormView/BasicForm.js
|
/* eslint-disable react/prop-types */
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import * as Yup from 'yup';
import { Field, SubmissionError, reduxForm } from 'redux-form';
import {
Box,
Button,
Card,
CardContent,
CardHeader,
Checkbox,
CircularProgress,
Divider,
FormHelperText,
Grid,
Link,
TextField,
Typography
} from '@material-ui/core';
import { Alert } from '@material-ui/lab';
import wait from 'src/utils/wait';
const validationSchema = Yup.object().shape({
email: Yup.string().email().required('Required'),
firstName: Yup.string().required('Required'),
lastName: Yup.string().required('Required'),
password: <PASSWORD>().min(7, 'Must be at least 7 characters').max(255).required('Required'),
policy: Yup.boolean().oneOf([true], 'This field must be checked')
});
function validate(values) {
const formErrors = {};
try {
validationSchema.validateSync(values, { abortEarly: false });
} catch (errors) {
errors.inner.forEach((error) => {
formErrors[error.path] = error.message;
});
}
return formErrors;
}
async function submit() {
try {
// Make API request
await wait(1000);
} catch (error) {
throw new SubmissionError({
_error: 'Login failed!'
});
}
}
function renderTextField({
input,
label,
meta: { touched, invalid, error },
...rest
}) {
return (
<TextField
error={touched && invalid}
fullWidth
helperText={touched && error}
label={label}
variant="outlined"
{...input}
{...rest}
/>
);
}
function renderCheckbox({
input,
label,
meta: { touched, invalid, error },
...rest
}) {
return (
<div>
<Box
alignItems="center"
display="flex"
ml={-1}
>
<Checkbox
checked={!!input.value}
onChange={input.onChange}
{...input}
{...rest}
/>
{label}
</Box>
{Boolean(touched && invalid) && (
<FormHelperText error>
{error}
</FormHelperText>
)}
</div>
);
}
function BasicForm({ handleSubmit, submitting }) {
const [isAlertVisible, setAlertVisible] = useState(true);
return (
<form onSubmit={handleSubmit(submit)}>
<Card>
<CardHeader title="Basic Form" />
<Divider />
<CardContent>
{isAlertVisible && (
<Box mb={3}>
<Alert
onClose={() => setAlertVisible(false)}
severity="info"
>
This is an info alert - check it out!
</Alert>
</Box>
)}
{(submitting) ? (
<Box
display="flex"
justifyContent="center"
my={5}
>
<CircularProgress />
</Box>
) : (
<>
<Grid
container
spacing={2}
>
<Grid
item
md={6}
xs={12}
>
<Field
name="firstName"
label="<NAME>"
component={renderTextField}
/>
</Grid>
<Grid
item
md={6}
xs={12}
>
<Field
name="lastName"
label="<NAME>"
component={renderTextField}
/>
</Grid>
</Grid>
<Box mt={2}>
<Field
name="email"
label="Email Address"
type="email"
component={renderTextField}
/>
</Box>
<Box mt={2}>
<Field
name="password"
label="Password"
type="password"
component={renderTextField}
/>
</Box>
<Box mt={2}>
<Field
name="policy"
label={(
<Typography
variant="body2"
color="textSecondary"
>
I have read the
{' '}
<Link
component="a"
href="#"
color="secondary"
>
Terms and Conditions
</Link>
</Typography>
)}
component={renderCheckbox}
/>
</Box>
<Box mt={2}>
<Button
color="secondary"
disabled={submitting}
fullWidth
size="large"
type="submit"
variant="contained"
>
Sign up
</Button>
</Box>
</>
)}
</CardContent>
</Card>
</form>
);
}
BasicForm.propTypes = {
handleSubmit: PropTypes.func.isRequired,
submitting: PropTypes.bool.isRequired
};
export default reduxForm({
form: 'BasicForm',
validate,
initialValues: {
email: '<EMAIL>',
firstName: 'John',
lastName: 'Doe',
password: '<PASSWORD>',
policy: false
}
})(BasicForm);
|
kant/ridership
|
src/js/getComponents/getHeaderButtons.js
|
<filename>src/js/getComponents/getHeaderButtons.js
import exportMethods from '../export/exportMethods';
import HeaderButtons from '../header/headerButtons';
const getHeaderButtons = ({ state, components }) => new HeaderButtons({
exportComponents: (callback) => {
const {
atlas,
sidebar,
histogram,
msaAtlas,
legend,
} = components;
const atlasPromise = state.get('scale') === 'national' ? atlas.export() : msaAtlas.export();
Promise.all([
atlasPromise,
sidebar.export(),
histogram.export(),
legend.export(),
]).then(([atlasImage, sidebarImage, histogramImage, legendImage]) => {
callback({
atlasImage,
sidebarImage,
histogramImage,
legendImage,
});
});
},
exportMethods,
howtoButton: d3.select('.header__howto-button'),
aboutButton: d3.select('.header__about-button'),
downloadButton: d3.select('.header__download-button'),
exportButton: d3.select('.header__export-button'),
});
export default getHeaderButtons;
|
EdwardPrentice/wrongo
|
jstests/disk/index_options.js
|
var baseName = "jstests_disk_index_options";
load('jstests/libs/command_line/test_parsed_options.js');
jsTest.log("Testing \"noIndexBuildRetry\" command line option");
var expectedResult = {"parsed": {"storage": {"indexBuildRetry": false}}};
testGetCmdLineOptsMongod({noIndexBuildRetry: ""}, expectedResult);
jsTest.log("Testing \"storage.indexBuildRetry\" config file option");
expectedResult = {
"parsed": {
"config": "jstests/libs/config_files/enable_indexbuildretry.json",
"storage": {"indexBuildRetry": true}
}
};
testGetCmdLineOptsMongod({config: "jstests/libs/config_files/enable_indexbuildretry.json"},
expectedResult);
jsTest.log("Testing with no explicit index option setting");
expectedResult = {
"parsed": {"storage": {}}
};
testGetCmdLineOptsMongod({}, expectedResult);
jsTest.log("Testing explicitly disabled \"noIndexBuildRetry\" config file option");
expectedResult = {
"parsed": {
"config": "jstests/libs/config_files/disable_noindexbuildretry.ini",
"storage": {"indexBuildRetry": true}
}
};
testGetCmdLineOptsMongod({config: "jstests/libs/config_files/disable_noindexbuildretry.ini"},
expectedResult);
print(baseName + " succeeded.");
|
RLGraph/RLGraph
|
rlgraph/components/common/environment_stepper.py
|
# Copyright 2018/2019 The RLgraph 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.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import OrderedDict
from rlgraph import get_backend
from rlgraph.components.component import Component
from rlgraph.components.neural_networks.actor_component import ActorComponent
from rlgraph.environments.environment import Environment
from rlgraph.spaces import Space, Dict
from rlgraph.utils.decorators import rlgraph_api
from rlgraph.utils.ops import DataOpTuple, DataOpDict, flatten_op, unflatten_op
from rlgraph.utils.specifiable_server import SpecifiableServer
if get_backend() == "tf":
import tensorflow as tf
nest = tf.contrib.framework.nest
class EnvironmentStepper(Component):
"""
A Component that takes an Environment object, a PreprocessorStack and a Policy to step
n times through the environment, each time picking actions depending on the states that the environment produces.
"""
def __init__(self, environment_spec, actor_component_spec, num_steps=20,
state_space=None, action_space=None, reward_space=None,
internal_states_space=None,
add_action_probs=False, action_probs_space=None,
add_action=False, add_reward=False,
add_previous_action_to_state=False, add_previous_reward_to_state=False,
max_timesteps=None,
scope="environment-stepper",
**kwargs):
"""
Args:
environment_spec (dict): A specification dict for constructing an Environment object that will be run
inside a SpecifiableServer for in-graph stepping.
actor_component_spec (Union[ActorComponent,dict]): A specification dict to construct this EnvStepper's
ActionComponent (to generate actions) or an already constructed ActionComponent object.
num_steps (int): The number of steps to perform per `step` call.
state_space (Optional[Space]): The state Space of the Environment. If None, will construct a dummy
environment to get the state Space from there.
action_space (Optional[Space]): The action Space of the Environment. If None, will construct a dummy
environment to get the action Space from there.
reward_space (Optional[Space]): The reward Space of the Environment. If None, will construct a dummy
environment to get the reward Space from there.
internal_states_space (Optional[Space]): The internal states Space (when using an RNN inside the
ActorComponent).
add_action_probs (bool): Whether to add all action probabilities for each step to the ActionComponent's
outputs at each step. These will be added as additional tensor inside the
Default: False.
action_probs_space (Optional[Space]): If add_action_probs is True, the Space that the action_probs will have.
This is usually just the flattened (one-hot) action space.
add_action (bool): Whether to add the action to the output of the `step` API-method.
Default: False.
add_reward (bool): Whether to add the reward to the output of the `step` API-method.
Default: False.
add_previous_reward_to_state (bool): Whether to add the previous reward as another input channel to the
ActionComponent's (NN's) input at each step. This is only possible if the state space is already a Dict.
It will be added under the key "previous_reward". Default: False.
add_previous_action_to_state (bool): Whether to add the previous action as another input channel to the
ActionComponent's (NN's) input at each step. This is only possible if the state space is already a Dict.
It will be added under the key "previous_action". Default: False.
add_previous_reward_to_state (bool): Whether to add the previous reward as another input channel to the
ActionComponent's (NN's) input at each step. This is only possible if the state space is already a Dict.
It will be added under the key "previous_reward". Default: False.
max_timesteps (Optional[int]): An optional max. timestep estimate to use for calculating `time_percentage`
values.
"""
super(EnvironmentStepper, self).__init__(scope=scope, **kwargs)
# Create the SpecifiableServer with the given env spec.
if state_space is None or reward_space is None or action_space is None:
# Only to retrieve some information about the particular Env.
dummy_env = Environment.from_spec(environment_spec) # type: Environment
if state_space is None:
state_space = dummy_env.state_space
if action_space is None:
action_space = dummy_env.action_space
if reward_space is None:
_, reward, _, _ = dummy_env.step(actions=action_space.sample())
# TODO: this may break on non 64-bit machines. tf seems to interpret a python float as tf.float64.
reward_space = Space.from_spec(
"float64" if type(reward) == float else float, shape=(1,)
).with_batch_rank()
dummy_env.terminate()
self.reward_space = Space.from_spec(reward_space).with_batch_rank()
self.action_space = Space.from_spec(action_space)
# The state that the environment produces.
self.state_space_env = Space.from_spec(state_space)
# The state that must be fed into the actor-component to produce an action.
# May contain prev_action and prev_reward.
self.state_space_actor = Space.from_spec(state_space)
self.add_previous_action_to_state = add_previous_action_to_state
self.add_previous_reward_to_state = add_previous_reward_to_state
# Circle actions and/or rewards in `step` API-method?
self.add_action = add_action
self.add_reward = add_reward
# The Problem with ContainerSpaces here is that py_func (SpecifiableServer) cannot handle container
# spaces, which is why we need to painfully convert these into flat spaces and tuples here whenever
# we make a call to the env. So to keep things unified, we treat all container spaces
# (state space, preprocessed state) from here on as tuples of primitive spaces sorted by their would be
# flat-keys in a flattened dict).
self.state_space_env_flattened = self.state_space_env.flatten()
# Need to flatten the state-space in case it's a ContainerSpace for the return dtypes.
self.state_space_env_list = list(self.state_space_env_flattened.values())
# TODO: automate this by lookup from the NN Component
self.internal_states_space = None
if internal_states_space is not None:
self.internal_states_space = internal_states_space.with_batch_rank(add_batch_rank=1)
# Add the action/reward spaces to the state space (must be Dict).
if self.add_previous_action_to_state is True:
assert isinstance(self.state_space_actor, Dict),\
"ERROR: If `add_previous_action_to_state` is True as input, state_space must be a Dict!"
self.state_space_actor["previous_action"] = self.action_space
if self.add_previous_reward_to_state is True:
assert isinstance(self.state_space_actor, Dict),\
"ERROR: If `add_previous_reward_to_state` is True as input, state_space must be a Dict!"
self.state_space_actor["previous_reward"] = self.reward_space
self.state_space_actor_flattened = self.state_space_actor.flatten()
self.state_space_actor_list = list(self.state_space_actor_flattened.values())
self.add_action_probs = add_action_probs
# TODO: Auto-infer of self.action_probs_space from action_space.
self.action_probs_space = action_probs_space
if self.add_action_probs is True:
assert isinstance(self.action_probs_space, Space),\
"ERROR: If `add_action_probs` is True, must provide an `action_probs_space`!"
self.environment_spec = environment_spec
self.environment_server = SpecifiableServer(
specifiable_class=Environment,
spec=environment_spec,
output_spaces=dict(
step_flow=self.state_space_env_list + [self.reward_space, bool],
reset_flow=self.state_space_env_list
),
shutdown_method="terminate"
)
# Add the sub-components.
self.actor_component = ActorComponent.from_spec(actor_component_spec) # type: ActorComponent
self.preprocessed_state_space = self.actor_component.preprocessor.get_preprocessed_space(self.state_space_actor)
self.num_steps = num_steps
# Variables that hold information of last step through Env.
self.current_state = None
self.current_internal_states = None
self.time_step = None
self.max_timesteps = max_timesteps
self.has_rnn = self.actor_component.policy.neural_network.has_rnn()
# Add all sub-components (only ActorComponent).
self.add_components(self.actor_component)
def create_variables(self, input_spaces, action_space=None):
self.time_step = self.get_variable(
name="time-step", dtype="int32", initializer=0, trainable=False, local=True, use_resource=True
)
self.current_state = self.get_variable(
name="current-state", from_space=self.state_space_actor, initializer=0, flatten=True, trainable=False,
local=True, use_resource=True
)
if self.has_rnn:
self.current_internal_states = self.get_variable(
name="current-internal-states", from_space=self.internal_states_space,
initializer=0.0, flatten=True, trainable=False, local=True, use_resource=True,
add_batch_rank=1
)
@rlgraph_api(returns=1)
def _graph_fn_step(self):
if get_backend() == "tf":
def scan_func(accum, time_delta):
# Not needed: preprocessed-previous-states (tuple!)
# `state` is a tuple as well. See comment in ctor for why tf cannot use ContainerSpaces here.
internal_states = None
state = accum[1]
if self.has_rnn:
internal_states = accum[-1]
state = tuple(tf.convert_to_tensor(value=s) for s in state)
flat_state = OrderedDict()
for i, flat_key in enumerate(self.state_space_actor_flattened.keys()):
# Add a simple (size 1) batch rank to the state so it'll pass through the NN.
# - Also have to add a time-rank for RNN processing.
expanded = state[i]
for _ in range(1 if self.has_rnn is False else 2):
expanded = tf.expand_dims(input=expanded, axis=0)
# Make None so it'll be recognized as batch-rank by the auto-Space detector.
flat_state[flat_key] = tf.placeholder_with_default(
input=expanded, shape=(None,) + ((None,) if self.has_rnn is True else ()) +
self.state_space_actor_list[i].shape
)
# Recreate state as the original Space to pass it into the actor-component.
state = unflatten_op(flat_state)
# Get action and preprocessed state (as batch-size 1).
out = (self.actor_component.get_preprocessed_state_and_action if self.add_action_probs is False else
self.actor_component.get_preprocessed_state_action_and_action_probs)(
state,
# Add simple batch rank to internal_states.
None if internal_states is None else DataOpTuple(internal_states), # <- None for non-RNN systems
time_precentage=(((self.time_step + time_delta) / self.max_timesteps) if
self.max_timesteps is not None else None)
)
# Get output depending on whether it contains internal_states or not.
a = out["action"]
action_probs = out.get("action_probs")
current_internal_states = out.get("last_internal_states")
# Strip the batch (and maybe time) ranks again from the action in case the Env doesn't like it.
a_no_extra_ranks = a[0, 0] if self.has_rnn is True else a[0]
# Step through the Env and collect next state (tuple!), reward and terminal as single values
# (not batched).
out = self.environment_server.step_flow(a_no_extra_ranks)
s_, r, t_ = out[:-2], out[-2], out[-1]
r = tf.cast(r, dtype="float32")
# Add a and/or r to next_state?
if self.add_previous_action_to_state is True:
assert isinstance(s_, tuple), "ERROR: Cannot add previous action to non tuple!"
s_ = s_ + (a_no_extra_ranks,)
if self.add_previous_reward_to_state is True:
assert isinstance(s_, tuple), "ERROR: Cannot add previous reward to non tuple!"
s_ = s_ + (r,)
# Note: s_ is packed as tuple.
ret = [t_, s_] + \
([a_no_extra_ranks] if self.add_action else []) + \
([r] if self.add_reward else []) + \
([(action_probs[0][0] if self.has_rnn is True else action_probs[0])] if
self.add_action_probs is True else []) + \
([tuple(current_internal_states)] if self.has_rnn is True else [])
return tuple(ret)
# Initialize the tf.scan run.
initializer = [
# terminals
tf.zeros(shape=(), dtype=tf.bool),
# current (raw) state (flattened components if ContainerSpace).
tuple(map(lambda x: x.read_value(), self.current_state.values()))
]
# Append actions and rewards if needed.
if self.add_action:
initializer.append(tf.zeros(shape=self.action_space.shape, dtype=self.action_space.dtype))
if self.add_reward:
initializer.append(tf.zeros(shape=self.reward_space.shape))
# Append action probs if needed.
if self.add_action_probs is True:
initializer.append(tf.zeros(shape=self.action_probs_space.shape))
# Append internal states if needed.
if self.current_internal_states is not None:
initializer.append(tuple(
tf.placeholder_with_default(
internal_s.read_value(), shape=(None,) + tuple(internal_s.shape.as_list()[1:])
) for internal_s in self.current_internal_states.values()
))
# Scan over n time-steps (tf.range produces the time_delta with respect to the current time_step).
# NOTE: Changed parallel to 1, to resolve parallel issues.
step_results = list(tf.scan(
fn=scan_func, elems=tf.range(self.num_steps, dtype="int32"), initializer=tuple(initializer),
back_prop=False
))
# Assign all values that need to be passed again into the next scan.
assigns = [tf.assign_add(self.time_step, self.num_steps)] # time step
# State (or flattened state components).
for flat_key, var_ref, state_comp in zip(
self.state_space_actor_flattened.keys(), self.current_state.values(), step_results[1]
):
assigns.append(self.assign_variable(var_ref, state_comp[-1])) # -1: current state (last observed)
# Current internal state.
if self.current_internal_states is not None:
# TODO: What if internal states is not the last item in the list anymore due to some change.
slot = -1
# TODO: What if internal states is a dict? Right now assume some tuple.
# Remove batch rank from internal states again.
internal_states_wo_batch = list()
for i, var_ref in enumerate(self.current_internal_states.values()): #range(len(step_results[slot])):
# 1=batch axis (which has dim=1); 0=time axis.
internal_states_component = tf.squeeze(step_results[slot][i], axis=1)
assigns.append(self.assign_variable(var_ref, internal_states_component[-1:]))
internal_states_wo_batch.append(internal_states_component)
step_results[slot] = tuple(internal_states_wo_batch)
# Concatenate first and rest (and make the concatenated tensors (which are the important return information)
# dependent on the assigns).
with tf.control_dependencies(control_inputs=assigns):
full_results = []
for slot in range(len(step_results)):
first_values, rest_values = initializer[slot], step_results[slot]
# Internal states need a slightly different concatenating as the batch rank is missing.
if self.current_internal_states is not None and slot == len(step_results) - 1:
full_results.append(nest.map_structure(self._concat, first_values, rest_values))
# States need concatenating (first state needed).
elif slot == 1:
full_results.append(nest.map_structure(
lambda first, rest: tf.concat([[first], rest], axis=0), first_values, rest_values)
)
# Everything else does not need concatenating (saves one op).
else:
full_results.append(step_results[slot])
# Re-build DataOpDicts of states (from tuple right now).
rebuild_s = DataOpDict()
for flat_key, var_ref, s_comp in zip(
self.state_space_actor_flattened.keys(), self.current_state.values(), full_results[1]
):
rebuild_s[flat_key] = s_comp
rebuild_s = unflatten_op(rebuild_s)
full_results[1] = rebuild_s
# Let the auto-infer system know, what time rank we have.
full_results = DataOpTuple(full_results)
for o in flatten_op(full_results).values():
o._time_rank = 0 # which position in the shape is the time-rank?
return full_results
@staticmethod
def _concat(first, rest):
"""
Helper method to concat initial value and scanned collected results.
"""
shape = first.shape.as_list()
first.set_shape(shape=(1,) + tuple(shape[1:]))
return tf.concat([first, rest], axis=0)
#@rlgraph_api
def step_with_dict_return(self):
"""
Simple wrapper to get a dict returned instead of a tuple of values.
Returns:
Dict:
- `terminals`: The is-terminal signals.
- `states`: The states.
- `actions` (optional): The actions actually taken.
- `rewards` (optional): The rewards actually received.
- `action_probs` (optional): The action probabilities.
- `internal_states` (optional): The internal-states (only for RNN type NNs in the ActorComponent).
"""
"""
out = self.step()
ret = dict(
terminals=out[0],
states=out[1]
)
if self.has_rnn:
ret["internal_states"] = out[-1]
plus = 0
if self.add_action:
ret["actions"] = out[2]
plus += 1
if self.add_reward:
ret["rewards"] = out[2 + plus]
plus += 1
if self.add_action_probs:
ret["action_probs"] = out[2 + plus]
plus += 1
return ret
"""
pass
|
java-tools/awe
|
awe-framework/awe-modules/awe-scheduler/src/main/java/com/almis/awe/scheduler/listener/SchedulerJobListener.java
|
<filename>awe-framework/awe-modules/awe-scheduler/src/main/java/com/almis/awe/scheduler/listener/SchedulerJobListener.java
package com.almis.awe.scheduler.listener;
import com.almis.awe.config.ServiceConfig;
import com.almis.awe.scheduler.bean.event.SchedulerTaskFinishedEvent;
import com.almis.awe.scheduler.bean.event.SchedulerTaskStartedEvent;
import com.almis.awe.scheduler.bean.task.Task;
import com.almis.awe.scheduler.job.scheduled.SchedulerJob;
import lombok.extern.log4j.Log4j2;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.springframework.context.ApplicationEventPublisher;
import static com.almis.awe.scheduler.constant.JobConstants.TASK;
import static com.almis.awe.scheduler.constant.ListenerConstants.JOB_LISTENER_NAME;
/**
* @author dfuentes
*/
@Log4j2
public class SchedulerJobListener extends ServiceConfig implements JobListener {
// Autowired services
private final ApplicationEventPublisher eventPublisher;
public SchedulerJobListener(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
@Override
public String getName() {
return JOB_LISTENER_NAME;
}
@Override
public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {
// Fire event
if (jobExecutionContext.getJobInstance() instanceof SchedulerJob) {
Task task = (Task) jobExecutionContext.getJobDetail().getJobDataMap().get(TASK);
eventPublisher.publishEvent(new SchedulerTaskStartedEvent(this, task));
}
}
@Override
public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
// DO nothing
}
@Override
public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException exception) {
// Publish event
if (jobExecutionContext.getJobInstance() instanceof SchedulerJob) {
SchedulerJob job = (SchedulerJob) jobExecutionContext.getJobInstance();
eventPublisher.publishEvent(new SchedulerTaskFinishedEvent(this, job.getTask(), job.getExecution(), job.getExecution().getExecutionTime()));
}
}
}
|
Magnitus-/gogcli
|
manifest/manifest-game-installer_test.go
|
package manifest
import (
"testing"
)
func TestManifestGameInstallerHasOneOfOses(t *testing.T) {
installer := ManifestGameInstaller{
Languages: []string{"french"},
Os: "linux",
Url: "/dontknowdontcare",
Title: "installer",
Name: "installer",
Version: "vDontKnow",
Date: "2111-11-11",
EstimatedSize: "1kb",
VerifiedSize: 1000,
Checksum: "sdfdsfsdfdsfwe",
}
if installer.HasOneOfOses([]string{"windows", "macos"}) {
t.Errorf("Should not indicate it has an os it doesn't have")
}
if !installer.HasOneOfOses([]string{"windows", "linux"}) {
t.Errorf("Should indicate it has an os it has")
}
}
func TestManifestGameInstallerHasOneOfLanguages(t *testing.T) {
installer := ManifestGameInstaller{
Languages: []string{"french"},
Os: "linux",
Url: "/dontknowdontcare",
Title: "installer",
Name: "installer",
Version: "vDontKnow",
Date: "2111-11-11",
EstimatedSize: "1kb",
VerifiedSize: 1000,
Checksum: "sdfdsfsdfdsfwe",
}
if installer.HasOneOfLanguages([]string{"english", "german"}) {
t.Errorf("Should not indicate it has a language it doesn't have")
}
if !installer.HasOneOfLanguages([]string{"english", "french"}) {
t.Errorf("Should indicate it has a language it has")
}
}
func TestManifestGameInstallerIsEquivalentTo(t *testing.T) {
installer := ManifestGameInstaller{
Languages: []string{"french"},
Os: "linux",
Url: "/dontknowdontcare",
Title: "installer",
Name: "installer",
Version: "vDontKnow",
Date: "2111-11-11",
EstimatedSize: "1kb",
VerifiedSize: 1000,
Checksum: "icheck",
}
otherInstaller := ManifestGameInstaller{
Languages: []string{"english"},
Os: "windows",
Url: "/dontknowdontcare",
Title: "installer",
Name: "installer",
Version: "vDontKnowToo",
Date: "2111-12-12",
EstimatedSize: "2kb",
VerifiedSize: 1000,
Checksum: "icheck",
}
if !installer.IsEquivalentTo(&otherInstaller, ChecksumValidation, false) {
t.Errorf("Installers who url, title, name, verified size and checksum match should be equivalent when empty checksums are not tolerated")
}
if !installer.IsEquivalentTo(&otherInstaller, ChecksumValidationIfPresent, false) {
t.Errorf("Installers who url, title, name, verified size and checksum match should be equivalent when empty checksums are tolerated")
}
if !installer.IsEquivalentTo(&otherInstaller, ChecksumNoValidation, false) {
t.Errorf("Installers who url, title, name, verified size and checksum match should be equivalent when checksums are not validated")
}
otherInstaller.Checksum = "idonotcheck"
if installer.IsEquivalentTo(&otherInstaller, ChecksumValidation, false) {
t.Errorf("Installers whose checksum doesn't match should not be equivalent when empty checksums are not tolerated")
}
if installer.IsEquivalentTo(&otherInstaller, ChecksumValidationIfPresent, false) {
t.Errorf("Installers whose checksum doesn't match should not be equivalent when empty checksums are tolerated")
}
if !installer.IsEquivalentTo(&otherInstaller, ChecksumNoValidation, false) {
t.Errorf("Installers whose checksum doesn't match should be equivalent when checksums are not validated")
}
otherInstaller.Checksum = ""
if installer.IsEquivalentTo(&otherInstaller, ChecksumValidation, false) {
t.Errorf("Installers whose checksum is empty should not be equivalent when empty checksums are not tolerated")
}
if !installer.IsEquivalentTo(&otherInstaller, ChecksumValidationIfPresent, false) {
t.Errorf("Installers whose checksum is empty should be equivalent when empty checksums are tolerated")
}
if !installer.IsEquivalentTo(&otherInstaller, ChecksumNoValidation, false) {
t.Errorf("Installers whose checksum is empty should be equivalent when checksums are not validated")
}
installer.Checksum = ""
otherInstaller.Checksum = "icheck"
if installer.IsEquivalentTo(&otherInstaller, ChecksumValidation, false) {
t.Errorf("Installers whose checksum is empty should not be equivalent when empty checksums are not tolerated")
}
if !installer.IsEquivalentTo(&otherInstaller, ChecksumValidationIfPresent, false) {
t.Errorf("Installers whose checksum is empty should be equivalent when empty checksums are tolerated")
}
if !installer.IsEquivalentTo(&otherInstaller, ChecksumNoValidation, false) {
t.Errorf("Installers whose checksum is empty should be equivalent when checksums are not validated")
}
installer.Checksum = ""
otherInstaller.Checksum = ""
if installer.IsEquivalentTo(&otherInstaller, ChecksumValidation, false) {
t.Errorf("Installers whose checksum is empty should not be equivalent when empty checksums are not tolerated")
}
if !installer.IsEquivalentTo(&otherInstaller, ChecksumValidationIfPresent, false) {
t.Errorf("Installers whose checksum is empty should be equivalent when empty checksums are tolerated")
}
if !installer.IsEquivalentTo(&otherInstaller, ChecksumNoValidation, false) {
t.Errorf("Installers whose checksum is empty should be equivalent when empty checksums are not tolerated")
}
otherInstaller.Title = "wrong"
if installer.IsEquivalentTo(&otherInstaller, ChecksumValidationIfPresent, false) {
t.Errorf("Installers whose title differs should be not equivalent")
}
otherInstaller.Title = "installer"
otherInstaller.Name = "wrong"
if installer.IsEquivalentTo(&otherInstaller, ChecksumValidationIfPresent, false) {
t.Errorf("Installers whose name differs should be not equivalent")
}
otherInstaller.Name = "installer"
otherInstaller.Url = "/dadadada"
if installer.IsEquivalentTo(&otherInstaller, ChecksumValidationIfPresent, false) {
t.Errorf("Installers whose url differs should be not equivalent")
}
otherInstaller.Url = "/dontknowdontcare"
otherInstaller.VerifiedSize = 9999
if installer.IsEquivalentTo(&otherInstaller, ChecksumValidationIfPresent, false) {
t.Errorf("Installers whose verified size differs should be not equivalent")
}
}
|
Bhaskers-Blu-Org2/Sora
|
DebugTool/source/DbgPlotViewer/PlotWndPlayPauseController.h
|
#pragma once
#include <map>
#include "AsyncObject.h"
#include "ProcessOpened.h"
#include "PlotWindowOpened.h"
class PlotWndPlayPauseController : public AsyncObject
{
public:
~PlotWndPlayPauseController();
void PauseProcess(std::shared_ptr<ProcessOpened>);
void AddProcessPlotWnd(std::shared_ptr<ProcessOpened>, std::shared_ptr<PlotWindowOpened>);
void RemovePlotWnd(std::shared_ptr<PlotWindowOpened>);
void SelectProcess(std::shared_ptr<ProcessOpened>);
void PlayPauseSelectedProcess(bool);
private:
std::map<std::shared_ptr<ProcessOpened>, std::set<std::shared_ptr<PlotWindowOpened> > > _processWndMap;
std::shared_ptr<ProcessOpened> _processSelected;
};
|
Prodian0013/cri-o
|
internal/oci/oci_test.go
|
package oci_test
import (
"github.com/cri-o/cri-o/internal/oci"
"github.com/cri-o/cri-o/pkg/config"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
// The actual test suite
var _ = t.Describe("Oci", func() {
t.Describe("New", func() {
It("should succeed with default config", func() {
// Given
c, err := config.DefaultConfig()
Expect(err).To(BeNil())
// When
runtime := oci.New(c)
// Then
Expect(runtime).NotTo(BeNil())
})
})
t.Describe("Oci", func() {
// The system under test
var sut *oci.Runtime
// Test constants
const (
invalidRuntime = "invalid"
defaultRuntime = "runc"
)
runtimes := config.Runtimes{
defaultRuntime: {
RuntimePath: "/bin/sh",
RuntimeType: "",
RuntimeRoot: "/run/runc",
}, invalidRuntime: {},
}
BeforeEach(func() {
c, err := config.DefaultConfig()
Expect(err).To(BeNil())
c.DefaultRuntime = defaultRuntime
c.Runtimes = runtimes
sut = oci.New(c)
Expect(sut).NotTo(BeNil())
})
It("should succeed to retrieve the runtimes", func() {
// Given
// When
result := sut.Runtimes()
// Then
Expect(result).To(Equal(runtimes))
})
It("should succeed to validate a runtime handler", func() {
// Given
// When
handler, err := sut.ValidateRuntimeHandler(defaultRuntime)
// Then
Expect(err).To(BeNil())
Expect(handler).To(Equal(runtimes[defaultRuntime]))
})
})
t.Describe("ExecSyncError", func() {
It("should succeed to get the exec sync error", func() {
// Given
sut := oci.ExecSyncError{}
// When
result := sut.Error()
// Then
Expect(result).To(ContainSubstring("error"))
})
})
})
|
entcore/entcore
|
auth/src/main/java/org/entcore/auth/services/impl/AbstractSSOProvider.java
|
/*
* Copyright © "Open Digital Education", 2015
*
* This program is published by "Open Digital Education".
* You must indicate the name of the software and the company in any production /contribution
* using the software and indicate on the home page of the software industry in question,
* "powered by Open Digital Education" with a reference to the website: https://opendigitaleducation.com/.
*
* This program is free software, licensed under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, version 3 of the License.
*
* You can redistribute this application and/or modify it since you respect the terms of the GNU Affero General Public License.
* If you modify the source code and then use this modified source code in your creation, you must make available the source code of your modifications.
*
* You should have received a copy of the GNU Affero General Public License along with the software.
* If not, please see : <http://www.gnu.org/licenses/>. Full compliance requires reading the terms of this license and following its directives.
*/
package org.entcore.auth.services.impl;
import fr.wseduc.webutils.Either;
import fr.wseduc.webutils.Utils;
import io.vertx.core.eventbus.EventBus;
import org.entcore.auth.services.SamlServiceProvider;
import org.entcore.common.neo4j.Neo4j;
import org.entcore.common.neo4j.Neo4jResult;
import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AttributeStatement;
import org.opensaml.saml2.core.Conditions;
import org.opensaml.xml.XMLObject;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public abstract class AbstractSSOProvider implements SamlServiceProvider {
protected static final String RETURN_QUERY = "OPTIONAL MATCH (p:Profile) " +
"WHERE HAS(u.profiles) AND p.name = head(u.profiles) " +
"RETURN DISTINCT u.id as id, u.activationCode as activationCode, " +
"u.login as login, u.email as email, u.mobile as mobile, u.federated, u.blocked as blockedUser, p.blocked as blockedProfile, u.source as source ";
protected boolean validConditions(Assertion assertion, Handler<Either<String, Object>> handler) {
if (Utils.validationParamsNull(handler, "invalid.assertion", assertion)) return false;
Conditions conditions = assertion.getConditions();
if (conditions.getNotBefore() == null || !conditions.getNotBefore().isBeforeNow() ||
conditions.getNotOnOrAfter() == null || !conditions.getNotOnOrAfter().isAfterNow()) {
handler.handle(new Either.Left<String, Object>("invalid.conditions"));
return false;
}
return true;
}
public void generate(EventBus eb, String userId, String host, String serviceProviderEntityId, Handler<Either<String, io.vertx.core.json.JsonArray>> handler) {
handler.handle(new Either.Left<String, io.vertx.core.json.JsonArray>("Override is required on generate function in AbstractSSOProvider"));
}
protected String getAttribute(Assertion assertion, String attr) {
if (assertion.getAttributeStatements() != null) {
for (AttributeStatement statement : assertion.getAttributeStatements()) {
for (Attribute attribute : statement.getAttributes()) {
if (attr.equals(attribute.getName())) {
for (XMLObject o : attribute.getAttributeValues()) {
if (o.getDOM() != null) {
return o.getDOM().getTextContent();
}
}
}
}
}
}
return null;
}
protected List<String> getAttributes(Assertion assertion, String attr) {
List<String> attributes = new ArrayList<>();
if (assertion.getAttributeStatements() != null) {
for (AttributeStatement statement : assertion.getAttributeStatements()) {
for (Attribute attribute : statement.getAttributes()) {
if (attr.equals(attribute.getName()) || attr.equals(attribute.getFriendlyName())) {
for (XMLObject o : attribute.getAttributeValues()) {
if (o.getDOM() != null) {
attributes.add(o.getDOM().getTextContent());
}
}
}
}
}
}
return attributes;
}
protected void executeQuery(String query, final JsonObject params, final Handler<Either<String, Object>> handler) {
executeQuery(query, params, null, handler);
}
protected void executeQuery(String query, final JsonObject params, final Assertion assertion,
final Handler<Either<String, Object>> handler) {
executeFederateQuery(query, params, assertion, Neo4j.getInstance(), handler);
}
static void executeFederateQuery(String query, JsonObject params, final Assertion assertion,
Neo4j neo4j, final Handler<Either<String, Object>> handler) {
executeFederateQuery(query, params, assertion, true, neo4j, handler);
}
static void executeFederateQuery(String query, JsonObject params, final Assertion assertion, final boolean setFederated,
Neo4j neo4j, final Handler<Either<String, Object>> handler) {
query += RETURN_QUERY;
neo4j.execute(query, params, Neo4jResult.validUniqueResultHandler(
new Handler<Either<String, JsonObject>>() {
@Override
public void handle(final Either<String, JsonObject> event) {
if (event.isRight() && (
event.right().getValue().getBoolean("blockedProfile", false) ||
event.right().getValue().getBoolean("blockedUser", false)
)) {
handler.handle(new Either.Left<String, Object>("blocked.profile"));
} else if (setFederated && event.isRight() && event.right().getValue().getBoolean("federated") == null &&
event.right().getValue().getString("id") != null) {
String query = "MATCH (u:User {id: {id}}) SET u.federated = true ";
JsonObject params = new JsonObject().put("id", event.right().getValue().getString("id"));
if (assertion != null && assertion.getIssuer() != null &&
assertion.getIssuer().getValue() != null && !assertion.getIssuer().getValue().trim().isEmpty()) {
query += ", u.federatedIDP = {idp} ";
params.put("idp", assertion.getIssuer().getValue());
}
Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> event2) {
handler.handle(new Either.Right<String, Object>(event.right().getValue()));
}
});
} else if (event.isRight()) {
handler.handle(new Either.Right<String, Object>(event.right().getValue()));
} else {
handler.handle(new Either.Left<String, Object>(event.left().getValue()));
}
}
}));
}
protected void executeMultiVectorQuery(String query, JsonObject params, final Assertion assertion,
final Handler<Either<String, Object>> handler) {
query += (RETURN_QUERY + ", s.name as structureName");
Neo4j.getInstance().execute(query, params, Neo4jResult.validResultHandler(new Handler<Either<String, JsonArray>>() {
@Override
public void handle(final Either<String, JsonArray> event) {
if (event.isRight()) {
JsonArray ids = new fr.wseduc.webutils.collections.JsonArray();
final Set<String> userIds = new HashSet<>();
final JsonArray users = event.right().getValue();
for (Object o: users) {
if (!(o instanceof JsonObject)) continue;
JsonObject j = (JsonObject) o;
if (j.getBoolean("blockedProfile", false)) {
handler.handle(new Either.Left<String, Object>("blocked.profile"));
return;
}
userIds.add(j.getString("id"));
if (Utils.isNotEmpty(j.getString("id")) && !j.getBoolean("federated", false)) {
ids.add(j.getString("id"));
}
}
if (ids.size() > 0) {
String query = "MATCH (u:User) WHERE u.id IN {ids} SET u.federated = true ";
JsonObject params = new JsonObject().put("ids", ids);
if (assertion != null && assertion.getIssuer() != null &&
assertion.getIssuer().getValue() != null && !assertion.getIssuer().getValue().trim().isEmpty()) {
query += ", u.federatedIDP = {idp} ";
params.put("idp", assertion.getIssuer().getValue());
}
Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> event2) {
if (userIds.size() == 1) {
handler.handle(new Either.Right<String, Object>(users.getJsonObject(0)));
} else {
handler.handle(new Either.Right<String, Object>(users));
}
}
});
} else {
if (userIds.size() == 1) {
handler.handle(new Either.Right<String, Object>(users.getJsonObject(0)));
} else {
handler.handle(new Either.Right<String, Object>(users));
}
}
} else {
handler.handle(new Either.Left<String, Object>(event.left().getValue()));
}
}
}));
}
}
|
sgholamian/log-aware-clone-detection
|
LACCPlus/Camel/4015_1.java
|
<filename>LACCPlus/Camel/4015_1.java
//,temp,FhirCreateIT.java,56,66,temp,FhirCreateIT.java,45,54
//,3
public class xxx {
@Test
public void testCreateStringResource() throws Exception {
Patient patient = new Patient().addName(new HumanName().addGiven("Vincent").setFamily("Freeman"));
String patientString = this.fhirContext.newXmlParser().encodeResourceToString(patient);
MethodOutcome result = requestBody("direct://RESOURCE_STRING", patientString);
LOG.debug("resource: " + result);
assertNotNull(result, "resource result");
assertTrue(result.getCreated());
}
};
|
mabetle/mcore
|
mterm/colorterm_print.go
|
package mterm
import (
"fmt"
)
// Print funcs
func PrintBlack(s string) { fmt.Print(Black(s)) }
func PrintWhite(s string) { fmt.Print(White(s)) }
func PrintRed(s string) { fmt.Print(Red(s)) }
func PrintGreen(s string) { fmt.Print(Green(s)) }
func PrintYellow(s string) { fmt.Print(Yellow(s)) }
func PrintBlue(s string) { fmt.Print(Blue(s)) }
func PrintMagenta(s string) { fmt.Print(Magenta(s)) }
func PrintCyan(s string) { fmt.Print(Cyan(s)) }
// Printf funcs
func PrintfWhite(format string, args ...interface{}) { PrintWhite(fmt.Sprintf(format, args...)) }
func PrintfBlack(format string, args ...interface{}) { PrintBlack(fmt.Sprintf(format, args...)) }
func PrintfRed(format string, args ...interface{}) { PrintRed(fmt.Sprintf(format, args...)) }
func PrintfGreen(format string, args ...interface{}) { PrintGreen(fmt.Sprintf(format, args...)) }
func PrintfYellow(format string, args ...interface{}) { PrintYellow(fmt.Sprintf(format, args...)) }
func PrintfBlue(format string, args ...interface{}) { PrintBlue(fmt.Sprintf(format, args...)) }
func PrintfMagenta(format string, args ...interface{}) { PrintMagenta(fmt.Sprintf(format, args...)) }
func PrintfCyan(format string, args ...interface{}) { PrintCyan(fmt.Sprintf(format, args...)) }
func ColorPrint(s string, i int) { fmt.Print(ColorText(i, s)) }
|
weucode/COMFORT
|
artifact_evaluation/data/codeCoverage/montage_generate/569.js
|
function f0() {
return arguments + 23 === 'foo,bar';
}
if (!f0())
throw new Error('Test failed');
|
garyyeap/serverless-mocker
|
test/spec/server/response/res.headers.js
|
<reponame>garyyeap/serverless-mocker
import { expect } from 'chai';
import { createServer } from 'service-mocker/server';
import {
uniquePath,
sendRequest,
} from '../../helpers/';
export default function () {
const { router } = createServer();
describe('res.headers', () => {
it('should has a `headers` property', async () => {
let response;
const path = uniquePath();
router.get(path, (_req, res) => {
response = res;
res.end();
});
await sendRequest(path);
expect(response).to.have.property('headers')
.and.that.is.an.instanceof(Headers);
});
describe('send headers to client', () => {
it('should receive a `X-Test` header', async () => {
const path = uniquePath();
router.get(path, (_req, res) => {
res.headers.set('X-Test', 'ServiceMocker');
res.end();
});
const { headers } = await sendRequest(path);
expect(headers.get('X-Test')).to.equal('ServiceMocker');
});
});
});
}
|
eduramirezh/pyinaturalist
|
pyinaturalist/converters.py
|
"""Type conversion utilities"""
from datetime import date, datetime, timedelta
from dateutil.parser import UnknownTimezoneWarning # type: ignore # (missing from type stubs)
from dateutil.parser import parse as parse_date
from dateutil.tz import tzlocal, tzoffset
from io import BytesIO
from logging import getLogger
from os.path import abspath, expanduser
from pathlib import Path
from typing import IO, Any, Dict, List, MutableSequence, Optional, Union
from warnings import catch_warnings, simplefilter
from pyinaturalist.constants import (
AnyFile,
Coordinates,
Dimensions,
HistogramResponse,
JsonResponse,
ResponseResult,
)
GENERIC_TIME_FIELDS = ('created_at', 'last_post_at', 'updated_at')
OBSERVATION_TIME_FIELDS = (
'created_at_details',
'created_time_zone',
'observed_on',
'observed_on_details',
'observed_on_string',
'observed_time_zone',
'time_zone_offset',
)
logger = getLogger(__name__)
# Wrapper functions to apply conversions to all results in a response
# --------------------
def convert_all_coordinates(results: List[ResponseResult]) -> List[ResponseResult]:
"""Convert coordinate pairs in response items from strings to floats, if valid
Args:
results: Results from API response; expects coordinates in either 'location' key or
'latitude' and 'longitude' keys
"""
results = [convert_lat_long_dict(result) for result in results]
results = [convert_lat_long_list(result) for result in results]
return results
def convert_all_place_coordinates(response: JsonResponse) -> JsonResponse:
"""Convert locations for both standard and community-contributed places to floats"""
response['results'] = {
'standard': convert_all_coordinates(response['results'].get('standard')),
'community': convert_all_coordinates(response['results'].get('community')),
}
return response
def convert_all_timestamps(results: List[ResponseResult]) -> List[ResponseResult]:
"""Replace all date/time info with datetime objects, where possible"""
results = [convert_generic_timestamps(result) for result in results]
results = [convert_observation_timestamps(result) for result in results]
return results
def convert_histogram(response: JsonResponse) -> HistogramResponse:
"""Convert a response containing time series data into a single ``{date: value}`` dict"""
# The inner result object's key will be the name of the interval requested
interval = next(iter(response['results'].keys()))
histogram = response['results'][interval]
# Convert keys to appropriate type depending on interval
if interval in ['month_of_year', 'week_of_year']:
return {int(k): v for k, v in histogram.items()}
else:
return {parse_date(k): v for k, v in histogram.items()}
# Type conversion functions for individual results or values
# --------------------
def convert_csv_list(obj: Any) -> str:
"""Convert list parameters into an API-compatible (comma-delimited) string"""
if not obj:
return ''
elif isinstance(obj, list):
return ','.join(map(str, obj))
else:
return str(obj)
def convert_isoformat(value: Union[date, datetime, str]) -> str:
"""Convert a date, datetime, or timestamps to a string in ISO 8601 format.
If it's a datetime and doesn't already have tzinfo, set it to the system's local timezone.
Raises:
:py:exc:`dateutil.parser._parser.ParserError` if a date/datetime format is invalid
"""
if isinstance(value, str):
value = parse_date(value)
if isinstance(value, datetime) and not value.tzinfo:
value = value.replace(tzinfo=tzlocal())
return value.isoformat()
def convert_lat_long(obj: Union[Dict, List, None, str]) -> Optional[Coordinates]:
"""Convert a coordinate pair as a dict, list, or string into a pair of floats, if valid"""
if not obj:
return None
if isinstance(obj, str):
return try_float_pair(*str(obj).split(','))
elif isinstance(obj, list):
return try_float_pair(*obj)
elif isinstance(obj, dict):
return try_float_pair(obj.get('latitude'), obj.get('longitude'))
def convert_lat_long_dict(result: ResponseResult) -> ResponseResult:
"""Convert a coordinate pair dict within a response to floats, if valid"""
if 'latitude' in result and 'longitude' in result:
result['latitude'] = try_float(result['latitude'])
result['longitude'] = try_float(result['longitude'])
return result
def convert_lat_long_list(result: ResponseResult):
"""Convert a coordinate pairs in a response item from strings to floats, if valid"""
# Format inner record if present, e.g. for search results
if 'record' in result:
result['record'] = convert_lat_long_list(result['record'])
return result
if ',' in (result.get('location') or ''):
result['location'] = [try_float(coord) for coord in result['location'].split(',')]
return result
def convert_generic_timestamps(result: ResponseResult) -> ResponseResult:
"""Replace generic created/updated info that's returned by multiple endpoints.
**Note:** Compared to observation timestamps, these are generally more reliable. These seem to
be consistently in ISO 8601 format.
"""
# Format inner record if present, e.g. for search results
if 'record' in result:
result['record'] = convert_generic_timestamps(result['record'])
return result
for field in GENERIC_TIME_FIELDS:
datetime_obj = try_datetime(result.get(field, ''))
if datetime_obj:
result[field] = datetime_obj
return result
# TODO: Replace this with attrs version
def convert_observation_timestamps(result: ResponseResult) -> ResponseResult:
"""Replace observation date/time info with datetime objects"""
if 'created_at_details' not in result and 'observed_on_string' not in result:
return result
observation = result.copy()
tz_offset = observation.get('time_zone_offset', '')
tz_name = observation.get('observed_time_zone')
created_datetime = observation.get('created_at')
if not isinstance(created_datetime, datetime):
created_datetime = try_datetime(observation.get('created_at_details', {}).get('date'))
created_datetime = convert_offset(created_datetime, tz_offset, tz_name)
# Ignore any timezone info in observed_on timestamp; offset field is more reliable
observed_datetime = try_datetime(observation.get('observed_on_string', ''), ignoretz=True)
observed_datetime = convert_offset(observed_datetime, tz_offset, tz_name)
# If valid, add the datetime objects and remove all other redundant date/time fields
if created_datetime and observed_datetime:
for field in OBSERVATION_TIME_FIELDS:
observation.pop(field, None)
observation['created_at'] = created_datetime
observation['observed_on'] = observed_datetime
return observation
def convert_observation_timestamp(
timestamp: str, tz_offset: str = None, tz_name: str = None, ignoretz: bool = False
) -> Optional[datetime]:
"""Convert an observation timestamp + timezone info to a datetime. This is needed because
observed_on and created_at can be in in inconsistent (user-submitted?) formats.
"""
dt = try_datetime(timestamp, ignoretz=ignoretz)
return convert_offset(dt, tz_offset, tz_name)
def convert_offset(
datetime_obj: Optional[datetime], tz_offset: str = None, tz_name: str = None
) -> Optional[datetime]:
"""Use timezone offset info to replace a datetime's tzinfo"""
if not datetime_obj or not tz_offset:
return datetime_obj
try:
offset = parse_offset(tz_offset, tz_name)
return datetime_obj.replace(tzinfo=offset)
except (AttributeError, TypeError, ValueError) as e:
logger.debug(f'Could not parse offset: {tz_offset}: {str(e)}')
return None
def parse_offset(tz_offset: str, tz_name: str = None) -> tzoffset:
"""Convert a timezone offset string to a tzoffset object, accounting for some common variations
in format
Examples:
>>> parse_offset('GMT-08:00', 'PST')
tzoffset('PST', -28800)
>>> parse_offset('-06:00')
tzoffset(None, -21600)
>>> parse_offset('+05:30')
tzoffset(None, 19800)
>>> parse_offset('0530')
tzoffset(None, 19800)
"""
def remove_prefixes(text, prefixes):
for prefix in prefixes:
if text.startswith(prefix):
text = text[len(prefix) :] # noqa # black and flake8 fight over this one
return text
# Parse hours, minutes, and sign from offset string; account for either `hh:mm` or `hhmm` format
tz_offset = remove_prefixes(tz_offset, ['GMT', 'UTC']).strip()
multiplier = -1 if tz_offset.startswith('-') else 1
tz_offset = tz_offset.lstrip('+-')
if ':' in tz_offset:
hours, minutes = tz_offset.split(':')
else:
hours, minutes = tz_offset[:2], tz_offset[2:]
# Convert to a timezone offset in +/- seconds
delta = timedelta(hours=int(hours), minutes=int(minutes))
return tzoffset(tz_name, delta.total_seconds() * multiplier)
def safe_split(value: Any, delimiter: str = '|') -> List[str]:
"""Split a pipe-(or other token)-delimited string"""
return list(ensure_list(value, convert_csv=True, delimiter=delimiter))
def strip_empty_values(values: Dict) -> Dict:
"""Remove any dict items with empty or ``None`` values."""
return {k: v for k, v in values.items() if v or v in [False, 0, 0.0]}
# Type conversion functions for collections
# -------------------
def ensure_list(value: Any, convert_csv: bool = False, delimiter: str = ',') -> MutableSequence[Any]:
"""Convert an object, response, or (optionally) comma-separated string into a list"""
if not value:
return []
elif isinstance(value, dict) and 'results' in value:
value = value['results']
elif convert_csv and isinstance(value, str) and delimiter in value:
return [s.strip() for s in value.split(delimiter)]
if isinstance(value, MutableSequence):
return value
elif isinstance(value, (tuple, set)):
return list(value)
else:
return [value]
def ensure_file_obj(value: AnyFile) -> IO:
"""Given a file object or path, read it into a file-like object if it's a path"""
if isinstance(value, (str, Path)):
file_path = abspath(expanduser(value))
logger.info(f'Reading from file: {file_path}')
with open(file_path, 'rb') as f:
return BytesIO(f.read())
return value
# Formatting functions
# --------------------
def format_dimensions(dimensions: Union[Dict[str, int], Dimensions, None]) -> Dimensions:
"""Simplify a 'dimensions' dict into a ``(width, height)`` tuple"""
if not dimensions:
return (0, 0)
if isinstance(dimensions, tuple):
return dimensions
return dimensions.get("width", 0), dimensions.get("height", 0)
def format_file_size(n_bytes: int) -> str:
"""Convert a file size in bytes into a human-readable format"""
filesize = float(n_bytes or 0)
def _format(unit):
return f'{int(filesize)} {unit}' if unit == 'bytes' else f'{filesize:.2f} {unit}'
for unit in ['bytes', 'KB', 'MB', 'GB']:
if filesize < 1024 or unit == 'GB':
return _format(unit)
filesize /= 1024
return _format(unit)
def format_license(value: str) -> Optional[str]:
"""Format a Creative Commons license code"""
return str(value).upper().replace('_', '-') if value else None
# 'Safe' conversion functions that return invalid values as None instead of raising an error
# --------------------
def try_datetime(timestamp: Any, **kwargs) -> Optional[datetime]:
"""Parse a timestamp string into a datetime, if valid; return ``None`` otherwise"""
if isinstance(timestamp, datetime):
return timestamp
if not timestamp or not str(timestamp).strip():
return None
try:
# Suppress UnknownTimezoneWarning
with catch_warnings():
simplefilter('ignore', category=UnknownTimezoneWarning)
return parse_date(timestamp, **kwargs)
except (AttributeError, TypeError, ValueError) as e:
logger.debug(f'Could not parse timestamp: {timestamp}: "{str(e)}"')
return None
def try_float(value: Any) -> Optional[float]:
"""Convert a value to a float, if valid; return ``None`` otherwise"""
try:
return float(value)
except (TypeError, ValueError):
return None
def try_float_pair(*values: Any) -> Optional[Coordinates]:
"""Convert a pair of coordinat values to floats, if both are valid; return ``None`` otherwise"""
if len(values) != 2:
return None
try:
return float(values[0]), float(values[1])
except (TypeError, ValueError):
return None
def try_int(value: Any) -> Optional[float]:
"""Convert a value to a int, if valid; return ``None`` otherwise"""
try:
return int(value)
except (TypeError, ValueError):
return None
def try_int_or_float(value: Any) -> Union[int, float, None]:
"""Convert a value to either an int or a float, if valid; return ``None`` otherwise"""
return try_int(str(value)) or try_float(str(value))
|
vandreas19/POJ_sol
|
2051/2092660_AC_15MS_76K.cpp
|
<gh_stars>10-100
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<algorithm>
using namespace std;
struct Query
{
int iID,iPeriod,iNext;
};
bool Compare(Query pLeft,Query pRight)
{
if(pLeft.iNext>pRight.iNext)
return true;
else if(pLeft.iNext<pRight.iNext)
return false;
else if(pLeft.iID>pRight.iID)
return true;
else
return false;
}
void main()
{
char cTemp[20],cCommand[10];
int iCount;
Query qTemp;
vector<Query> vqStream;
while(gets(cTemp))
{
if(cTemp[0]=='#')
break;
sscanf(cTemp,"%s %d %d",cCommand,&(qTemp.iID),&(qTemp.iPeriod));
qTemp.iNext=qTemp.iPeriod;
vqStream.push_back(qTemp);
}
make_heap(vqStream.begin(),vqStream.end(),Compare);
scanf("%d",&iCount);
while(iCount--)
{
printf("%d\n",vqStream[0].iID);
pop_heap(vqStream.begin(),vqStream.end(),Compare);
(vqStream.end()-1)->iNext+=(vqStream.end()-1)->iPeriod;
push_heap(vqStream.begin(),vqStream.end(),Compare);
}
}
|
cctvzd7/aliyun-openapi-java-sdk
|
aliyun-java-sdk-sofa/src/main/java/com/aliyuncs/sofa/transform/v20190815/CreateLinkeBahamutFlowtaskResponseUnmarshaller.java
|
<reponame>cctvzd7/aliyun-openapi-java-sdk<filename>aliyun-java-sdk-sofa/src/main/java/com/aliyuncs/sofa/transform/v20190815/CreateLinkeBahamutFlowtaskResponseUnmarshaller.java
/*
* 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.aliyuncs.sofa.transform.v20190815;
import com.aliyuncs.sofa.model.v20190815.CreateLinkeBahamutFlowtaskResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class CreateLinkeBahamutFlowtaskResponseUnmarshaller {
public static CreateLinkeBahamutFlowtaskResponse unmarshall(CreateLinkeBahamutFlowtaskResponse createLinkeBahamutFlowtaskResponse, UnmarshallerContext _ctx) {
createLinkeBahamutFlowtaskResponse.setRequestId(_ctx.stringValue("CreateLinkeBahamutFlowtaskResponse.RequestId"));
createLinkeBahamutFlowtaskResponse.setResultCode(_ctx.stringValue("CreateLinkeBahamutFlowtaskResponse.ResultCode"));
createLinkeBahamutFlowtaskResponse.setResultMessage(_ctx.stringValue("CreateLinkeBahamutFlowtaskResponse.ResultMessage"));
createLinkeBahamutFlowtaskResponse.setErrorMessage(_ctx.stringValue("CreateLinkeBahamutFlowtaskResponse.ErrorMessage"));
createLinkeBahamutFlowtaskResponse.setMessage(_ctx.stringValue("CreateLinkeBahamutFlowtaskResponse.Message"));
createLinkeBahamutFlowtaskResponse.setSuccess(_ctx.booleanValue("CreateLinkeBahamutFlowtaskResponse.Success"));
return createLinkeBahamutFlowtaskResponse;
}
}
|
onesword0618/leetcode
|
src/test/maximum69Number.test.js
|
<filename>src/test/maximum69Number.test.js<gh_stars>0
const maximum69Number = require("./../main/maximum69Number");
describe("最大桁の6を9に変換する", () => {
test("9669を与えて9969を返す", () => {
expect(maximum69Number(9669)).toBe(9969);
});
});
|
deyanpeychev00/JS-Web-SoftUni-September-2017
|
ExpressJS-Fundamentals/exercises/04-Exercise-NodeJS-Commonly-Used-Modules-Files-Utilities-Streams-Deployment/meme-node/handlers/memeHandler.js
|
<gh_stars>1-10
const fs = require('fs');
const allMemesHTML = './views/viewAll.html';
const addMemeHTML = './views/addMeme.html';
const memeDetailsHTML = './views/details.html';
const db = require('./../config/dataBase');
const formidable = require('formidable');
const shortid = require('shortid');
let memeGenerator = (id, title, memeSrc, description, privacy) => {
return {
id: id,
title: title,
memeSrc: memeSrc,
description: description,
privacy: privacy,
dateStamp: Date.now()
}
};
let viewAll = (req, res) => {
let memes = db.getDb()
.sort((a, b) => {
return b.dateStamp - a.dateStamp;
})
.filter(meme => {
return meme.privacy === 'on';
});
fs.readFile(allMemesHTML, (err, data) => {
if (err) {
console.warn(err);
return;
}
data = data.toString().replace('<div id="replaceMe">{{replaceMe}}</div>', () => {
let html = '';
for (let i = 0; i < memes.length; i++) {
html += `<div class="meme">
<a href="/getDetails?id=${memes[i].id}" data-id="${memes[i].id}">
<img class="memePoster" src="${memes[i].memeSrc}"/>
</div>
`;
}
return html;
});
res.writeHead(200, {
'content-type': 'text/html'
});
res.write(data);
res.end();
});
};
let viewAddMeme = (req, res) => {
fs.readFile(addMemeHTML, (err, data) => {
if (err) {
console.warn(err);
return;
}
res.writeHead(200, {
'content-type': 'text/html'
});
res.write(data);
res.end();
});
};
let addMeme = (req, res) => {
let form = new formidable.IncomingForm();
let dbLen = Math.ceil(db.getDb().length / 10);
let fileName = shortid.generate();
let filePath = `./public/memeStorage/${dbLen}/${fileName}.jpg`;
form.on('error', (err) => {
console.log(err);
return;
}).on('fileBegin', (name, file) => {
fs.access(`./public/memeStorage/${dbLen}`, (err) => {
if (err) {
console.log(err);
fs.mkdirSync(`./public/memeStorage/${dbLen}`);
}
});
file.path = filePath;
});
form.parse(req, function (err, fields, files) {
let id = shortid.generate();
let newMeme = memeGenerator(id, fields.memeTitle, filePath, fields.memeDescription, fields.status);
db.add(newMeme);
db.save()
.then(() => {
viewAddMeme(req,res);
});
});
};
let getDetails = (req, res) => {
fs.readFile(memeDetailsHTML, (err, data) => {
if (err) {
console.warn(err);
return;
}
let memes = db.getDb();
let targetedMeme = {};
for (let meme of memes) {
if (req.url.endsWith(meme.id)) {
targetedMeme = meme;
break;
}
}
data = data.toString().replace('<div id="replaceMe">{{replaceMe}}</div>', () => {
return `<div class="content">
<img src="${targetedMeme.memeSrc}" alt=""/>
<h3>Title ${targetedMeme.title}</h3>
<p> ${targetedMeme.description}</p>
<button><a href="${targetedMeme.memeSrc}" download="${targetedMeme.title}">Download Meme</a></button>
</div>`;
});
res.writeHead(200, {
'content-type': 'text/html'
});
res.write(data);
res.end();
});
};
module.exports = (req, res) => {
if (req.pathname === '/viewAllMemes' && req.method === 'GET') {
viewAll(req, res);
} else if (req.pathname === '/addMeme' && req.method === 'GET') {
viewAddMeme(req, res);
} else if (req.pathname === '/addMeme' && req.method === 'POST') {
addMeme(req, res);
} else if (req.pathname.startsWith('/getDetails') && req.method === 'GET') {
getDetails(req, res);
} else {
return true;
}
};
|
dsebban/protocol
|
mgcp/src/main/scala/spinoco/protocol/mgcp/codec/MGCPParameterCodec.scala
|
package spinoco.protocol.mgcp.codec
import scodec.{Attempt, Codec, DecodeResult, Err, SizeBound}
import scodec.bits.BitVector
import scodec.codecs._
import shapeless.{:+:, CNil, Coproduct, Inl, Inr}
import spinoco.protocol.mgcp._
import spinoco.protocol.mgcp.MGCPParameter._
import spinoco.protocol.common.codec._
import spinoco.protocol.mgcp.BearerAttribute.{BearerEncoding, BearerExtensionName}
import spinoco.protocol.mgcp.CapabilityValue.{SupportedModes, SupportedPackages}
import spinoco.protocol.mgcp.LocalConnectionOption._
import scala.annotation.tailrec
import scala.concurrent.duration._
object MGCPParameterCodec {
/**
* A combinator, that first splits the stream by comma and then applies codec, stripping any whitespace after coma
*/
def delimitedByComma[A](codec: Codec[A]):Codec[List[A]] = {
listDelimited(BitVector.view(",".getBytes), takeWhileChar(dropWS ~> codec)(','))
}
/**
* Like `delimitedByComma`, but codec is first applied, and then if there is another item (because of the next character being comma
* then next codec is applied
*/
def delimitedByComma2[A](codec: Codec[A]): Codec[List[A]] = {
val commaSpace = BitVector.view(", ".getBytes())
val comma = ','.toByte
@tailrec
def go(acc: Vector[A], bs: BitVector): Attempt[DecodeResult[List[A]]] = {
codec.decode(bs) match {
case Attempt.Failure(err) => Attempt.failure(err)
case Attempt.Successful(DecodeResult(a, rem)) =>
if (rem.isEmpty) Attempt.successful(DecodeResult((acc :+ a).toList, BitVector.empty))
else if (rem.getByte(0) != comma) Attempt.failure(Err("Separator must be `,` optionally followed by whitespace"))
else {
val next = rem.bytes.tail.dropWhile(_.toChar.isWhitespace)
go(acc :+ a, next.bits)
}
}
}
new Codec[List[A]] {
val encoder = listDelimited(commaSpace, codec)
def sizeBound: SizeBound = SizeBound.unknown
def encode(value: List[A]): Attempt[BitVector] = encoder.encode(value)
def decode(bits: BitVector): Attempt[DecodeResult[List[A]]] = go(Vector.empty, bits)
}
}
val responseAckCodec: Codec[ResponseAck] = {
val ackTxCodec: Codec[AckTx] =
untilWs(transactionId :: optional(recover2(constant(BitVector.view("-".getBytes))), transactionId))
.as[AckTx]
delimitedByComma(ackTxCodec)
.as[ResponseAck]
}
val bearerInformationCodec: Codec[BearerInformation] = {
val baCodec: Codec[BearerAttribute] = {
choice(
(constant(BitVector("e:".getBytes)) :: mappedEnum(ascii, BearerEncodingType.values.map { v => v -> v.toString}.toMap)).as[BearerEncoding].upcast
, ascii.as[BearerExtensionName].upcast
)
}
delimitedByComma(baCodec)
.as[BearerInformation]
}
val callIdCodec: Codec[CallId] = {
tagged[String, CallId](guard(ascii)(is32Hex("CallId")))
.as[CallId]
}
val connectionIdParameterCodec: Codec[ConnectionId] = {
connectionIdCodec.as[ConnectionId]
}
val notifiedEntityCodec: Codec[NotifiedEntity] = {
val entityNameCodec: Codec[EntityName] = {
val withLocalPart =
(
("LocalName" | takeWhileChar(localEndpointNameCodec)('@') <~ constantString1("@"))
.xmap[Some[LocalEndpointName]](Some(_), _.get).upcast[Option[LocalEndpointName]] ::
("Domain" | takeWhileChar(domainCodec)(':')) ::
("Port" | optional(recover2(constant(BitVector(":".getBytes))), intAsString))
).as[EntityName]
val domainOnly =
(
("LocalName" | provide(None).upcast[Option[LocalEndpointName]]) ::
("Domain" | takeWhileChar(domainCodec)(':')) ::
("Port" | optional(recover2(constant(BitVector(":".getBytes))), intAsString))
).as[EntityName]
choice(
withLocalPart
, domainOnly
)
}
entityNameCodec
.as[NotifiedEntity]
}
val requestIdentifierCodec: Codec[RequestIdentifier] = {
tagged[String, RequestIdentifier](guard(ascii)(is32Hex("RequestIdentifier")))
.as[RequestIdentifier]
}
val localOptionCodec: Codec[LocalConnectionOption] = {
val compressionAlgorithmCodec: Codec[CompressionAlgorithm] =
ascii.as[CompressionAlgorithm]
val bandwidthCodec: Codec[Bandwidth] =
(intAsString :: optional(recover2(constant(BitVector.view("-".getBytes))), intAsString)).as[Bandwidth]
val echoCancelCodec: Codec[EchoCancel] =
mappedEnum(ascii, Map(true -> "on", false -> "off" ))
.as[EchoCancel]
val packetizationPeriodCodec: Codec[PacketizationPeriod] =
intAsString.as[PacketizationPeriod]
val gainControlCodec: Codec[GainControl] =
choice[Option[Int]](
constant(BitVector.view("auto".getBytes)).xmap[None.type](_ => None, _ => ()).upcast
, intAsString.xmap[Some[Int]](Some(_), _.get).upcast
).as[GainControl]
val silenceSuppressionCodec: Codec[SilenceSuppression] =
mappedEnum(ascii, Map(true -> "on", false -> "off" ))
.as[SilenceSuppression]
val typeOfServiceCodec: Codec[TypeOfService] =
ascii.as[TypeOfService]
val resourceReservationCodec: Codec[ResourceReservation] =
ascii.as[ResourceReservation]
val typeOfNetworkCodec: Codec[TypeOfNetwork] = {
val ntCodec = mappedEnum(ascii, NetworkType.values.map { v => v -> v.toString }.toMap)
listDelimited(BitVector.view(";".getBytes), ntCodec).narrow(
ls => {
ls.headOption match {
case None => Attempt.failure(Err("At least one type of the netowrk must be specified"))
case Some(nt) => Attempt.successful(TypeOfNetwork(nt, ls.tail))
}
}
, ton => ton.nt +: ton.supported
)
}
val keyCodec: Codec[String] = takeWhile(ascii)(_ != ':'.asInstanceOf[Byte]) <~ constant(BitVector.view(":".getBytes))
choice(
discriminated[LocalConnectionOption].by(keyCodec)
.typecase("p", packetizationPeriodCodec)
.typecase("a", compressionAlgorithmCodec)
.typecase("b", bandwidthCodec)
.typecase("e", echoCancelCodec)
.typecase("gc", gainControlCodec)
.typecase("s", silenceSuppressionCodec)
.typecase("t", typeOfServiceCodec)
.typecase("r", resourceReservationCodec)
.typecase("nt", typeOfNetworkCodec)
, (keyCodec :: utf8).as[VendorOption].upcast[LocalConnectionOption]
)
}
val localConnectionOptionsCodec: Codec[LocalConnectionOptions] = {
delimitedByComma(localOptionCodec).as[LocalConnectionOptions]
}
val connectionModeTypeCodec: Codec[ConnectionModeType] = {
import ConnectionModeType._
choice(
mappedEnum(ascii, Map(
SendOnly -> "sendonly"
, ReceiveOnly -> "recvonly"
, SendAndReceive -> "sendrecv"
, Inactive -> "inactive"
, Conference -> "confrnce"
, Loopback -> "loopback"
, ConnectionTest -> "conttest"
, NetworkLoop -> "netwloop"
, NetworkTest -> "netwtest"
))
, (takeWhile(ascii)(_ != '/'.asInstanceOf[Byte]) :: constant(BitVector.view("/".getBytes)) :: utf8).as[Extension].upcast[ConnectionModeType]
)
}
val connectionModeCodec: Codec[ConnectionMode] =
connectionModeTypeCodec.as[ConnectionMode]
val listOfRequestedEventsCodec: Codec[List[RequestedEvent]] = {
import RequestedEventAction._
val embeddedEventActionCodec: Codec[EmbeddedRequest] = {
val RCodec: Codec[List[RequestedEvent]] =
constantString1("R") ~> guard(enclosedBy('(',')')(lazily(listOfRequestedEventsCodec))) {
ls => if (ls.isEmpty) Some(Err("Requested Events must not be empty")) else None
}
val SCodec: Codec[List[ParametrizedEvent]] =
constantString1("S") ~> guard(enclosedBy('(',')')(lazily(listOfParametrizedEvents))) {
ls => if (ls.isEmpty) Some(Err("Signalled Events must not be empty")) else None
}
val DCodec: Codec[String] = constantString1("D") ~> enclosedBy('(',')')(ascii)
type Choice = List[RequestedEvent] :+: List[ParametrizedEvent] :+: String :+: CNil
constantString1("E") ~> enclosedBy('(',')')(
delimitedByComma2((RCodec :+: SCodec :+: DCodec).choice)
).xmap (
ls => {
ls.foldLeft(EmbeddedRequest(Nil, Nil, None)) {
case (er, Inr(Inr(Inl(digitmap)))) => er.copy(digitMap = Some(digitmap))
case (er, Inr(Inl(signalled))) => er.copy(signalled = signalled)
case (er, Inl(requests)) => er.copy(requests = requests)
case (er, _) => er
}
}
, er => {
er.requests.headOption.toList.map { _ => Coproduct[Choice](er.requests) } ++
er.signalled.headOption.toList.map { _ => Coproduct[Choice](er.signalled) } ++
er.digitMap.toList.map(Coproduct[Choice](_))
}
)
}
val actionCodec = "Event Action" |
choice[RequestedEventAction](
constantString1("N").decodeAs(NotifyImmediately).upcast
, constantString1("A").decodeAs(Accumulate).upcast
, constantString1("D").decodeAs(TreatByDigitMap).upcast
, constantString1("S").decodeAs(Swap).upcast
, constantString1("I").decodeAs(Ignore).upcast
, constantString1("K").decodeAs(KeepActive).upcast
, "Embeded " | embeddedEventActionCodec.upcast
)
val eventCodec: Codec[RequestedEvent] = {
(
takeWhileChar(eventSpecificationCodec)('(', ',') ::
("Event Actions" | optional(lookahead2(constantString1("(")), enclosedBy('(', ')')(delimitedByComma2(actionCodec))))
.xmap[List[RequestedEventAction]](_.toList.flatten, ls => ls.headOption.map(_ => ls))
).as[RequestedEvent]
}
delimitedByComma2(eventCodec)
}
val requestedEventsCodec: Codec[RequestedEvents] = {
listOfRequestedEventsCodec.as[RequestedEvents]
}
val listOfParametrizedEvents: Codec[List[ParametrizedEvent]] = {
val eventCodec: Codec[ParametrizedEvent] = {
(eventSpecificationCodec ::
("Actions" | optional(recover2(constantString1("(")), takeWhile(ascii)(_ != ')'.asInstanceOf[Byte]) <~ constantString1(")") ))
)
.as[ParametrizedEvent]
}
delimitedByComma(eventCodec)
}
val signalRequestsCodec: Codec[SignalRequests] = {
listOfParametrizedEvents.as[SignalRequests]
}
val digitMapCodec: Codec[DigitMap] =
utf8.as[DigitMap]
val observedEventsCodec: Codec[ObservedEvents] =
listOfParametrizedEvents.as[ObservedEvents]
val connectionParametersCodec: Codec[ConnectionParameters] = {
import ConnectionParameter._
val keyCodec: Codec[String] = takeWhile(ascii)(_ != '='.asInstanceOf[Byte])
val param =
discriminated[ConnectionParameter].by(keyCodec)
.typecase("PS", intAsString.as[PacketSent])
.typecase("OS", intAsString.as[OctetsSent])
.typecase("PR", intAsString.as[PacketReceived])
.typecase("OR", intAsString.as[OctetsReceived])
.typecase("PL", intAsString.as[PacketLost])
.typecase("JI", intAsString.as[Jitter])
.typecase("LA", intAsString.as[AvgLatency])
delimitedByComma(param).as[ConnectionParameters]
}
val reasonCodeCodec: Codec[ReasonCode] = {
stringEnumerated(ascii, ReasonCodeType).as[ReasonCode]
}
val specificEndpointIDCodec: Codec[SpecificEndpointID] =
localEndpointNameCodec.as[SpecificEndpointID]
val secondEndpointIDCodec: Codec[SecondEndpointID] =
localEndpointNameCodec.as[SecondEndpointID]
val secondConnectionIDCodec: Codec[SecondConnectionID] =
tagged[String, ConnectionId](guard(ascii)(is32Hex("SecondConnectionID")))
.as[SecondConnectionID]
val requestedInfoCodec: Codec[RequestedInfo] =
delimitedByComma(
stringEnumerated(ascii, MGCPParameterInfoName)
).as[RequestedInfo]
val quarantineHandlingCodec: Codec[QuarantineHandling] =
delimitedByComma(
stringEnumerated(ascii, QuarantineHandlingStyle)
).as[QuarantineHandling]
val detectEventsCodec: Codec[DetectEvents] =
listOfParametrizedEvents.as[DetectEvents]
val restartMethodCodec: Codec[RestartMethod] =
stringEnumerated(ascii, RestartMethodType).as[RestartMethod]
val restartDelayCodec: Codec[RestartDelay] =
intAsString.xmap[FiniteDuration](_.seconds, _.toSeconds.toInt).as[RestartDelay]
val capabilitiesCodec: Codec[Capabilities] = {
val supportedPackagesCodec : Codec[SupportedPackages] =
constantString1("v:") ~>
listDelimited(BitVector.view(";".getBytes), utf8).as[SupportedPackages]
val supportedModesCodec: Codec[SupportedModes] =
constantString1("m:") ~>
listDelimited(BitVector.view(";".getBytes), connectionModeTypeCodec).as[SupportedModes]
val valueCodec =
choice[CapabilityValue](
localOptionCodec.upcast
, supportedPackagesCodec.upcast
, supportedModesCodec.upcast
)
delimitedByComma(valueCodec).as[Capabilities]
}
val eventStatesCodec: Codec[EventStates] =
utf8.as[EventStates]
val packageListCodec: Codec[PackageList] = {
val packageVersionCodec: Codec[PackageVersion] = {
(takeWhile(utf8)(_ != ':'.asInstanceOf[Byte]) :: constantString1(":") ::
ascii).as[PackageVersion]
}
listDelimited(BitVector.view(",".getBytes), packageVersionCodec).as[PackageList]
}
val maxMGCPDatagramCodec: Codec[MaxMGCPDatagram] =
intAsString.as[MaxMGCPDatagram]
val codec: Codec[MGCPParameter] = {
val keyCodec: Codec[String] = takeWhile(ascii)(_ != ':'.asInstanceOf[Byte]) <~ constant(BitVector.view(":".getBytes())) <~ WS
val keyAndParamCodec =
discriminated[MGCPParameter].by(keyCodec)
.typecase("K", "ResponseAck" | responseAckCodec)
.typecase("B", "BearerInformation" | bearerInformationCodec)
.typecase("C", "CallId" | callIdCodec)
.typecase("I", "ConnectionId" | connectionIdParameterCodec)
.typecase("N", "NotifiedEntity" | notifiedEntityCodec)
.typecase("X", "RequestIdentifier" | requestIdentifierCodec)
.typecase("L", "LocalConnectionOptions" | localConnectionOptionsCodec)
.typecase("M", "ConnectionMode" | connectionModeCodec)
.typecase("R", "RequestEvents" | requestedEventsCodec)
.typecase("S", "SignalRequests" | signalRequestsCodec)
.typecase("D", "DigitMap" | digitMapCodec)
.typecase("O", "ObservedEvents" | observedEventsCodec)
.typecase("P", "ConnectionParameter" | connectionParametersCodec)
.typecase("E", "ReasonCode" | reasonCodeCodec)
.typecase("Z", "SpecificEndpointId" | specificEndpointIDCodec)
.typecase("Z2", "SecondEnpointId" | secondEndpointIDCodec)
.typecase("I2", "SecondConnectionId" | secondConnectionIDCodec)
.typecase("F", "RequestedInfo" | requestedInfoCodec)
.typecase("Q", "QuarantineHandling" | quarantineHandlingCodec)
.typecase("T", "DetectEvents" | detectEventsCodec)
.typecase("RM", "RestartMethod" | restartMethodCodec)
.typecase("RD", "RestartDelay" | restartDelayCodec)
.typecase("A", "Capabilities" | capabilitiesCodec)
.typecase("ES", "EventStates" | eventStatesCodec)
.typecase("PL", "PackageList" | packageListCodec)
.typecase("MD", "MaxMGCPDatagram" | maxMGCPDatagramCodec)
untilEOL(keyAndParamCodec)
}
}
|
lucykolosova/waivio
|
src/client/wallet/TransfersCards/MarketCloseOrder.js
|
<reponame>lucykolosova/waivio
import React from 'react';
import PropTypes from 'prop-types';
import TransactionCardContainer from './TransactionCardContainer';
const MarketCloseOrder = ({ timestamp, orderType }) => (
<TransactionCardContainer timestamp={timestamp} iconType={'check'}>
<span>Limit order to {orderType} successful</span>
</TransactionCardContainer>
);
MarketCloseOrder.propTypes = {
timestamp: PropTypes.number.isRequired,
orderType: PropTypes.string.isRequired,
};
export default MarketCloseOrder;
|
ItamarBenjamin/codeine
|
src/common/codeine/jsons/auth/EncryptionUtils.java
|
package codeine.jsons.auth;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import codeine.utils.ExceptionUtils;
import com.google.common.base.Charsets;
public class EncryptionUtils{
private static byte[] encrypt(String key, String value) {
byte[] raw = key.getBytes(Charsets.US_ASCII);
if (raw.length != 16) {
throw ExceptionUtils.asUnchecked(new IllegalArgumentException("Invalid key size."));
}
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
return cipher.doFinal(value.getBytes(Charsets.US_ASCII));
} catch (Exception e) {
throw ExceptionUtils.asUnchecked(e);
}
}
public static String encryptToken(String token, String secret) {
return new String(new BASE64Encoder().encode(encrypt(secret, token)));
}
public static String decrypt(String secret, String encrypted) {
byte[] raw = secret.getBytes(Charsets.US_ASCII);
if (raw.length != 16) {
throw ExceptionUtils.asUnchecked(new IllegalArgumentException("Invalid key size."));
}
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
byte[] original = cipher.doFinal(new BASE64Decoder().decodeBuffer(encrypted));
return new String(original, Charsets.US_ASCII);
} catch (Exception e) {
throw ExceptionUtils.asUnchecked(e);
}
}
}
|
BasisTI/madre
|
prescricao/src/test/java/br/com/basis/madre/prescricao/web/rest/PrescricaoMedicamentoResourceIT.java
|
package br.com.basis.madre.prescricao.web.rest;
import br.com.basis.madre.prescricao.PrescricaoApp;
import br.com.basis.madre.prescricao.domain.PrescricaoMedicamento;
import br.com.basis.madre.prescricao.repository.PrescricaoMedicamentoRepository;
import br.com.basis.madre.prescricao.repository.search.PrescricaoMedicamentoSearchRepository;
import br.com.basis.madre.prescricao.service.PrescricaoMedicamentoService;
import br.com.basis.madre.prescricao.service.dto.PrescricaoMedicamentoDTO;
import br.com.basis.madre.prescricao.service.mapper.PrescricaoMedicamentoMapper;
import br.gov.nuvem.comum.microsservico.web.rest.errors.ExceptionTranslator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.util.Collections;
import java.util.List;
import static br.com.basis.madre.prescricao.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@link PrescricaoMedicamentoResource} REST controller.
*/
@SpringBootTest(classes = PrescricaoApp.class)
public class PrescricaoMedicamentoResourceIT {
private static final Long DEFAULT_ID_PACIENTE = 1L;
private static final Long UPDATED_ID_PACIENTE = 2L;
private static final String DEFAULT_OBSERVACAO = "AAAAAAAAAA";
private static final String UPDATED_OBSERVACAO = "BBBBBBBBBB";
@Autowired
private PrescricaoMedicamentoRepository prescricaoMedicamentoRepository;
@Autowired
private PrescricaoMedicamentoMapper prescricaoMedicamentoMapper;
@Autowired
private PrescricaoMedicamentoService prescricaoMedicamentoService;
/**
* This repository is mocked in the br.com.basis.madre.prescricao.repository.search test package.
*
* @see br.com.basis.madre.prescricao.repository.search.PrescricaoMedicamentoSearchRepositoryMockConfiguration
*/
@Autowired
private PrescricaoMedicamentoSearchRepository mockPrescricaoMedicamentoSearchRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restPrescricaoMedicamentoMockMvc;
private PrescricaoMedicamento prescricaoMedicamento;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
final PrescricaoMedicamentoResource prescricaoMedicamentoResource = new PrescricaoMedicamentoResource(prescricaoMedicamentoService);
this.restPrescricaoMedicamentoMockMvc = MockMvcBuilders.standaloneSetup(prescricaoMedicamentoResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static PrescricaoMedicamento createEntity(EntityManager em) {
PrescricaoMedicamento prescricaoMedicamento = (PrescricaoMedicamento) new PrescricaoMedicamento()
.idPaciente(DEFAULT_ID_PACIENTE)
.observacao(DEFAULT_OBSERVACAO);
return prescricaoMedicamento;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static PrescricaoMedicamento createUpdatedEntity(EntityManager em) {
PrescricaoMedicamento prescricaoMedicamento = (PrescricaoMedicamento) new PrescricaoMedicamento()
.idPaciente(UPDATED_ID_PACIENTE)
.observacao(UPDATED_OBSERVACAO);
return prescricaoMedicamento;
}
@BeforeEach
public void initTest() {
prescricaoMedicamento = createEntity(em);
}
@Test
@Transactional
public void createPrescricaoMedicamento() throws Exception {
int databaseSizeBeforeCreate = prescricaoMedicamentoRepository.findAll().size();
// Create the PrescricaoMedicamento
PrescricaoMedicamentoDTO prescricaoMedicamentoDTO = prescricaoMedicamentoMapper.toDto(prescricaoMedicamento);
restPrescricaoMedicamentoMockMvc.perform(post("/api/prescricao-medicamentos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(prescricaoMedicamentoDTO)))
.andExpect(status().isCreated());
// Validate the PrescricaoMedicamento in the database
List<PrescricaoMedicamento> prescricaoMedicamentoList = prescricaoMedicamentoRepository.findAll();
assertThat(prescricaoMedicamentoList).hasSize(databaseSizeBeforeCreate + 1);
PrescricaoMedicamento testPrescricaoMedicamento = prescricaoMedicamentoList.get(prescricaoMedicamentoList.size() - 1);
assertThat(testPrescricaoMedicamento.getIdPaciente()).isEqualTo(DEFAULT_ID_PACIENTE);
assertThat(testPrescricaoMedicamento.getObservacao()).isEqualTo(DEFAULT_OBSERVACAO);
// Validate the PrescricaoMedicamento in Elasticsearch
verify(mockPrescricaoMedicamentoSearchRepository, times(1)).save(testPrescricaoMedicamento);
}
@Test
@Transactional
public void createPrescricaoMedicamentoWithExistingId() throws Exception {
int databaseSizeBeforeCreate = prescricaoMedicamentoRepository.findAll().size();
// Create the PrescricaoMedicamento with an existing ID
prescricaoMedicamento.setId(1L);
PrescricaoMedicamentoDTO prescricaoMedicamentoDTO = prescricaoMedicamentoMapper.toDto(prescricaoMedicamento);
// An entity with an existing ID cannot be created, so this API call must fail
restPrescricaoMedicamentoMockMvc.perform(post("/api/prescricao-medicamentos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(prescricaoMedicamentoDTO)))
.andExpect(status().isBadRequest());
// Validate the PrescricaoMedicamento in the database
List<PrescricaoMedicamento> prescricaoMedicamentoList = prescricaoMedicamentoRepository.findAll();
assertThat(prescricaoMedicamentoList).hasSize(databaseSizeBeforeCreate);
// Validate the PrescricaoMedicamento in Elasticsearch
verify(mockPrescricaoMedicamentoSearchRepository, times(0)).save(prescricaoMedicamento);
}
@Test
@Transactional
public void getAllPrescricaoMedicamentos() throws Exception {
// Initialize the database
prescricaoMedicamentoRepository.saveAndFlush(prescricaoMedicamento);
// Get all the prescricaoMedicamentoList
restPrescricaoMedicamentoMockMvc.perform(get("/api/prescricao-medicamentos?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(prescricaoMedicamento.getId().intValue())))
.andExpect(jsonPath("$.[*].idPaciente").value(hasItem(DEFAULT_ID_PACIENTE.intValue())))
.andExpect(jsonPath("$.[*].observacao").value(hasItem(DEFAULT_OBSERVACAO)));
}
@Test
@Transactional
public void getPrescricaoMedicamento() throws Exception {
// Initialize the database
prescricaoMedicamentoRepository.saveAndFlush(prescricaoMedicamento);
// Get the prescricaoMedicamento
restPrescricaoMedicamentoMockMvc.perform(get("/api/prescricao-medicamentos/{id}", prescricaoMedicamento.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(prescricaoMedicamento.getId().intValue()))
.andExpect(jsonPath("$.idPaciente").value(DEFAULT_ID_PACIENTE.intValue()))
.andExpect(jsonPath("$.observacao").value(DEFAULT_OBSERVACAO));
}
@Test
@Transactional
public void getNonExistingPrescricaoMedicamento() throws Exception {
// Get the prescricaoMedicamento
restPrescricaoMedicamentoMockMvc.perform(get("/api/prescricao-medicamentos/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updatePrescricaoMedicamento() throws Exception {
// Initialize the database
prescricaoMedicamentoRepository.saveAndFlush(prescricaoMedicamento);
int databaseSizeBeforeUpdate = prescricaoMedicamentoRepository.findAll().size();
// Update the prescricaoMedicamento
PrescricaoMedicamento updatedPrescricaoMedicamento = prescricaoMedicamentoRepository.findById(prescricaoMedicamento.getId()).get();
// Disconnect from session so that the updates on updatedPrescricaoMedicamento are not directly saved in db
em.detach(updatedPrescricaoMedicamento);
updatedPrescricaoMedicamento
.idPaciente(UPDATED_ID_PACIENTE)
.observacao(UPDATED_OBSERVACAO);
PrescricaoMedicamentoDTO prescricaoMedicamentoDTO = prescricaoMedicamentoMapper.toDto(updatedPrescricaoMedicamento);
restPrescricaoMedicamentoMockMvc.perform(put("/api/prescricao-medicamentos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(prescricaoMedicamentoDTO)))
.andExpect(status().isOk());
// Validate the PrescricaoMedicamento in the database
List<PrescricaoMedicamento> prescricaoMedicamentoList = prescricaoMedicamentoRepository.findAll();
assertThat(prescricaoMedicamentoList).hasSize(databaseSizeBeforeUpdate);
PrescricaoMedicamento testPrescricaoMedicamento = prescricaoMedicamentoList.get(prescricaoMedicamentoList.size() - 1);
assertThat(testPrescricaoMedicamento.getIdPaciente()).isEqualTo(UPDATED_ID_PACIENTE);
assertThat(testPrescricaoMedicamento.getObservacao()).isEqualTo(UPDATED_OBSERVACAO);
// Validate the PrescricaoMedicamento in Elasticsearch
verify(mockPrescricaoMedicamentoSearchRepository, times(1)).save(testPrescricaoMedicamento);
}
@Test
@Transactional
public void updateNonExistingPrescricaoMedicamento() throws Exception {
int databaseSizeBeforeUpdate = prescricaoMedicamentoRepository.findAll().size();
// Create the PrescricaoMedicamento
PrescricaoMedicamentoDTO prescricaoMedicamentoDTO = prescricaoMedicamentoMapper.toDto(prescricaoMedicamento);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restPrescricaoMedicamentoMockMvc.perform(put("/api/prescricao-medicamentos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(prescricaoMedicamentoDTO)))
.andExpect(status().isBadRequest());
// Validate the PrescricaoMedicamento in the database
List<PrescricaoMedicamento> prescricaoMedicamentoList = prescricaoMedicamentoRepository.findAll();
assertThat(prescricaoMedicamentoList).hasSize(databaseSizeBeforeUpdate);
// Validate the PrescricaoMedicamento in Elasticsearch
verify(mockPrescricaoMedicamentoSearchRepository, times(0)).save(prescricaoMedicamento);
}
@Test
@Transactional
public void deletePrescricaoMedicamento() throws Exception {
// Initialize the database
prescricaoMedicamentoRepository.saveAndFlush(prescricaoMedicamento);
int databaseSizeBeforeDelete = prescricaoMedicamentoRepository.findAll().size();
// Delete the prescricaoMedicamento
restPrescricaoMedicamentoMockMvc.perform(delete("/api/prescricao-medicamentos/{id}", prescricaoMedicamento.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<PrescricaoMedicamento> prescricaoMedicamentoList = prescricaoMedicamentoRepository.findAll();
assertThat(prescricaoMedicamentoList).hasSize(databaseSizeBeforeDelete - 1);
// Validate the PrescricaoMedicamento in Elasticsearch
verify(mockPrescricaoMedicamentoSearchRepository, times(1)).deleteById(prescricaoMedicamento.getId());
}
@Test
@Transactional
public void searchPrescricaoMedicamento() throws Exception {
// Initialize the database
prescricaoMedicamentoRepository.saveAndFlush(prescricaoMedicamento);
when(mockPrescricaoMedicamentoSearchRepository.search(queryStringQuery("id:" + prescricaoMedicamento.getId()), PageRequest.of(0, 20)))
.thenReturn(new PageImpl<>(Collections.singletonList(prescricaoMedicamento), PageRequest.of(0, 1), 1));
// Search the prescricaoMedicamento
restPrescricaoMedicamentoMockMvc.perform(get("/api/_search/prescricao-medicamentos?query=id:" + prescricaoMedicamento.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(prescricaoMedicamento.getId().intValue())))
.andExpect(jsonPath("$.[*].idPaciente").value(hasItem(DEFAULT_ID_PACIENTE.intValue())))
.andExpect(jsonPath("$.[*].observacao").value(hasItem(DEFAULT_OBSERVACAO)));
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(PrescricaoMedicamento.class);
PrescricaoMedicamento prescricaoMedicamento1 = new PrescricaoMedicamento();
prescricaoMedicamento1.setId(1L);
PrescricaoMedicamento prescricaoMedicamento2 = new PrescricaoMedicamento();
prescricaoMedicamento2.setId(prescricaoMedicamento1.getId());
assertThat(prescricaoMedicamento1).isEqualTo(prescricaoMedicamento2);
prescricaoMedicamento2.setId(2L);
assertThat(prescricaoMedicamento1).isNotEqualTo(prescricaoMedicamento2);
prescricaoMedicamento1.setId(null);
assertThat(prescricaoMedicamento1).isNotEqualTo(prescricaoMedicamento2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(PrescricaoMedicamentoDTO.class);
PrescricaoMedicamentoDTO prescricaoMedicamentoDTO1 = new PrescricaoMedicamentoDTO();
prescricaoMedicamentoDTO1.setId(1L);
PrescricaoMedicamentoDTO prescricaoMedicamentoDTO2 = new PrescricaoMedicamentoDTO();
assertThat(prescricaoMedicamentoDTO1).isNotEqualTo(prescricaoMedicamentoDTO2);
prescricaoMedicamentoDTO2.setId(prescricaoMedicamentoDTO1.getId());
assertThat(prescricaoMedicamentoDTO1).isEqualTo(prescricaoMedicamentoDTO2);
prescricaoMedicamentoDTO2.setId(2L);
assertThat(prescricaoMedicamentoDTO1).isNotEqualTo(prescricaoMedicamentoDTO2);
prescricaoMedicamentoDTO1.setId(null);
assertThat(prescricaoMedicamentoDTO1).isNotEqualTo(prescricaoMedicamentoDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(prescricaoMedicamentoMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(prescricaoMedicamentoMapper.fromId(null)).isNull();
}
}
|
rafael-radkowski/setforge
|
src/MaterialRandomization.h
|
#pragma once
/**
Class MaterialRandomization
@brief - generate a random color.
The class generates a random color / material.
The material is generated as a HSV color model and picks a random hue and saturation.
The brightness either remains constant or can also change.
The values are converted to RGB values and returned as RGB.
For further information, see: https://docs.google.com/document/d/1xMMXdtCLFCR4rh1uQc7IpIVlAw9hsM409nWJOY54mX0
<NAME>
Iowa State University
<EMAIL>
Dec. 12, 2019
MIT License
-----------------------------------------------------------------------------------------------------
Last edited:
April 21, 2020, RR
- Fixed a bug that mixed up std::min and std::max with the min/max macros.
*/
// stl
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <random>
#include <time.h>
#include <iomanip>
class MaterialRandomization
{
public:
MaterialRandomization();
~MaterialRandomization();
/**
Set the hue value range.
@param min - a min value in the range from 0 to 1.
@param max - a max value in the range from 0 to 1.
Note that min must be smaller than max.
*/
void setHueRange(float min, float max);
/**
Set the saturation value range.
@param min - a min value in the range from 0 to 1.
@param max - a max value in the range from 0 to 1.
Note that min must be smaller than max.
*/
void setSaturationRange(float min, float max);
/**
Set the brightness value range.
@param min - a min value in the range from 0 to 1.
@param max - a max value in the range from 0 to 1.
Note that min must be smaller than max.
*/
void setBrightnessRange(float min, float max);
/**
The brightness is not randomized by default.
Enable brighness randomizaton
@param value true enables randomizatoin, default is false.
*/
void setRandomizeBrightness(bool value);
/**
Create a random color value and return it as RGB value;
*/
std::vector<float> getRGB(void);
private:
/*
Create a random color value
*/
void createRandomColor(void);
/*
@param - H(Hue): 0 - 360 degree (integer)
@param - S(Saturation): 0 - 1.00 (double)
@param - V(Value): 0 - 1.00 (double)
@return Output, array size 3, int
*/
std::vector<float> MaterialRandomization::HSVtoRGB(int H, double S, double V);
float _hue_min;
float _hue_max;
float _sat_min;
float _sat_max;
float _bright_min;
float _bright_max;
bool _randomize_brightness;
// the random color value
std::vector<float> _hsv_values;
bool _verbose;
std::random_device _rd;
};
|
malliina/pics
|
backend/src/main/scala/com/malliina/pics/ImageHandler.scala
|
<filename>backend/src/main/scala/com/malliina/pics/ImageHandler.scala
package com.malliina.pics
import java.nio.file.{Files, Path}
import cats.effect.IO
import com.sksamuel.scrimage.ImmutableImage
object ImageHandlerIO:
def apply(prefix: String, resizer: ImageResizerIO, storage: DataSourceIO) =
new ImageHandlerIO(prefix, resizer, storage)
class ImageHandlerIO(prefix: String, resizer: ImageResizerIO, val storage: DataSourceIO)
extends ImageService[IO]:
def createTempFile = IO(Files.createTempFile(prefix, null))
override def handle(original: Path, key: Key): IO[Path] =
IO(ImmutableImage.loader().fromPath(original)).flatMap { image =>
handleImage(image, key)
}
override def handleImage(image: ImmutableImage, key: Key) = createTempFile.flatMap { dest =>
resizer.resize(image, dest).flatMap { e =>
e.fold(err => IO.raiseError(err.ioe), _ => storage.saveBody(key, dest).map(_ => dest))
}
}
override def remove(key: Key): IO[PicResult] = storage.remove(key)
trait ImageHandlerLike[F[_]]:
def handleImage(image: ImmutableImage, key: Key): F[Path]
def remove(key: Key): F[PicResult]
trait ImageService[F[_]] extends ImageHandlerLike[F]:
/** Might fail with Exception, ImageParseException, IllegalArgumentException, ...
*
* @param original
* orig image
* @param key
* desired key
* @return
*/
def handle(original: Path, key: Key): F[Path]
|
cysec-platform/coach-standard-language
|
src/main/java/eu/smesec/cysec/csl/parser/CommandIsSelected.java
|
/*-
* #%L
* CYSEC Standard Coach Language
* %%
* Copyright (C) 2020 - 2022 FHNW (University of Applied Sciences and Arts Northwestern Switzerland)
* %%
* 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.
* #L%
*/
package eu.smesec.cysec.csl.parser;
import eu.smesec.cysec.platform.bridge.execptions.CacheException;
import eu.smesec.cysec.platform.bridge.generated.Answer;
import java.util.List;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CommandIsSelected extends Command {
public Atom execute(List<Atom> aList, CoachContext coachContext) throws ExecutorException {
// expects 3 parameters: name, context of var and value
if (aList.size() != 1) {
throw new ExecutorException("Invalid number of arguments. Expected 1 parameter.");
}
// evaluate parameters
Atom varContent = aList.get(0).execute(coachContext);
// assert type of parameters
if (varContent.getType() != Atom.AtomType.STRING) {
throw new ExecutorException("Invalid types for parameters: Provide [0] String");
}
Answer answer = null;
try {
// v
//q110oNone
// split id of "company-q10o4" to "q10o4"
//Problem: question id might contain "o" thus splitting into more than 2 parts!
String regex = "[^0-9]*[q]\\d+";
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(varContent.getId());
if(match.find()) {
String questionId = varContent.getId().substring(match.start(), match.end());
// disassemble option into question and option by splitting with "o": q10o1
answer = coachContext.getCal().getAnswer(coachContext.getFqcn().toString(), questionId);
} else throw new ExecutorException("question id doesn't match pattern [^0-9]*[q]\\d+");
} catch (CacheException e) {
coachContext.getLogger().log(Level.SEVERE, String.format("Error loading answer %s", varContent.getId()));
}
// determine provided option is selected
String boolResult;
if(answer != null) {
if(answer.getAidList() == null) {
if(answer.getText().equals(varContent.getId())) {
boolResult = "TRUE";
} else {
boolResult = "FALSE";
}
coachContext.getLogger().info(String.format("isSelected(%s) == %s is: %s", varContent.getId(), answer.getText(), boolResult));
} else {
// Attention: Order matters
if(answer.getAidList().contains(varContent.getId())) {
boolResult = "TRUE";
} else {
boolResult = "FALSE";
}
coachContext.getLogger().info(String.format("isSelected(%s) == %s is: %s", varContent.getId(), answer.getAidList(), boolResult));
}
} else {
boolResult = "FALSE";
coachContext.getLogger().info(String.format("isSelected(%s) == null is: %s", varContent.getId(), boolResult));
}
return new Atom(Atom.AtomType.BOOL, boolResult, null);
}
}
|
beanz/advent
|
2015/11/main.go
|
<filename>2015/11/main.go
package main
import (
_ "embed"
"fmt"
. "github.com/beanz/advent/lib-go"
)
//go:embed input.txt
var input []byte
func Valid(pw string) bool {
seen := make(map[string]bool, len(pw)/2)
hasStraight := false
hasBad := false
numPairs := 0
for i := 0; i < len(pw); i++ {
if pw[i] == 'i' || pw[i] == 'o' || pw[i] == 'l' {
hasBad = true
break
}
if i == len(pw)-1 {
continue
}
if pw[i] == pw[i+1] && !seen[""+string(pw[i:i+2])] {
seen[""+string(pw[i:i+2])] = true
numPairs++
}
if i == len(pw)-2 || hasStraight {
continue
}
if pw[i] == pw[i+1]-1 && pw[i] == pw[i+2]-2 {
hasStraight = true
}
}
return hasStraight && !hasBad && numPairs >= 2
}
func Next(cur string) string {
pw := NewPerlyString(cur)
pw.Inc()
for ; !Valid(pw.String()); pw.Inc() {
}
return pw.String()
}
func main() {
in := InputLines(input)
p1 := Next(in[0])
if !benchmark {
fmt.Printf("Part 1: %s\n", p1)
}
p2 := Next(p1)
if !benchmark {
fmt.Printf("Part 2: %s\n", p2)
}
}
var benchmark bool
|
Glavo/kala-common
|
kala-base/src/main/java/kala/control/OptionContainer.java
|
<filename>kala-base/src/main/java/kala/control/OptionContainer.java
package kala.control;
import kala.collection.base.Iterators;
import kala.collection.base.Traversable;
import kala.collection.base.Mappable;
import kala.annotations.Covariant;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.*;
import java.util.function.Consumer;
import java.util.stream.Collector;
import java.util.stream.Stream;
/**
* A container object which may or may not contain a value.
*
* @param <T> the type of value
* @author Glavo
*/
public interface OptionContainer<@Covariant T> extends Iterable<T>, Mappable<T>, Traversable<T> {
/**
* Returns {@code true} if the container contain a value, otherwise return {@code false}.
*
* @return {@code true} if the container contain a value, otherwise {@code false}
*/
boolean isDefined();
/**
* Returns {@code true} if the container is empty, otherwise return {@code false}.
*
* @return {@code true} if the container is empty, otherwise {@code false}
*/
default boolean isEmpty() {
return !isDefined();
}
default @NotNull Stream<T> stream() {
return isDefined() ? Stream.of(get()) : Stream.empty();
}
default @NotNull Stream<T> parallelStream() {
return stream().parallel();
}
/**
* {@inheritDoc}
*/
@Override
default @NotNull Iterator<T> iterator() {
return isDefined() ? Iterators.of(get()) : Iterators.empty();
}
/**
* {@inheritDoc}
*/
@Override
default int size() {
return isDefined() ? 1 : 0;
}
/**
* Returns the value of the container.
*
* @return the value of the container
* @throws NoSuchElementException if the container is empty
*/
T get();
/**
* Returns the value of the container if it is not empty, otherwise return the {@code null}.
*
* @return the value of the container if the container {@link #isDefined()},
* or the {@code null} if the container {@link #isEmpty()}
*/
default @Nullable T getOrNull() {
return isDefined() ? get() : null;
}
/**
* Returns {@code Option.some(get())} if it is not empty, otherwise return the {@code Option.none()}.
*
* @return {@code Option.some(get())} if the container {@link #isDefined()},
* or the {@code Option.none()} if the container {@link #isEmpty()}
*/
default @NotNull Option<T> getOption() {
return isDefined() ? Option.some(get()) : Option.none();
}
/**
* Returns the value of the container if it is not empty, otherwise return the {@code defaultValue}.
*
* @param defaultValue the default value
* @return the value of the container if the container {@link #isDefined()},
* or the {@code defaultValue} if the container {@link #isEmpty()}
*/
default T getOrDefault(T defaultValue) {
return isDefined() ? get() : defaultValue;
}
default T getOrElse(@NotNull Supplier<? extends T> supplier) {
return isDefined() ? get() : supplier.get();
}
/**
* Returns the value of the container if it is not empty, otherwise throw the {@code exception}.
*
* @return the value of the container if the container {@link #isDefined()}
* @throws Ex if no value is present
*/
default <Ex extends Throwable> T getOrThrowException(@NotNull Ex exception) throws Ex {
if (isEmpty()) {
Objects.requireNonNull(exception);
throw exception;
}
return get();
}
/**
* Returns the value of the container if it is not empty, otherwise throw {@code supplier.get()}.
*
* @return the value of the container if the container {@link #isDefined()}
* @throws Ex if no value is present
*/
default <Ex extends Throwable> T getOrThrow(@NotNull Supplier<? extends Ex> supplier) throws Ex {
if (isEmpty()) {
Objects.requireNonNull(supplier);
throw supplier.get();
}
return get();
}
/**
* Returns {@code Option.some(get())} if it is not empty, otherwise return the {@code Option.none()}.
*
* @return {@code Option.some(get())} if the container {@link #isDefined()},
* or the {@code Option.none()} if the container {@link #isEmpty()}
*/
default @NotNull Option<T> toOption() {
return getOption();
}
@SuppressWarnings("unchecked")
default <R, Builder> R collect(@NotNull Collector<? super T, Builder, ? extends R> factory) {
final Collector<T, Object, R> f = ((Collector<T, Object, R>) factory);
Object builder = f.supplier().get();
if (isDefined()) {
f.accumulator().accept(builder, get());
}
return f.finisher().apply(builder);
}
@Override
<U> @NotNull OptionContainer<U> map(@NotNull Function<? super T, ? extends U> mapper);
/**
* {@inheritDoc}
*/
@Override
@Contract(pure = true)
default int count(@NotNull Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
return anyMatch(predicate) ? 1 : 0;
}
/**
* {@inheritDoc}
*/
@Override
default <U> U foldLeft(U zero, @NotNull BiFunction<? super U, ? super T, ? extends U> op) {
if (isEmpty()) {
return zero;
}
return op.apply(zero, get());
}
/**
* {@inheritDoc}
*/
@Override
@Contract(pure = true)
default <U> U foldRight(U zero, @NotNull BiFunction<? super T, ? super U, ? extends U> op) {
if (isEmpty()) {
return zero;
}
return op.apply(get(), zero);
}
/**
* {@inheritDoc}
*/
@Override
default T reduceLeft(@NotNull BiFunction<? super T, ? super T, ? extends T> op) {
if (isEmpty()) {
throw new NoSuchElementException();
}
return get();
}
/**
* {@inheritDoc}
*/
@Override
default T reduceRight(@NotNull BiFunction<? super T, ? super T, ? extends T> op) {
if (isEmpty()) {
throw new NoSuchElementException();
}
return get();
}
/**
* {@inheritDoc}
*/
@Override
@Contract(pure = true)
default @NotNull Option<T> reduceLeftOption(@NotNull BiFunction<? super T, ? super T, ? extends T> op) {
return getOption();
}
/**
* {@inheritDoc}
*/
@Override
@Contract(pure = true)
default @NotNull Option<T> reduceRightOption(@NotNull BiFunction<? super T, ? super T, ? extends T> op) {
return getOption();
}
/**
* {@inheritDoc}
*/
@Override
@Contract(pure = true)
default boolean anyMatch(@NotNull Predicate<? super T> predicate) {
return isDefined() && predicate.test(get());
}
/**
* {@inheritDoc}
*/
@Override
@Contract(pure = true)
default boolean allMatch(@NotNull Predicate<? super T> predicate) {
return isEmpty() || predicate.test(get());
}
/**
* {@inheritDoc}
*/
@Override
@Contract(pure = true)
default boolean noneMatch(@NotNull Predicate<? super T> predicate) {
return isEmpty() || !predicate.test(get());
}
/**
* {@inheritDoc}
*/
@Override
default boolean contains(Object value) {
return isDefined() && Objects.equals(value, get());
}
/**
* {@inheritDoc}
*/
@Override
@NotNull
default Option<T> find(@NotNull Predicate<? super T> predicate) {
return isDefined() && predicate.test(get()) // implicit null check of predicate
? Option.some(get())
: Option.none();
}
/**
* {@inheritDoc}
*/
@Override
default void forEach(@NotNull Consumer<? super T> action) {
Objects.requireNonNull(action);
if (isDefined()) {
action.accept(get());
}
}
}
|
Moccine/Symfony-Projet-1
|
web/libariries/bootstrap/node_modules/grunt-legacy-util/node_modules/lodash/fp/conforms.js
|
module.exports = require('../conforms');
|
alparslansari/algorithm
|
src/leetcode/problems/linkedin/_261GraphValidTree.java
|
package leetcode.problems.linkedin;
import java.util.*;
/** 261. Graph Valid Tree
* You have a graph of n nodes labeled from 0 to n - 1.
* You are given an integer n and a list of edges where edges[i] = [ai, bi]
* indicates that there is an undirected edge between nodes ai and bi in the graph.
*
* Return true if the edges of the given graph make up a valid tree, and false otherwise.
*
* Example 1:
* Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
* Output: true
*
* Example 2:
* Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
* Output: false
*
* Constraints:
* 1 <= n <= 2000
* 0 <= edges.length <= 5000
* edges[i].length == 2
* 0 <= ai, bi < n
* ai != bi
* There are no self-loops or repeated edges.
*/
public class _261GraphValidTree {
public boolean validTree(int n, int[][] edges) {
List<List<Integer>> adjacencyList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adjacencyList.add(new ArrayList<>());
}
for (int[] edge : edges) {
adjacencyList.get(edge[0]).add(edge[1]);
adjacencyList.get(edge[1]).add(edge[0]);
}
Map<Integer, Integer> parent = new HashMap<>();
parent.put(0, -1);
Stack<Integer> stack = new Stack<>();
stack.push(0);
while (!stack.isEmpty()) {
int node = stack.pop();
for (int neighbour : adjacencyList.get(node)) {
if (parent.get(node) == neighbour) {
continue;
}
if (parent.containsKey(neighbour)) {
return false;
}
stack.push(neighbour);
parent.put(neighbour, node);
}
}
return parent.size() == n;
}
/**********************************************************************/
// https://leetcode.com/problems/graph-valid-tree/solution/
class Solution {
private List<List<Integer>> adjacencyList = new ArrayList<>();
private Set<Integer> seen = new HashSet<>();
public boolean validTree(int n, int[][] edges) {
if (edges.length != n - 1) return false;
// Make the adjacency list.
for (int i = 0; i < n; i++) {
adjacencyList.add(new ArrayList<>());
}
for (int[] edge : edges) {
adjacencyList.get(edge[0]).add(edge[1]);
adjacencyList.get(edge[1]).add(edge[0]);
}
// Carry out depth first search.
dfs(0);
// Inspect result and return the verdict.
return seen.size() == n;
}
public void dfs(int node) {
if (seen.contains(node)) return;
seen.add(node);
for (int neighbour : adjacencyList.get(node)) {
dfs(neighbour);
}
}
}
}
|
metaword/oasystem
|
src/main/java/com/aifurion/oasystem/service/DeptService.java
|
package com.aifurion.oasystem.service;
import com.aifurion.oasystem.entity.user.Dept;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import java.util.List;
/**
* @author :zzy
* @description:TODO
* @date :2021/1/19 14:19
*/
public interface DeptService {
Dept findOne(Long id);
List<Dept> findAll();
void deptManage(Model model);
boolean addDept(Dept dept, String xg, BindingResult br, Model model);
void changeDept(Long deptId, Model model);
void readDept(Long deptId, Model model);
void depTanDpositionChange(Long positionid, Long changedeptid, Long userid, Long deptid, Model model);
void deletDept(Long deletedeptid);
void deptManageChange(Long positionid, Long changedeptid, Long oldmanageid, Long newmanageid, Long deptid, Model model);
}
|
sharkprince/tank-game
|
src/main.cpp
|
#include "core/game.h"
int main() {
try {
Game* g = new Game();
g->Start();
} catch (...) {
return 1;
}
return 0;
}
|
fabriziobertoglio1987/sprachspiel
|
db/migrate/20170608080207_remove_and_add__fields_from_sales.rb
|
<reponame>fabriziobertoglio1987/sprachspiel
class RemoveAndAddFieldsFromSales < ActiveRecord::Migration[5.0]
def change
remove_column :sales, :user_id, :integer
add_column :sales, :room_id, :integer
end
end
|
heltonricardo/estudo-java
|
fundamentos/ConversaoNumeroString.java
|
package fundamentos;
public class ConversaoNumeroString {
public static void main(String[] args) {
Integer n = 10000;
System.out.println(n.toString().length());
int m = 123456;
System.out.println(Integer.toString(m).length());
}
}
|
IHTSDO/snow-owl
|
dependencies/org.eclipse.emf.cdo.common/src/org/eclipse/emf/cdo/common/revision/CDORevisionProvider.java
|
/*
* Copyright (c) 2004 - 2012 <NAME> (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* <NAME> - initial API and implementation
*/
package org.eclipse.emf.cdo.common.revision;
import org.eclipse.emf.cdo.common.branch.CDOBranchPoint;
import org.eclipse.emf.cdo.common.id.CDOID;
/**
* Provides consumers with the {@link CDORevision revisions} of {@link CDOID identifiable} CDO objects by selecting a
* particular one from several possible {@link CDOBranchPoint branch points}.
*
* @author <NAME>
* @since 3.0
* @apiviz.uses {@link CDORevision} - - provides
*/
public interface CDORevisionProvider
{
public CDORevision getRevision(CDOID id);
}
|
st3107/pdffitx
|
pdffitx/modeling/adding.py
|
<filename>pdffitx/modeling/adding.py
"""Add variables to recipe."""
import typing as tp
from diffpy.srfit.pdf import PDFGenerator, DebyePDFGenerator
from pdffitx.modeling.core import MyRecipe, MyContribution
G = tp.Union[PDFGenerator, DebyePDFGenerator]
def initialize(
recipe: MyRecipe,
scale: bool = True,
delta: tp.Union[str, None] = "2",
lat: tp.Union[str, None] = "s",
adp: tp.Union[str, None] = "a",
xyz: tp.Union[str, None] = "s",
params: tp.Union[None, str, tp.List[str]] = "a"
) -> MyRecipe:
"""Initialize a single-contribution recipe with the variables.
The variables will be constrained, created and added according to the mode indicated by the arguments. If an
argument is None, nothing will be done. It is assumed that the recipe only has one contribution and all
variables in the generators in that contribution will be initialized in the same way. To constrain specific
contribution and generator, please use `~pdfstream.modeling.adding.add_con_vars` and
`~pdfstream.modeling.adding.add_gen_vars`.
The name for each parameter follows the rule of "{generator or function name}_{variable name}". For the
B-factors and coordinates variables, the variable name follows the rule
"{atom name or element name}_{Biso, B11, B22, B33, x, y, z}".
Each parameter in generator is tagged by three tags: the catagory of the paramter ("scale", "delta",
"lat", "adp", "xyz"), the name of the generator (e. g. "G0") and their union (e. g. "G0_lat"). Each parameter
in the contribution is tagged by the name of its function if the parameter is named by
"{function name}_{...}".
Parameters
----------
recipe :
A recipe with a single contribution and generators.
scale :
Whether to add the scale of the generator. Default True.
delta :
If "1", add delta1 parameter.
If "2", add delta2 parameter.
If None, do nothing.
lat :
If "s", constrain the lattice parameters by space group and add the independent variables.
If "a", add all the lattice paramters.
If None, do nothing.
Default "s".
adp :
If "a", add all the Biso parameter.
If the structure is `~pyobjcryst.crystal.Crystal`, this step means add all the Biso of unique atoms.
If "e", constrain the Biso by elements, add the independent Biso.
If "s", constrain the B-tensor by space group, add all the independent diagonal terms like B11, B22, B33
or Biso.
If None, do nothing.
Default "a".
xyz :
If "s", constrain the coordinates of atoms by space group and add independent coordinates.
If "a", add all coordinates of atoms.
If None, do nothing.
Default "s".
params :
If "a", add all the parameters in the equation and characteristic functions like "psize".
If list of str, add all the parameters whose names are in the list.
If None, do nothing.
Default "a".
Returns
-------
recipe :
The initialized recipe. The operation is done inplace so the recipe is the same as the input.
"""
add_con_vars(recipe, params=params)
add_gen_vars(recipe, scale=scale, delta=delta, lat=lat, adp=adp, xyz=xyz)
return recipe
def add_con_vars(
recipe: MyRecipe,
name: tp.Union[str, None] = None,
params: tp.Union[None, str, tp.List[str]] = "a"
):
"""Add variables at contribution level.
The name is the name of the contribution. If None, all the contribution will be searched and added.
"""
if not name:
for con_name in recipe.contributions.keys():
add_con_vars(recipe, con_name, params)
return
con = recipe.contributions[name]
add_params(recipe, con, params)
return
def add_params(recipe: MyRecipe, con: MyContribution, params: tp.Union[None, str, tp.List[str]]) -> None:
"""Add contribution-level parameters in the contribution."""
if not params:
return
args = {
arg.name: arg
for eq in con.eqfactory.equations
if eq.name == "eq"
for arg in eq.args
if arg.name != con.xname
}
if params == "a":
pars = args.values()
else:
pars = [args[p] for p in params]
for par in pars:
recipe.addVar(par, tag=par.name.split("_")[0])
return
def add_gen_vars(
recipe: MyRecipe,
names: tp.Tuple[str, str] = None,
scale: bool = True,
delta: tp.Union[str, None] = "2",
lat: tp.Union[str, None] = "s",
adp: tp.Union[str, None] = "a",
xyz: tp.Union[str, None] = "s",
) -> None:
"""Add parameters at generator level.
The names are (contribution name, generator name). If None, all generators will be constrained and added.
"""
if not names:
for con_name, con in recipe.contributions.items():
for gen_name in con.generators.keys():
add_gen_vars(
recipe, names=(con_name, gen_name), scale=scale, delta=delta, lat=lat, adp=adp, xyz=xyz
)
return
gen = recipe.contributions[names[0]].generators[names[1]]
add_scale(recipe, gen, scale)
add_delta(recipe, gen, delta)
add_lat(recipe, gen, lat)
add_adp(recipe, gen, adp)
add_xyz(recipe, gen, xyz)
return
def add_scale(recipe: MyRecipe, gen: G, scale: bool = True) -> None:
"""Add the scale of the generator."""
if not scale:
return
recipe.addVar(
gen.scale,
value=0.,
name="{}_scale".format(gen.name),
tags=["{}_scale".format(gen.name), "scale", gen.name]
).boundRange(
lb=0.
)
return
def add_delta(recipe: MyRecipe, gen: G, delta: tp.Union[str, None]) -> None:
"""Add the delta parameter of the generator."""
if not delta:
return
if delta == "1":
par = gen.delta1
elif delta == "2":
par = gen.delta2
else:
raise ValueError("Unknown delta: {}. Allowed: delta1, delta2.".format(delta))
recipe.addVar(
par,
value=0.,
name="{}_{}".format(gen.name, par.name),
tags=["{}_delta".format(gen.name), "delta", gen.name]
).boundRange(
lb=0.
)
return
def add_lat(recipe: MyRecipe, gen: G, lat: tp.Union[str, None]) -> None:
"""Add the lattice parameters of the phase."""
if not lat:
return
if lat == "s":
pars = gen.phase.sgpars.latpars
elif lat == "a":
pars = gen.phase.getLattice()
else:
raise ValueError("Unknown lat: {}. Allowed: sg, all.".format(lat))
for par in pars:
recipe.addVar(
par,
name="{}_{}".format(gen.name, par.name),
tags=["lat", gen.name, "{}_lat".format(gen.name)]
).boundRange(
lb=0.
)
return
def add_adp(
recipe: MyRecipe, gen: G, adp: tp.Union[str, None],
symbols: tp.Tuple[str] = ("Biso", "B11", "B22", "B33")
) -> None:
"""Add the atomic displacement parameter of the phase."""
if not adp:
return
atoms = gen.phase.getScatterers()
if adp == "e":
elements = set((atom.element for atom in atoms))
dct = dict()
for element in elements:
dct[element] = recipe.newVar(
"{}_{}_Biso".format(gen.name, bleach(element)),
value=0.05,
tags=["adp", gen.name, "{}_adp".format(gen.name)]
)
for atom in atoms:
recipe.constrain(atom.Biso, dct[atom.element])
return
if adp == "a":
pars = [atom.Biso for atom in atoms]
names = ["{}_Biso".format(bleach(atom.name)) for atom in atoms]
elif adp == "s":
pars = gen.phase.sgpars.adppars
names = [
rename_by_atom(par.name, atoms) for par in pars
if par.name.split("_")[0] in symbols
]
else:
raise ValueError("Unknown adp: {}. Allowed: element, sg, all.".format(adp))
for par, name in zip(pars, names):
recipe.addVar(
par,
name="{}_{}".format(gen.name, name),
value=par.value if par.value != 0. else 0.05,
tags=["adp", gen.name, "{}_adp".format(gen.name)]
).boundRange(
lb=0.
)
return
def add_xyz(recipe: MyRecipe, gen: G, xyz: tp.Union[str, None]) -> None:
"""Add the coordinates of the atoms in the phase."""
if not xyz:
return
atoms = gen.phase.getScatterers()
if xyz == "s":
pars = gen.phase.sgpars.xyzpars
names = [rename_by_atom(par.name, atoms) for par in pars]
elif xyz == "a":
pars, names = list(), list()
for atom in atoms:
pars.append(atom.x)
names.append("{}_x".format(atom.name))
pars.append(atom.y)
names.append("{}_y".format(atom.name))
pars.append(atom.z)
names.append("{}_z".format(atom.name))
else:
raise ValueError("Unknown xyz: {}. Allowed: s, a.".format(xyz))
for par, name in zip(pars, names):
recipe.addVar(
par,
name="{}_{}".format(gen.name, name),
tags=["xyz", gen.name, "{}_xyz".format(gen.name)]
)
return
def rename_by_atom(name: str, atoms: list) -> str:
"""Rename of the name of a parameter by replacing the index of the atom in the name by the label of
the atom and revert the order of coordinates and atom name.
Used for the space group constrained parameters. For example, "x_0" where atom index 0 is Ni will become
"Ni0_x" after renamed. If the name can not renamed, return the original name.
"""
parts = name.split("_")
if len(parts) > 1 and parts[1].isdigit() and -1 < int(parts[1]) < len(atoms):
parts[1] = atoms[int(parts[1])].name
parts = parts[::-1]
return "_".join(parts)
def bleach(s: str):
"""Bleach the string of the atom names and element names.
Replace '+' with 'p', '-' with 'n'. Strip all the characters except the number and letters.
"""
return ''.replace("+", "p").replace("-", "n").join((c for c in s if c.isalnum()))
|
he-guang-wen/water-ui
|
src/components/water-ui/components/progress/index.js
|
import WrProgress from './src/progress.vue'
WrProgress.install = function(Vue){
Vue.component(WrProgress.name,WrProgress)
}
export default WrProgress
|
kayler-renslow/arma-intellij-plugin
|
src/com/kaylerrenslow/armaplugin/ArmaAddonIndexingHandle.java
|
<reponame>kayler-renslow/arma-intellij-plugin
package com.kaylerrenslow.armaplugin;
import org.jetbrains.annotations.NotNull;
import java.io.File;
/**
* @author Kayler
* @see ArmaAddonsIndexingCallback
* @see ArmaAddonsManager#loadAddonsAsync(ArmaAddonsProjectConfig, File, ArmaAddonsIndexingCallback)
* @since 10/26/2017
*/
public interface ArmaAddonIndexingHandle {
/**
* Invoke this method to cancel the indexing for the addon
*/
void cancel();
/**
* @return true if {@link #cancel()} was invoked
*/
boolean isCancelled();
/**
* @return the total indexing progress for the addon (ranged 0.0 - 1.0)
*/
double getCurrentWorkProgress();
/**
* @return the progress for current indexing work the addon (ranged 0.0 - 1.0)
*/
double getTotalWorkProgress();
/**
* @return the addon/mod's name (the @ prefixed name to be specific)
*/
@NotNull
String getAddonName();
}
|
stella/stella
|
try/34_testrun_try.rb
|
require 'stella'
#Stella.debug = true
Stella.load! :tryouts
Stella::Testrun.destroy! :runid => 'tryoutsrun34'
Stella::Testplan.destroy! :planid => 'tryoutsplan34'
@cust = Stella::Customer.first_or_create :custid => :tryouts_34, :email => '<EMAIL>'
@host = Stella::Host.first_or_create :customer => @cust, :hostname => '34stellaaahhhh.com'
@plan = Stella::Testplan.create :planid => 'tryoutsplan34', :definition => { :tryouts => true }, :host => @host
## Create
run = Stella::Testrun.new :runid => 'tryoutsrun34', :testplan => @plan, :customer => @cust, :host => @host
run.data = {
'concurrency' => 2,
'repetitions' => 1,
'anyoloption' => 'textual'
}
begin
run.save
rescue DataMapper::PersistenceError => ex
puts ex.message, ex.resource
ex.resource.errors.each { |e| puts e }
nil
end
#=> true
## Can change status
run = Stella::Testrun.first :runid => 'tryoutsrun34'
run.status = :done
run.save
run = Stella::Testrun.first :runid => 'tryoutsrun34'
run.status
#=> :done
## Can't change to unknown status
run = Stella::Testrun.first :runid => 'tryoutsrun34'
run.status = :poop
begin
run.save
rescue DataMapper::SaveFailureError => ex
:success
end
#=> :success
## Find
run = Stella::Testrun.first :runid => 'tryoutsrun34'
[run.data['concurrency'], run.data['repetitions'], run.data['anyoloption']]
#=> [2, 1, 'textual']
## Find w/ testplan
run = Stella::Testrun.first :runid => 'tryoutsrun34'
run.testplan.saved?
#=> true
## Delete
run = Stella::Testrun.first :runid => 'tryoutsrun34'
run.destroy
#=> true
## runids are always unique
runs = []
1000.times { run = Stella::Testrun.new(:customer => @cust); run.normalize; runs << run }
runs.collect(&:runid).uniq.size
#=> 1000
@plan.destroy!
@host.destroy!
@cust.destroy!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.