code
stringlengths
4
1.01M
language
stringclasses
2 values
package org.ocbc.utils; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; public class request { public static JSONObject get(String url, HashMap<String, String> headers) { BufferedReader in = null; StringBuffer response = null; try { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); for (String key : headers.keySet()) { con.setRequestProperty(key, headers.get(key)); } in = new BufferedReader(new InputStreamReader(con.getInputStream())); response = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch(Exception exception) { System.out.println(exception); return null; } return new JSONObject(response.toString()); } }
Java
/* * Mounts a BitLocker Drive Encrypted (BDE) volume * * Copyright (C) 2011-2015, Joachim Metz <joachim.metz@gmail.com> * * Refer to AUTHORS for acknowledgements. * * This software is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This software 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 Lesser General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ #include <common.h> #include <memory.h> #include <types.h> #include <stdio.h> #if defined( HAVE_ERRNO_H ) #include <errno.h> #endif #if defined( HAVE_UNISTD_H ) #include <unistd.h> #endif #if defined( HAVE_STDLIB_H ) || defined( WINAPI ) #include <stdlib.h> #endif #if !defined( WINAPI ) || defined( USE_CRT_FUNCTIONS ) #if defined( TIME_WITH_SYS_TIME ) #include <sys/time.h> #include <time.h> #elif defined( HAVE_SYS_TIME_H ) #include <sys/time.h> #else #include <time.h> #endif #endif #if defined( HAVE_LIBFUSE ) || defined( HAVE_LIBOSXFUSE ) #define FUSE_USE_VERSION 26 #if defined( HAVE_LIBFUSE ) #include <fuse.h> #elif defined( HAVE_LIBOSXFUSE ) #include <osxfuse/fuse.h> #endif #elif defined( HAVE_LIBDOKAN ) #include <dokan.h> #endif #include "bdeoutput.h" #include "bdetools_libbde.h" #include "bdetools_libcerror.h" #include "bdetools_libclocale.h" #include "bdetools_libcnotify.h" #include "bdetools_libcstring.h" #include "bdetools_libcsystem.h" #include "mount_handle.h" mount_handle_t *bdemount_mount_handle = NULL; int bdemount_abort = 0; /* Prints the executable usage information */ void usage_fprint( FILE *stream ) { if( stream == NULL ) { return; } fprintf( stream, "Use bdemount to mount a BitLocker Drive Encrypted (BDE) volume\n\n" ); fprintf( stream, "Usage: bdemount [ -k keys ] [ -o offset ] [ -p password ]\n" " [ -r password ] [ -s filename ] [ -X extended_options ]\n" " [ -hvV ] source mount_point\n\n" ); fprintf( stream, "\tsource: the source file or device\n" ); fprintf( stream, "\tmount_point: the directory to serve as mount point\n\n" ); fprintf( stream, "\t-h: shows this help\n" ); fprintf( stream, "\t-k: the full volume encryption key and tweak key\n" "\t formatted in base16 and separated by a : character\n" "\t e.g. FKEV:TWEAK\n" ); fprintf( stream, "\t-o: specify the volume offset in bytes\n" ); fprintf( stream, "\t-p: specify the password/passphrase\n" ); fprintf( stream, "\t-r: specify the recovery password\n" ); fprintf( stream, "\t-s: specify the file containing the startup key.\n" "\t typically this file has the extension .BEK\n" ); fprintf( stream, "\t-v: verbose output to stderr\n" "\t bdemount will remain running in the foreground\n" ); fprintf( stream, "\t-V: print version\n" ); fprintf( stream, "\t-X: extended options to pass to sub system\n" ); } /* Signal handler for bdemount */ void bdemount_signal_handler( libcsystem_signal_t signal LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_signal_handler"; LIBCSYSTEM_UNREFERENCED_PARAMETER( signal ) bdemount_abort = 1; if( bdemount_mount_handle != NULL ) { if( mount_handle_signal_abort( bdemount_mount_handle, &error ) != 1 ) { libcnotify_printf( "%s: unable to signal mount handle to abort.\n", function ); libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } } /* Force stdin to close otherwise any function reading it will remain blocked */ if( libcsystem_file_io_close( 0 ) != 0 ) { libcnotify_printf( "%s: unable to close stdin.\n", function ); } } #if defined( HAVE_LIBFUSE ) || defined( HAVE_LIBOSXFUSE ) #if ( SIZEOF_OFF_T != 8 ) && ( SIZEOF_OFF_T != 4 ) #error Size of off_t not supported #endif static char *bdemount_fuse_path = "/bde1"; static size_t bdemount_fuse_path_length = 5; #if defined( HAVE_TIME ) time_t bdemount_timestamp = 0; #endif /* Opens a file * Returns 0 if successful or a negative errno value otherwise */ int bdemount_fuse_open( const char *path, struct fuse_file_info *file_info ) { libcerror_error_t *error = NULL; static char *function = "bdemount_fuse_open"; size_t path_length = 0; int result = 0; if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -EINVAL; goto on_error; } if( file_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file info.", function ); result = -EINVAL; goto on_error; } path_length = libcstring_narrow_string_length( path ); if( ( path_length != bdemount_fuse_path_length ) || ( libcstring_narrow_string_compare( path, bdemount_fuse_path, bdemount_fuse_path_length ) != 0 ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path.", function ); result = -ENOENT; goto on_error; } if( ( file_info->flags & 0x03 ) != O_RDONLY ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_UNSUPPORTED_VALUE, "%s: write access currently not supported.", function ); result = -EACCES; goto on_error; } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Reads a buffer of data at the specified offset * Returns number of bytes read if successful or a negative errno value otherwise */ int bdemount_fuse_read( const char *path, char *buffer, size_t size, off_t offset, struct fuse_file_info *file_info ) { libcerror_error_t *error = NULL; static char *function = "bdemount_fuse_read"; size_t path_length = 0; ssize_t read_count = 0; int result = 0; if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -EINVAL; goto on_error; } if( size > (size_t) INT_MAX ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid size value exceeds maximum.", function ); result = -EINVAL; goto on_error; } if( file_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file info.", function ); result = -EINVAL; goto on_error; } path_length = libcstring_narrow_string_length( path ); if( ( path_length != bdemount_fuse_path_length ) || ( libcstring_narrow_string_compare( path, bdemount_fuse_path, bdemount_fuse_path_length ) != 0 ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path.", function ); result = -ENOENT; goto on_error; } if( mount_handle_seek_offset( bdemount_mount_handle, (off64_t) offset, SEEK_SET, &error ) == -1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_SEEK_FAILED, "%s: unable to seek offset in mount handle.", function ); result = -EIO; goto on_error; } read_count = mount_handle_read_buffer( bdemount_mount_handle, (uint8_t *) buffer, size, &error ); if( read_count == -1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_READ_FAILED, "%s: unable to read from mount handle.", function ); result = -EIO; goto on_error; } return( (int) read_count ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Sets the values in a stat info structure * Returns 1 if successful or -1 on error */ int bdemount_fuse_set_stat_info( struct stat *stat_info, uint64_t creation_time, uint64_t modification_time, uint64_t access_time, size64_t size, int number_of_sub_items, uint8_t use_mount_time, libcerror_error_t **error ) { static char *function = "bdemount_fuse_set_stat_info"; if( stat_info == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid stat info.", function ); return( -1 ); } if( use_mount_time == 0 ) { /* TODO check size fo time_t if 64-bit allow for more precision */ if( creation_time != 0 ) { creation_time /= 10000000; if( creation_time < 11644473600UL ) { creation_time = 0; } else { creation_time -= 11644473600UL; } /* TODO check upper bound */ stat_info->st_ctime = (time_t) creation_time; } if( modification_time != 0 ) { modification_time /= 10000000; if( modification_time < 11644473600UL ) { modification_time = 0; } else { modification_time -= 11644473600UL; } /* TODO check upper bound */ stat_info->st_mtime = (time_t) modification_time; } if( access_time != 0 ) { access_time /= 10000000; if( access_time < 11644473600UL ) { access_time = 0; } else { access_time -= 11644473600UL; } /* TODO check upper bound */ stat_info->st_atime = (time_t) access_time; } } #if defined( HAVE_TIME ) else { if( bdemount_timestamp == 0 ) { if( time( &bdemount_timestamp ) == (time_t) -1 ) { bdemount_timestamp = 0; } } stat_info->st_atime = bdemount_timestamp; stat_info->st_mtime = bdemount_timestamp; stat_info->st_ctime = bdemount_timestamp; } #endif if( size != 0 ) { #if SIZEOF_OFF_T <= 4 if( size > (size64_t) UINT32_MAX ) #else if( size > (size64_t) INT64_MAX ) #endif { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS, "%s: invalid size value out of bounds.", function ); return( -1 ); } stat_info->st_size = (off_t) size; } if( number_of_sub_items > 0 ) { stat_info->st_mode = S_IFDIR | 0555; stat_info->st_nlink = 2; } else { stat_info->st_mode = S_IFREG | 0444; stat_info->st_nlink = 1; } #if defined( HAVE_GETEUID ) stat_info->st_uid = geteuid(); #endif #if defined( HAVE_GETEGID ) stat_info->st_gid = getegid(); #endif return( 1 ); } /* Fills a directory entry * Returns 1 if successful or -1 on error */ int bdemount_fuse_filldir( void *buffer, fuse_fill_dir_t filler, char *name, size_t name_size, struct stat *stat_info, mount_handle_t *mount_handle, uint8_t use_mount_time, libcerror_error_t **error ) { static char *function = "bdemount_fuse_filldir"; size64_t volume_size = 0; uint64_t creation_time = 0; int number_of_sub_items = 0; if( filler == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid filler.", function ); return( -1 ); } if( mount_handle == NULL ) { number_of_sub_items = 1; } else { if( mount_handle_get_creation_time( mount_handle, &creation_time, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve creation time.", function ); return( -1 ); } if( mount_handle_get_size( mount_handle, &volume_size, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve volume size.", function ); return( -1 ); } } if( memory_set( stat_info, 0, sizeof( struct stat ) ) == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_SET_FAILED, "%s: unable to clear stat info.", function ); return( -1 ); } if( bdemount_fuse_set_stat_info( stat_info, creation_time, creation_time, creation_time, volume_size, number_of_sub_items, use_mount_time, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set stat info.", function ); return( -1 ); } if( filler( buffer, name, stat_info, 0 ) == 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set directory entry.", function ); return( -1 ); } return( 1 ); } /* Reads a directory * Returns 0 if successful or a negative errno value otherwise */ int bdemount_fuse_readdir( const char *path, void *buffer, fuse_fill_dir_t filler, off_t offset LIBCSYSTEM_ATTRIBUTE_UNUSED, struct fuse_file_info *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; struct stat *stat_info = NULL; static char *function = "bdemount_fuse_readdir"; size_t path_length = 0; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( offset ) LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -EINVAL; goto on_error; } path_length = libcstring_narrow_string_length( path ); if( ( path_length != 1 ) || ( path[ 0 ] != '/' ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path.", function ); result = -ENOENT; goto on_error; } stat_info = memory_allocate_structure( struct stat ); if( stat_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_INSUFFICIENT, "%s: unable to create stat info.", function ); result = errno; goto on_error; } if( bdemount_fuse_filldir( buffer, filler, ".", 2, stat_info, NULL, 1, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set directory entry.", function ); result = -EIO; goto on_error; } if( bdemount_fuse_filldir( buffer, filler, "..", 3, stat_info, NULL, 0, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set directory entry.", function ); result = -EIO; goto on_error; } if( bdemount_fuse_filldir( buffer, filler, &( bdemount_fuse_path[ 1 ] ), bdemount_fuse_path_length + 1, stat_info, bdemount_mount_handle, 0, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set directory entry.", function ); result = -EIO; goto on_error; } memory_free( stat_info ); return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } if( stat_info != NULL ) { memory_free( stat_info ); } return( result ); } /* Retrieves the file stat info * Returns 0 if successful or a negative errno value otherwise */ int bdemount_fuse_getattr( const char *path, struct stat *stat_info ) { libcerror_error_t *error = NULL; static char *function = "bdemount_fuse_getattr"; size64_t volume_size = 0; uint64_t creation_time = 0; size_t path_length = 0; int number_of_sub_items = 0; int result = -ENOENT; uint8_t use_mount_time = 0; if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -EINVAL; goto on_error; } if( stat_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid stat info.", function ); result = -EINVAL; goto on_error; } if( memory_set( stat_info, 0, sizeof( struct stat ) ) == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_SET_FAILED, "%s: unable to clear stat info.", function ); result = errno; goto on_error; } path_length = libcstring_narrow_string_length( path ); if( path_length == 1 ) { if( path[ 0 ] == '/' ) { number_of_sub_items = 1; use_mount_time = 1; result = 0; } } else if( path_length == bdemount_fuse_path_length ) { if( libcstring_narrow_string_compare( path, bdemount_fuse_path, bdemount_fuse_path_length ) == 0 ) { if( mount_handle_get_creation_time( bdemount_mount_handle, &creation_time, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve creation time.", function ); result = -EIO; goto on_error; } if( mount_handle_get_size( bdemount_mount_handle, &volume_size, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve volume size.", function ); result = -EIO; goto on_error; } result = 0; } } if( result == 0 ) { if( bdemount_fuse_set_stat_info( stat_info, creation_time, creation_time, creation_time, volume_size, number_of_sub_items, use_mount_time, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set stat info.", function ); result = -EIO; goto on_error; } } return( result ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Cleans up when fuse is done */ void bdemount_fuse_destroy( void *private_data LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_fuse_destroy"; LIBCSYSTEM_UNREFERENCED_PARAMETER( private_data ) if( bdemount_mount_handle != NULL ) { if( mount_handle_free( &bdemount_mount_handle, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED, "%s: unable to free mount handle.", function ); goto on_error; } } return; on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return; } #elif defined( HAVE_LIBDOKAN ) static wchar_t *bdemount_dokan_path = L"\\BDE1"; static size_t bdemount_dokan_path_length = 5; /* Opens a file or directory * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_CreateFile( const wchar_t *path, DWORD desired_access, DWORD share_mode LIBCSYSTEM_ATTRIBUTE_UNUSED, DWORD creation_disposition, DWORD attribute_flags LIBCSYSTEM_ATTRIBUTE_UNUSED, DOKAN_FILE_INFO *file_info ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_CreateFile"; size_t path_length = 0; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( share_mode ) LIBCSYSTEM_UNREFERENCED_PARAMETER( attribute_flags ) if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } if( ( desired_access & GENERIC_WRITE ) != 0 ) { return( -ERROR_WRITE_PROTECT ); } /* Ignore the share_mode */ if( creation_disposition == CREATE_NEW ) { return( -ERROR_FILE_EXISTS ); } else if( creation_disposition == CREATE_ALWAYS ) { return( -ERROR_ALREADY_EXISTS ); } else if( creation_disposition == OPEN_ALWAYS ) { return( -ERROR_FILE_NOT_FOUND ); } else if( creation_disposition == TRUNCATE_EXISTING ) { return( -ERROR_FILE_NOT_FOUND ); } else if( creation_disposition != OPEN_EXISTING ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid creation disposition.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } if( file_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file info.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } path_length = libcstring_wide_string_length( path ); if( path_length == 1 ) { if( path[ 0 ] != (wchar_t) '\\' ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } } else { if( ( path_length != bdemount_dokan_path_length ) || ( libcstring_wide_string_compare( path, bdemount_dokan_path, bdemount_dokan_path_length ) != 0 ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Opens a directory * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_OpenDirectory( const wchar_t *path, DOKAN_FILE_INFO *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_OpenDirectory"; size_t path_length = 0; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } path_length = libcstring_wide_string_length( path ); if( ( path_length != 1 ) || ( path[ 0 ] != (wchar_t) '\\' ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Closes a file or direcotry * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_CloseFile( const wchar_t *path, DOKAN_FILE_INFO *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_CloseFile"; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Reads a buffer of data at the specified offset * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_ReadFile( const wchar_t *path, void *buffer, DWORD number_of_bytes_to_read, DWORD *number_of_bytes_read, LONGLONG offset, DOKAN_FILE_INFO *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_ReadFile"; size_t path_length = 0; ssize_t read_count = 0; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } if( number_of_bytes_to_read > (DWORD) INT32_MAX ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid number of bytes to read value exceeds maximum.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } if( number_of_bytes_read == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid number of bytes read.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } path_length = libcstring_wide_string_length( path ); if( ( path_length != bdemount_dokan_path_length ) || ( libcstring_wide_string_compare( path, bdemount_dokan_path, bdemount_dokan_path_length ) != 0 ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } if( mount_handle_seek_offset( bdemount_mount_handle, (off64_t) offset, SEEK_SET, &error ) == -1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_SEEK_FAILED, "%s: unable to seek offset in mount handle.", function ); result = -ERROR_SEEK_ON_DEVICE; goto on_error; } read_count = mount_handle_read_buffer( bdemount_mount_handle, (uint8_t *) buffer, (size_t) number_of_bytes_to_read, &error ); if( read_count == -1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_READ_FAILED, "%s: unable to read from mount handle.", function ); result = -ERROR_READ_FAULT; goto on_error; } if( read_count > (size_t) INT32_MAX ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid read count value exceeds maximum.", function ); result = -ERROR_READ_FAULT; goto on_error; } /* Dokan does not require the read function to return ERROR_HANDLE_EOF */ *number_of_bytes_read = (DWORD) read_count; return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Sets the values in a find data structure * Returns 1 if successful or -1 on error */ int bdemount_dokan_set_find_data( WIN32_FIND_DATAW *find_data, uint64_t creation_time, uint64_t modification_time, uint64_t access_time, size64_t size, int number_of_sub_items, uint8_t use_mount_time, libcerror_error_t **error ) { static char *function = "bdemount_dokan_set_find_data"; if( find_data == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid find data.", function ); return( -1 ); } if( use_mount_time == 0 ) { if( creation_time != 0 ) { find_data->ftCreationTime.dwLowDateTime = (uint32_t) ( creation_time & 0x00000000ffffffffULL ); find_data->ftCreationTime.dwHighDateTime = creation_time >> 32; } if( modification_time != 0 ) { find_data->ftLastWriteTime.dwLowDateTime = (uint32_t) ( modification_time & 0x00000000ffffffffULL ); find_data->ftLastWriteTime.dwHighDateTime = modification_time >> 32; } if( access_time != 0 ) { find_data->ftLastAccessTime.dwLowDateTime = (uint32_t) ( access_time & 0x00000000ffffffffULL ); find_data->ftLastAccessTime.dwHighDateTime = access_time >> 32; } } /* TODO implement else { } */ if( size > 0 ) { find_data->nFileSizeHigh = (DWORD) ( size >> 32 ); find_data->nFileSizeLow = (DWORD) ( size & 0xffffffffUL ); } find_data->dwFileAttributes = FILE_ATTRIBUTE_READONLY; if( number_of_sub_items > 0 ) { find_data->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY; } return( 1 ); } /* Fills a directory entry * Returns 1 if successful or -1 on error */ int bdemount_dokan_filldir( PFillFindData fill_find_data, DOKAN_FILE_INFO *file_info, wchar_t *name, size_t name_size, WIN32_FIND_DATAW *find_data, mount_handle_t *mount_handle, uint8_t use_mount_time, libcerror_error_t **error ) { static char *function = "bdemount_dokan_filldir"; size64_t volume_size = 0; uint64_t creation_time = 0; int number_of_sub_items = 0; if( fill_find_data == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid fill find data.", function ); return( -1 ); } if( name == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid name.", function ); return( -1 ); } if( name_size > (size_t) MAX_PATH ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_OUT_OF_BOUNDS, "%s: invalid name size value out of bounds.", function ); return( -1 ); } if( mount_handle == NULL ) { number_of_sub_items = 1; } else { if( mount_handle_get_creation_time( mount_handle, &creation_time, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve creation time.", function ); return( -1 ); } if( mount_handle_get_size( mount_handle, &volume_size, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve volume size.", function ); return( -1 ); } } if( memory_set( find_data, 0, sizeof( WIN32_FIND_DATAW ) ) == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_SET_FAILED, "%s: unable to clear find data.", function ); return( -1 ); } if( libcstring_wide_string_copy( find_data->cFileName, name, name_size ) == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_COPY_FAILED, "%s: unable to copy filename.", function ); return( -1 ); } if( name_size <= (size_t) 14 ) { if( libcstring_wide_string_copy( find_data->cAlternateFileName, name, name_size ) == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_COPY_FAILED, "%s: unable to copy alternate filename.", function ); return( -1 ); } } if( bdemount_dokan_set_find_data( find_data, creation_time, creation_time, creation_time, volume_size, number_of_sub_items, use_mount_time, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set find data.", function ); return( -1 ); } if( fill_find_data( find_data, file_info ) != 0 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set directory entry.", function ); return( -1 ); } return( 1 ); } /* Reads a directory * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_FindFiles( const wchar_t *path, PFillFindData fill_find_data, DOKAN_FILE_INFO *file_info ) { WIN32_FIND_DATAW find_data; libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_FindFiles"; size_t path_length = 0; int result = 0; if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } path_length = libcstring_wide_string_length( path ); if( ( path_length != 1 ) || ( path[ 0 ] != (wchar_t) '\\' ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } if( bdemount_dokan_filldir( fill_find_data, file_info, L".", 2, &find_data, NULL, 1, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set find data.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } if( bdemount_dokan_filldir( fill_find_data, file_info, L"..", 3, &find_data, NULL, 0, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set find data.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } if( bdemount_dokan_filldir( fill_find_data, file_info, &( bdemount_dokan_path[ 1 ] ), bdemount_dokan_path_length, &find_data, bdemount_mount_handle, 0, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set find data.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Sets the values in a file information structure * Returns 1 if successful or -1 on error */ int bdemount_dokan_set_file_information( BY_HANDLE_FILE_INFORMATION *file_information, uint64_t creation_time, uint64_t modification_time, uint64_t access_time, size64_t size, int number_of_sub_items, uint8_t use_mount_time, libcerror_error_t **error ) { static char *function = "bdemount_dokan_set_file_information"; if( file_information == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file information.", function ); return( -1 ); } if( use_mount_time == 0 ) { if( creation_time != 0 ) { file_information->ftCreationTime.dwLowDateTime = (uint32_t) ( creation_time & 0x00000000ffffffffULL ); file_information->ftCreationTime.dwHighDateTime = creation_time >> 32; } if( modification_time != 0 ) { file_information->ftLastWriteTime.dwLowDateTime = (uint32_t) ( modification_time & 0x00000000ffffffffULL ); file_information->ftLastWriteTime.dwHighDateTime = modification_time >> 32; } if( access_time != 0 ) { file_information->ftLastAccessTime.dwLowDateTime = (uint32_t) ( access_time & 0x00000000ffffffffULL ); file_information->ftLastAccessTime.dwHighDateTime = access_time >> 32; } } /* TODO implement else { } */ if( size > 0 ) { file_information->nFileSizeHigh = (DWORD) ( size >> 32 ); file_information->nFileSizeLow = (DWORD) ( size & 0xffffffffUL ); } file_information->dwFileAttributes = FILE_ATTRIBUTE_READONLY; if( number_of_sub_items > 0 ) { file_information->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY; } return( 1 ); } /* Retrieves the file information * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_GetFileInformation( const wchar_t *path, BY_HANDLE_FILE_INFORMATION *file_information, DOKAN_FILE_INFO *file_info ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_GetFileInformation"; size64_t volume_size = 0; uint64_t creation_time = 0; size_t path_length = 0; int number_of_sub_items = 0; int result = 0; uint8_t use_mount_time = 0; if( path == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid path.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } if( file_info == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file info.", function ); result = -ERROR_BAD_ARGUMENTS; goto on_error; } path_length = libcstring_wide_string_length( path ); if( path_length == 1 ) { if( path[ 0 ] != (wchar_t) '\\' ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } number_of_sub_items = 1; use_mount_time = 1; } else { if( ( path_length != bdemount_dokan_path_length ) || ( libcstring_wide_string_compare( path, bdemount_dokan_path, bdemount_dokan_path_length ) != 0 ) ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported path: %ls.", function, path ); result = -ERROR_FILE_NOT_FOUND; goto on_error; } if( mount_handle_get_creation_time( bdemount_mount_handle, &creation_time, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve creation time.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } if( mount_handle_get_size( bdemount_mount_handle, &volume_size, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve volume size.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } } if( bdemount_dokan_set_file_information( file_information, creation_time, creation_time, creation_time, volume_size, number_of_sub_items, use_mount_time, &error ) != 1 ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_SET_FAILED, "%s: unable to set file info.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Retrieves the volume information * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_GetVolumeInformation( wchar_t *volume_name, DWORD volume_name_size, DWORD *volume_serial_number, DWORD *maximum_filename_length, DWORD *file_system_flags, wchar_t *file_system_name, DWORD file_system_name_size, DOKAN_FILE_INFO *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { libcerror_error_t *error = NULL; static char *function = "bdemount_dokan_GetVolumeInformation"; int result = 0; LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) if( ( volume_name != NULL ) && ( volume_name_size > (DWORD) ( sizeof( wchar_t ) * 4 ) ) ) { /* Using wcsncpy seems to cause strange behavior here */ if( memory_copy( volume_name, L"BDE", sizeof( wchar_t ) * 4 ) == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_COPY_FAILED, "%s: unable to copy volume name.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } } if( volume_serial_number != NULL ) { /* If this value contains 0 it can crash the system is this an issue in Dokan? */ *volume_serial_number = 0x19831116; } if( maximum_filename_length != NULL ) { *maximum_filename_length = 256; } if( file_system_flags != NULL ) { *file_system_flags = FILE_CASE_SENSITIVE_SEARCH | FILE_CASE_PRESERVED_NAMES | FILE_UNICODE_ON_DISK | FILE_READ_ONLY_VOLUME; } if( ( file_system_name != NULL ) && ( file_system_name_size > (DWORD) ( sizeof( wchar_t ) * 6 ) ) ) { /* Using wcsncpy seems to cause strange behavior here */ if( memory_copy( file_system_name, L"Dokan", sizeof( wchar_t ) * 6 ) == NULL ) { libcerror_error_set( &error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_COPY_FAILED, "%s: unable to copy file system name.", function ); result = -ERROR_GEN_FAILURE; goto on_error; } } return( 0 ); on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } return( result ); } /* Unmount the image * Returns 0 if successful or a negative error code otherwise */ int __stdcall bdemount_dokan_Unmount( DOKAN_FILE_INFO *file_info LIBCSYSTEM_ATTRIBUTE_UNUSED ) { static char *function = "bdemount_dokan_Unmount"; LIBCSYSTEM_UNREFERENCED_PARAMETER( file_info ) return( 0 ); } #endif /* The main program */ #if defined( LIBCSTRING_HAVE_WIDE_SYSTEM_CHARACTER ) int wmain( int argc, wchar_t * const argv[] ) #else int main( int argc, char * const argv[] ) #endif { libbde_error_t *error = NULL; libcstring_system_character_t *mount_point = NULL; libcstring_system_character_t *option_extended_options = NULL; libcstring_system_character_t *option_keys = NULL; libcstring_system_character_t *option_password = NULL; libcstring_system_character_t *option_recovery_password = NULL; libcstring_system_character_t *option_startup_key_filename = NULL; libcstring_system_character_t *option_volume_offset = NULL; libcstring_system_character_t *source = NULL; char *program = "bdemount"; libcstring_system_integer_t option = 0; int result = 0; int verbose = 0; #if defined( HAVE_LIBFUSE ) || defined( HAVE_LIBOSXFUSE ) struct fuse_operations bdemount_fuse_operations; struct fuse_args bdemount_fuse_arguments = FUSE_ARGS_INIT(0, NULL); struct fuse_chan *bdemount_fuse_channel = NULL; struct fuse *bdemount_fuse_handle = NULL; #elif defined( HAVE_LIBDOKAN ) DOKAN_OPERATIONS bdemount_dokan_operations; DOKAN_OPTIONS bdemount_dokan_options; #endif libcnotify_stream_set( stderr, NULL ); libcnotify_verbose_set( 1 ); if( libclocale_initialize( "bdetools", &error ) != 1 ) { fprintf( stderr, "Unable to initialize locale values.\n" ); goto on_error; } if( libcsystem_initialize( _IONBF, &error ) != 1 ) { fprintf( stderr, "Unable to initialize system values.\n" ); goto on_error; } bdeoutput_version_fprint( stdout, program ); while( ( option = libcsystem_getopt( argc, argv, _LIBCSTRING_SYSTEM_STRING( "hk:o:p:r:s:vVX:" ) ) ) != (libcstring_system_integer_t) -1 ) { switch( option ) { case (libcstring_system_integer_t) '?': default: fprintf( stderr, "Invalid argument: %" PRIs_LIBCSTRING_SYSTEM "\n", argv[ optind - 1 ] ); usage_fprint( stdout ); return( EXIT_FAILURE ); case (libcstring_system_integer_t) 'h': usage_fprint( stdout ); return( EXIT_SUCCESS ); case (libcstring_system_integer_t) 'k': option_keys = optarg; break; case (libcstring_system_integer_t) 'o': option_volume_offset = optarg; break; case (libcstring_system_integer_t) 'p': option_password = optarg; break; case (libcstring_system_integer_t) 'r': option_recovery_password = optarg; break; case (libcstring_system_integer_t) 's': option_startup_key_filename = optarg; break; case (libcstring_system_integer_t) 'v': verbose = 1; break; case (libcstring_system_integer_t) 'V': bdeoutput_copyright_fprint( stdout ); return( EXIT_SUCCESS ); case (libcstring_system_integer_t) 'X': option_extended_options = optarg; break; } } if( optind == argc ) { fprintf( stderr, "Missing source file or device.\n" ); usage_fprint( stdout ); return( EXIT_FAILURE ); } source = argv[ optind++ ]; if( optind == argc ) { fprintf( stderr, "Missing mount point.\n" ); usage_fprint( stdout ); return( EXIT_FAILURE ); } mount_point = argv[ optind ]; libcnotify_verbose_set( verbose ); libbde_notify_set_stream( stderr, NULL ); libbde_notify_set_verbose( verbose ); if( mount_handle_initialize( &bdemount_mount_handle, &error ) != 1 ) { fprintf( stderr, "Unable to initialize mount handle.\n" ); goto on_error; } if( option_keys != NULL ) { if( mount_handle_set_keys( bdemount_mount_handle, option_keys, &error ) != 1 ) { fprintf( stderr, "Unable to set keys.\n" ); goto on_error; } } if( option_password != NULL ) { if( mount_handle_set_password( bdemount_mount_handle, option_password, &error ) != 1 ) { fprintf( stderr, "Unable to set password.\n" ); goto on_error; } } if( option_recovery_password != NULL ) { if( mount_handle_set_recovery_password( bdemount_mount_handle, option_recovery_password, &error ) != 1 ) { fprintf( stderr, "Unable to set recovery password.\n" ); goto on_error; } } if( option_startup_key_filename != NULL ) { if( mount_handle_read_startup_key( bdemount_mount_handle, option_startup_key_filename, &error ) != 1 ) { fprintf( stderr, "Unable to read startup key.\n" ); goto on_error; } } if( option_volume_offset != NULL ) { if( mount_handle_set_volume_offset( bdemount_mount_handle, option_volume_offset, &error ) != 1 ) { fprintf( stderr, "Unable to set volume offset.\n" ); goto on_error; } } result = mount_handle_open_input( bdemount_mount_handle, source, &error ); if( result != 1 ) { fprintf( stderr, "Unable to open: %" PRIs_LIBCSTRING_SYSTEM ".\n", source ); goto on_error; } result = mount_handle_input_is_locked( bdemount_mount_handle, &error ); if( result != 0 ) { fprintf( stderr, "Unable to unlock volume.\n" ); goto on_error; } #if defined( HAVE_LIBFUSE ) || defined( HAVE_LIBOSXFUSE ) if( memory_set( &bdemount_fuse_operations, 0, sizeof( struct fuse_operations ) ) == NULL ) { fprintf( stderr, "Unable to clear fuse operations.\n" ); goto on_error; } if( option_extended_options != NULL ) { /* This argument is required but ignored */ if( fuse_opt_add_arg( &bdemount_fuse_arguments, "" ) != 0 ) { fprintf( stderr, "Unable add fuse arguments.\n" ); goto on_error; } if( fuse_opt_add_arg( &bdemount_fuse_arguments, "-o" ) != 0 ) { fprintf( stderr, "Unable add fuse arguments.\n" ); goto on_error; } if( fuse_opt_add_arg( &bdemount_fuse_arguments, option_extended_options ) != 0 ) { fprintf( stderr, "Unable add fuse arguments.\n" ); goto on_error; } } bdemount_fuse_operations.open = &bdemount_fuse_open; bdemount_fuse_operations.read = &bdemount_fuse_read; bdemount_fuse_operations.readdir = &bdemount_fuse_readdir; bdemount_fuse_operations.getattr = &bdemount_fuse_getattr; bdemount_fuse_operations.destroy = &bdemount_fuse_destroy; bdemount_fuse_channel = fuse_mount( mount_point, &bdemount_fuse_arguments ); if( bdemount_fuse_channel == NULL ) { fprintf( stderr, "Unable to create fuse channel.\n" ); goto on_error; } bdemount_fuse_handle = fuse_new( bdemount_fuse_channel, &bdemount_fuse_arguments, &bdemount_fuse_operations, sizeof( struct fuse_operations ), bdemount_mount_handle ); if( bdemount_fuse_handle == NULL ) { fprintf( stderr, "Unable to create fuse handle.\n" ); goto on_error; } if( verbose == 0 ) { if( fuse_daemonize( 0 ) != 0 ) { fprintf( stderr, "Unable to daemonize fuse.\n" ); goto on_error; } } result = fuse_loop( bdemount_fuse_handle ); if( result != 0 ) { fprintf( stderr, "Unable to run fuse loop.\n" ); goto on_error; } fuse_destroy( bdemount_fuse_handle ); fuse_opt_free_args( &bdemount_fuse_arguments ); return( EXIT_SUCCESS ); #elif defined( HAVE_LIBDOKAN ) if( memory_set( &bdemount_dokan_operations, 0, sizeof( DOKAN_OPERATIONS ) ) == NULL ) { fprintf( stderr, "Unable to clear dokan operations.\n" ); goto on_error; } if( memory_set( &bdemount_dokan_options, 0, sizeof( DOKAN_OPTIONS ) ) == NULL ) { fprintf( stderr, "Unable to clear dokan options.\n" ); goto on_error; } bdemount_dokan_options.Version = 600; bdemount_dokan_options.ThreadCount = 0; bdemount_dokan_options.MountPoint = mount_point; if( verbose != 0 ) { bdemount_dokan_options.Options |= DOKAN_OPTION_STDERR; #if defined( HAVE_DEBUG_OUTPUT ) bdemount_dokan_options.Options |= DOKAN_OPTION_DEBUG; #endif } /* This will only affect the drive properties bdemount_dokan_options.Options |= DOKAN_OPTION_REMOVABLE; */ bdemount_dokan_options.Options |= DOKAN_OPTION_KEEP_ALIVE; bdemount_dokan_operations.CreateFile = &bdemount_dokan_CreateFile; bdemount_dokan_operations.OpenDirectory = &bdemount_dokan_OpenDirectory; bdemount_dokan_operations.CreateDirectory = NULL; bdemount_dokan_operations.Cleanup = NULL; bdemount_dokan_operations.CloseFile = &bdemount_dokan_CloseFile; bdemount_dokan_operations.ReadFile = &bdemount_dokan_ReadFile; bdemount_dokan_operations.WriteFile = NULL; bdemount_dokan_operations.FlushFileBuffers = NULL; bdemount_dokan_operations.GetFileInformation = &bdemount_dokan_GetFileInformation; bdemount_dokan_operations.FindFiles = &bdemount_dokan_FindFiles; bdemount_dokan_operations.FindFilesWithPattern = NULL; bdemount_dokan_operations.SetFileAttributes = NULL; bdemount_dokan_operations.SetFileTime = NULL; bdemount_dokan_operations.DeleteFile = NULL; bdemount_dokan_operations.DeleteDirectory = NULL; bdemount_dokan_operations.MoveFile = NULL; bdemount_dokan_operations.SetEndOfFile = NULL; bdemount_dokan_operations.SetAllocationSize = NULL; bdemount_dokan_operations.LockFile = NULL; bdemount_dokan_operations.UnlockFile = NULL; bdemount_dokan_operations.GetFileSecurity = NULL; bdemount_dokan_operations.SetFileSecurity = NULL; bdemount_dokan_operations.GetDiskFreeSpace = NULL; bdemount_dokan_operations.GetVolumeInformation = &bdemount_dokan_GetVolumeInformation; bdemount_dokan_operations.Unmount = &bdemount_dokan_Unmount; result = DokanMain( &bdemount_dokan_options, &bdemount_dokan_operations ); switch( result ) { case DOKAN_SUCCESS: break; case DOKAN_ERROR: fprintf( stderr, "Unable to run dokan main: generic error\n" ); break; case DOKAN_DRIVE_LETTER_ERROR: fprintf( stderr, "Unable to run dokan main: bad drive letter\n" ); break; case DOKAN_DRIVER_INSTALL_ERROR: fprintf( stderr, "Unable to run dokan main: unable to load driver\n" ); break; case DOKAN_START_ERROR: fprintf( stderr, "Unable to run dokan main: driver error\n" ); break; case DOKAN_MOUNT_ERROR: fprintf( stderr, "Unable to run dokan main: unable to assign drive letter\n" ); break; case DOKAN_MOUNT_POINT_ERROR: fprintf( stderr, "Unable to run dokan main: mount point error\n" ); break; default: fprintf( stderr, "Unable to run dokan main: unknown error: %d\n", result ); break; } return( EXIT_SUCCESS ); #else fprintf( stderr, "No sub system to mount BDE volume.\n" ); return( EXIT_FAILURE ); #endif on_error: if( error != NULL ) { libcnotify_print_error_backtrace( error ); libcerror_error_free( &error ); } #if defined( HAVE_LIBFUSE ) || defined( HAVE_LIBOSXFUSE ) if( bdemount_fuse_handle != NULL ) { fuse_destroy( bdemount_fuse_handle ); } fuse_opt_free_args( &bdemount_fuse_arguments ); #endif if( bdemount_mount_handle != NULL ) { mount_handle_free( &bdemount_mount_handle, NULL ); } return( EXIT_FAILURE ); }
Java
###说明 - 这是用C++实现的二分搜索树 ####使用工具 - CMake - make ####使用代码 - 注意请安装cmake3.5以上版本 - 新建一个文件夹 `mkdir build` - 进入build目录 `cd build` - cmake配置 `cmake ..` - 编译执行 `make` - 进入bin目录下 `cd bin/` - 执行代码 `./BinarySearchTree`
Java
/* * Copyright (C) 2014 Stuart Howarth <showarth@marxoft.co.uk> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 3, as published by the Free Software Foundation. * * This program is distributed in the hope 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, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef MASKEDITEM_H #define MASKEDITEM_H #include "maskeffect.h" #include <QDeclarativeItem> class MaskEffect; class QDeclarativeComponent; class MaskedItem : public QDeclarativeItem { Q_OBJECT Q_PROPERTY(QDeclarativeComponent *mask READ mask WRITE setMask NOTIFY maskChanged) public: MaskedItem(QDeclarativeItem *parent = 0); virtual ~MaskedItem(); QDeclarativeComponent *mask() const; void setMask(QDeclarativeComponent *component); signals: void maskChanged(); private: MaskEffect *m_effect; QDeclarativeComponent *m_maskComponent; }; #endif // MASKEDITEM_H
Java
/* * Copyright(c) 2013 Tim Ruehsen * Copyright(c) 2015-2016 Free Software Foundation, Inc. * * This file is part of libwget. * * Libwget is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Libwget 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 libwget. If not, see <https://www.gnu.org/licenses/>. * * * Highlevel HTTP functions * * Changelog * 21.01.2013 Tim Ruehsen created * */ #if HAVE_CONFIG_H # include <config.h> #endif #include <stdio.h> #include <string.h> #include <errno.h> #include <wget.h> #include "private.h" static int _stream_callback(wget_http_response_t *resp G_GNUC_WGET_UNUSED, void *user_data, const char *data, size_t length) { FILE *stream = (FILE *) user_data; size_t nbytes = fwrite(data, 1, length, stream); if (nbytes != length) { error_printf(_("Failed to write %zu bytes of data (%d)\n"), length, errno); if (feof(stream)) return -1; } return 0; } static int _fd_callback(wget_http_response_t *resp G_GNUC_WGET_UNUSED, void *user_data, const char *data, size_t length) { int fd = *(int *) user_data; ssize_t nbytes = write(fd, data, length); if (nbytes == -1 || (size_t) nbytes != length) error_printf(_("Failed to write %zu bytes of data (%d)\n"), length, errno); return 0; } wget_http_response_t *wget_http_get(int first_key, ...) { wget_vector_t *headers = wget_vector_create(8, 8, NULL); wget_iri_t *uri = NULL; wget_http_connection_t *conn = NULL, **connp = NULL; wget_http_request_t *req; wget_http_response_t *resp = NULL; wget_vector_t *challenges = NULL; wget_cookie_db_t *cookie_db = NULL; FILE *saveas_stream = NULL; wget_http_body_callback_t saveas_callback = NULL; int saveas_fd = -1; wget_http_header_callback_t header_callback = NULL; va_list args; const char *url = NULL, *url_encoding = NULL, *scheme = "GET"; const char *http_username = NULL, *http_password = NULL; const char *saveas_name = NULL; int key, it, max_redirections = 5, redirection_level = 0; size_t bodylen = 0; const void *body = NULL; void *header_user_data = NULL, *body_user_data = NULL; struct { unsigned int cookies_enabled : 1, keep_header : 1, free_uri : 1; } bits = { .cookies_enabled = !!wget_global_get_int(WGET_COOKIES_ENABLED) }; va_start(args, first_key); for (key = first_key; key; key = va_arg(args, int)) { switch (key) { case WGET_HTTP_URL: url = va_arg(args, const char *); break; case WGET_HTTP_URI: uri = va_arg(args, wget_iri_t *); break; case WGET_HTTP_URL_ENCODING: url_encoding = va_arg(args, const char *); break; case WGET_HTTP_HEADER_ADD: { wget_http_header_param_t param = { .name = va_arg(args, const char *), .value = va_arg(args, const char *) }; wget_vector_add(headers, &param, sizeof(param)); break; } case WGET_HTTP_CONNECTION_PTR: connp = va_arg(args, wget_http_connection_t **); if (connp) conn = *connp; break; case WGET_HTTP_RESPONSE_KEEPHEADER: bits.keep_header = va_arg(args, int); break; case WGET_HTTP_MAX_REDIRECTIONS: max_redirections = va_arg(args, int); break; case WGET_HTTP_BODY_SAVEAS: saveas_name = va_arg(args, const char *); break; case WGET_HTTP_BODY_SAVEAS_STREAM: saveas_stream = va_arg(args, FILE *); break; case WGET_HTTP_BODY_SAVEAS_FUNC: saveas_callback = va_arg(args, wget_http_body_callback_t); body_user_data = va_arg(args, void *); break; case WGET_HTTP_BODY_SAVEAS_FD: saveas_fd = va_arg(args, int); break; case WGET_HTTP_HEADER_FUNC: header_callback = va_arg(args, wget_http_header_callback_t); header_user_data = va_arg(args, void *); break; case WGET_HTTP_SCHEME: scheme = va_arg(args, const char *); break; case WGET_HTTP_BODY: body = va_arg(args, const void *); bodylen = va_arg(args, size_t); break; default: error_printf(_("Unknown option %d\n"), key); goto out; } } va_end(args); if (url && !uri) { uri = wget_iri_parse(url, url_encoding); if (!uri) { error_printf (_("Error parsing URL\n")); goto out; } bits.free_uri = 1; } if (!uri) { error_printf(_("Missing URL/URI\n")); goto out; } if (bits.cookies_enabled) cookie_db = (wget_cookie_db_t *)wget_global_get_ptr(WGET_COOKIE_DB); while (uri && redirection_level <= max_redirections) { // create a HTTP/1.1 GET request. // the only default header is 'Host: domain' (taken from uri) req = wget_http_create_request(uri, scheme); // add HTTP headers for (it = 0; it < wget_vector_size(headers); it++) { wget_http_add_header_param(req, wget_vector_get(headers, it)); } if (challenges) { // There might be more than one challenge, we could select the most secure one. // For simplicity and testing we just take the first for now. // the following adds an Authorization: HTTP header wget_http_add_credentials(req, wget_vector_get(challenges, 0), http_username, http_password); wget_http_free_challenges(&challenges); } // use keep-alive if you want to send more requests on the same connection // http_add_header(req, "Connection", "keep-alive"); // enrich the HTTP request with the uri-related cookies we have if (cookie_db) { const char *cookie_string; if ((cookie_string = wget_cookie_create_request_header(cookie_db, uri))) { wget_http_add_header(req, "Cookie", cookie_string); xfree(cookie_string); } } if (connp) { wget_http_add_header(req, "Connection", "keepalive"); } // open/reopen/reuse HTTP/HTTPS connection if (conn && !wget_strcmp(conn->esc_host, uri->host) && conn->scheme == uri->scheme && !wget_strcmp(conn->port, uri->resolv_port)) { debug_printf("reuse connection %s\n", conn->esc_host); } else { if (conn) { debug_printf("close connection %s\n", conn->esc_host); wget_http_close(&conn); } if (wget_http_open(&conn, uri) == WGET_E_SUCCESS) debug_printf("opened connection %s\n", conn->esc_host); } if (conn) { int rc; if (body && bodylen) wget_http_request_set_body(req, NULL, wget_memdup(body, bodylen), bodylen); rc = wget_http_send_request(conn, req); if (rc == 0) { wget_http_request_set_header_cb(req, header_callback, header_user_data); wget_http_request_set_int(req, WGET_HTTP_RESPONSE_KEEPHEADER, 1); if (saveas_name) { FILE *fp; if ((fp = fopen(saveas_name, "w"))) { wget_http_request_set_body_cb(req, _stream_callback, fp); resp = wget_http_get_response(conn); fclose(fp); } else debug_printf("Failed to open '%s' for writing\n", saveas_name); } else if (saveas_stream) { wget_http_request_set_body_cb(req, _stream_callback, saveas_stream); resp = wget_http_get_response(conn); } else if (saveas_callback) { wget_http_request_set_body_cb(req, saveas_callback, body_user_data); resp = wget_http_get_response(conn); } else if (saveas_fd != -1) { wget_http_request_set_body_cb(req, _fd_callback, &saveas_fd); resp = wget_http_get_response(conn); } else resp = wget_http_get_response(conn); } } wget_http_free_request(&req); if (!resp) goto out; // server doesn't support or want keep-alive if (!resp->keep_alive) wget_http_close(&conn); if (cookie_db) { // check and normalization of received cookies wget_cookie_normalize_cookies(uri, resp->cookies); // put cookies into cookie-store (also known as cookie-jar) wget_cookie_store_cookies(cookie_db, resp->cookies); } if (resp->code == 401 && !challenges) { // Unauthorized if ((challenges = resp->challenges)) { resp->challenges = NULL; wget_http_free_response(&resp); if (redirection_level == 0 && max_redirections) { redirection_level = max_redirections; // just try one more time with authentication continue; // try again with credentials } } break; } // 304 Not Modified if (resp->code / 100 == 2 || resp->code / 100 >= 4 || resp->code == 304) break; // final response if (resp->location) { char uri_sbuf[1024]; wget_buffer_t uri_buf; // if relative location, convert to absolute wget_buffer_init(&uri_buf, uri_sbuf, sizeof(uri_sbuf)); wget_iri_relative_to_abs(uri, resp->location, strlen(resp->location), &uri_buf); if (bits.free_uri) wget_iri_free(&uri); uri = wget_iri_parse(uri_buf.data, NULL); bits.free_uri = 1; wget_buffer_deinit(&uri_buf); redirection_level++; continue; } break; } out: if (connp) { *connp = conn; } else { wget_http_close(&conn); } wget_http_free_challenges(&challenges); // wget_vector_clear_nofree(headers); wget_vector_free(&headers); if (bits.free_uri) wget_iri_free(&uri); return resp; }
Java
<?php /** * * Copyright (c) 2014 gfg-development * * @link http://www.gfg-development.de * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL */ $GLOBALS['TL_LANG']['tl_linkslist_list']['title_legend'] = 'Titel'; $GLOBALS['TL_LANG']['tl_linkslist_list']['config_legend'] = 'Einstellungen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['name'][0] = 'Titel'; $GLOBALS['TL_LANG']['tl_linkslist_list']['name'][1] = 'Geben Sie hier den Linklist Titel ein.'; $GLOBALS['TL_LANG']['tl_linkslist_list']['new'][0] = 'Neue Linkliste'; $GLOBALS['TL_LANG']['tl_linkslist_list']['new'][1] = 'Eine neue Linkliste anlegen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['edit'][0] = 'Linkliste bearbeiten'; $GLOBALS['TL_LANG']['tl_linkslist_list']['edit'][1] = 'Linkliste ID %s bearbeiten'; $GLOBALS['TL_LANG']['tl_linkslist_list']['delete'][0] = 'Linkliste löschen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['delete'][1] = 'Linkliste ID %s löchen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['show'][0] = 'Linklistendetails'; $GLOBALS['TL_LANG']['tl_linkslist_list']['show'][1] = 'Details der Linkliste ID %s anzeigen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['target'][0] = 'Links in neuem Fenster öffnen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['target'][1] = 'Bitte wählen sie aus, ob die Links in einem neuen Fenster geöffnet werden sollen (target="_blank").'; ?>
Java
namespace MoCap.Manager { class Dispatcher : IComMsg { } }
Java
/********************************************************************** * Copyright (c) 2010, j. montgomery * * 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. * * * * + Neither the name of j. montgomery's employer 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 OWNER 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. * **********************************************************************/ using System; using System.IO; using System.Net; using System.Net.Sockets; using DnDns.Records; using DnDns.Enums; namespace DnDns.Query { /// <summary> /// Summary description for DnsQueryResponse. /// </summary> public class DnsQueryResponse : DnsQueryBase { #region Fields private DnsQueryRequest _queryRequest = new DnsQueryRequest(); private IDnsRecord[] _answers; private IDnsRecord[] _authoritiveNameServers; private IDnsRecord[] _additionalRecords; private int _bytesReceived = 0; #endregion Fields #region properties public DnsQueryRequest QueryRequest { get { return _queryRequest; } } public IDnsRecord[] Answers { get { return _answers; } } public IDnsRecord[] AuthoritiveNameServers { get { return _authoritiveNameServers; } } public IDnsRecord[] AdditionalRecords { get { return _additionalRecords; } } public int BytesReceived { get { return _bytesReceived; } } #endregion /// <summary> /// /// </summary> public DnsQueryResponse() { } private DnsQueryRequest ParseQuery(ref MemoryStream ms) { DnsQueryRequest queryRequest = new DnsQueryRequest(); // Read name queryRequest.Name = DnsRecordBase.ParseName(ref ms); return queryRequest; } internal void ParseResponse(byte[] recvBytes, ProtocolType protocol) { MemoryStream ms = new MemoryStream(recvBytes); byte[] flagBytes = new byte[2]; byte[] transactionId = new byte[2]; byte[] questions = new byte[2]; byte[] answerRRs = new byte[2]; byte[] authorityRRs = new byte[2]; byte[] additionalRRs = new byte[2]; byte[] nsType = new byte[2]; byte[] nsClass = new byte[2]; this._bytesReceived = recvBytes.Length; // Parse DNS Response ms.Read(transactionId, 0, 2); ms.Read(flagBytes, 0, 2); ms.Read(questions, 0, 2); ms.Read(answerRRs, 0, 2); ms.Read(authorityRRs, 0, 2); ms.Read(additionalRRs ,0, 2); // Parse Header _transactionId = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(transactionId, 0)); _flags = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(flagBytes, 0)); _queryResponse = (QueryResponse)(_flags & (ushort)FlagMasks.QueryResponseMask); _opCode = (OpCode)(_flags & (ushort)FlagMasks.OpCodeMask); _nsFlags = (NsFlags)(_flags & (ushort)FlagMasks.NsFlagMask); _rCode = (RCode)(_flags & (ushort)FlagMasks.RCodeMask); // Parse Questions Section _questions = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(questions, 0)); _answerRRs = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(answerRRs, 0)); _authorityRRs = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(authorityRRs, 0)); _additionalRRs = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(additionalRRs, 0)); _additionalRecords = new DnsRecordBase[_additionalRRs]; _answers = new DnsRecordBase[_answerRRs]; _authoritiveNameServers = new DnsRecordBase[_authorityRRs]; // Parse Queries _queryRequest = this.ParseQuery(ref ms); // Read dnsType ms.Read(nsType, 0, 2); // Read dnsClass ms.Read(nsClass, 0, 2); _nsType = (NsType)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(nsType, 0)); _nsClass = (NsClass)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(nsClass, 0)); // Read in Answer Blocks for (int i=0; i < _answerRRs; i++) { _answers[i] = RecordFactory.Create(ref ms); } // Parse Authority Records for (int i=0; i < _authorityRRs; i++) { _authoritiveNameServers[i] = RecordFactory.Create(ref ms); } // Parse Additional Records for (int i=0; i < _additionalRRs; i++) { _additionalRecords[i] = RecordFactory.Create(ref ms); } } } }
Java
<?php /** * This file is part of contao-community-alliance/dc-general. * * (c) 2013-2019 Contao Community Alliance. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * This project is provided in good faith and hope to be usable by anyone. * * @package contao-community-alliance/dc-general * @author Christian Schiffler <c.schiffler@cyberspectrum.de> * @author Tristan Lins <tristan.lins@bit3.de> * @author Sven Baumann <baumann.sv@gmail.com> * @copyright 2013-2019 Contao Community Alliance. * @license https://github.com/contao-community-alliance/dc-general/blob/master/LICENSE LGPL-3.0-or-later * @filesource */ namespace ContaoCommunityAlliance\DcGeneral\Contao\View\Contao2BackendView\Event; /** * Class GetGlobalButtonEvent. * * This event gets issued when the top level buttons in the listing view are being retrieved. * * These buttons include, but are not limited to, the "back" button and the "edit multiple" button. */ class GetGlobalButtonEvent extends BaseButtonEvent { public const NAME = 'dc-general.view.contao2backend.get-global-button'; /** * The hotkey for the button. * * @var string */ protected $accessKey; /** * The css class to use. * * @var string */ protected $class; /** * The href to use. * * @var string */ protected $href; /** * Set the hotkey for the button. * * @param string $accessKey The hotkey for the button. * * @return $this */ public function setAccessKey($accessKey) { $this->accessKey = $accessKey; return $this; } /** * Get the hotkey for the button. * * @return string */ public function getAccessKey() { return $this->accessKey; } /** * Set the css class for this button. * * @param string $class The css class. * * @return $this */ public function setClass($class) { $this->class = $class; return $this; } /** * Get the css class for this button. * * @return string */ public function getClass() { return $this->class; } /** * Set the href for this button. * * @param string $href The href. * * @return $this */ public function setHref($href) { $this->href = $href; return $this; } /** * Get the href for this button. * * @return string */ public function getHref() { return $this->href; } }
Java
/* * Copyright 2016 - 2021 Marcin Matula * * This file is part of Oap. * * Oap 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. * * Oap 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 Oap. If not, see <http://www.gnu.org/licenses/>. */ #include "gtest/gtest.h" #include "oapHostMemoryApi.h" class OapMemoryApiTests : public testing::Test { public: virtual void SetUp() {} virtual void TearDown() {} }; TEST_F(OapMemoryApiTests, Test_1) { oap::Memory memory = oap::host::NewMemory ({1, 1}); oap::Memory memory1 = oap::host::ReuseMemory (memory); oap::Memory memory2 = oap::host::ReuseMemory (memory); oap::host::DeleteMemory (memory); oap::host::DeleteMemory (memory1); oap::host::DeleteMemory (memory2); } TEST_F(OapMemoryApiTests, Test_2) { oap::Memory memory = oap::host::NewMemoryWithValues ({2, 1}, 2.f); oap::host::DeleteMemory (memory); }
Java
package org.openbase.bco.device.openhab.communication; /*- * #%L * BCO Openhab Device Manager * %% * Copyright (C) 2015 - 2021 openbase.org * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import com.google.gson.*; import org.eclipse.smarthome.core.internal.service.CommandDescriptionServiceImpl; import org.eclipse.smarthome.core.internal.types.CommandDescriptionImpl; import org.eclipse.smarthome.core.types.CommandDescription; import org.eclipse.smarthome.core.types.CommandDescriptionBuilder; import org.eclipse.smarthome.core.types.CommandOption; import org.openbase.bco.device.openhab.jp.JPOpenHABURI; import org.openbase.jps.core.JPService; import org.openbase.jps.exception.JPNotAvailableException; import org.openbase.jul.exception.InstantiationException; import org.openbase.jul.exception.*; import org.openbase.jul.exception.printer.ExceptionPrinter; import org.openbase.jul.exception.printer.LogLevel; import org.openbase.jul.iface.Shutdownable; import org.openbase.jul.pattern.Observable; import org.openbase.jul.pattern.ObservableImpl; import org.openbase.jul.pattern.Observer; import org.openbase.jul.schedule.GlobalScheduledExecutorService; import org.openbase.jul.schedule.SyncObject; import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState; import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.sse.InboundSseEvent; import javax.ws.rs.sse.SseEventSource; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public abstract class OpenHABRestConnection implements Shutdownable { public static final String SEPARATOR = "/"; public static final String REST_TARGET = "rest"; public static final String APPROVE_TARGET = "approve"; public static final String EVENTS_TARGET = "events"; public static final String TOPIC_KEY = "topic"; public static final String TOPIC_SEPARATOR = SEPARATOR; private static final Logger LOGGER = LoggerFactory.getLogger(OpenHABRestConnection.class); private final SyncObject topicObservableMapLock = new SyncObject("topicObservableMapLock"); private final SyncObject connectionStateSyncLock = new SyncObject("connectionStateSyncLock"); private final Map<String, ObservableImpl<Object, JsonObject>> topicObservableMap; private final Client restClient; private final WebTarget restTarget; private SseEventSource sseSource; private boolean shutdownInitiated = false; protected final JsonParser jsonParser; protected final Gson gson; private ScheduledFuture<?> connectionTask; protected ConnectionState.State openhabConnectionState = State.DISCONNECTED; public OpenHABRestConnection() throws InstantiationException { try { this.topicObservableMap = new HashMap<>(); this.gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return false; } @Override public boolean shouldSkipClass(Class<?> aClass) { // ignore Command Description because its an interface and can not be serialized without any instance creator. if(aClass.equals(CommandDescription.class)) { return true; } return false; } }).create(); this.jsonParser = new JsonParser(); this.restClient = ClientBuilder.newClient(); this.restTarget = restClient.target(JPService.getProperty(JPOpenHABURI.class).getValue().resolve(SEPARATOR + REST_TARGET)); this.setConnectState(State.CONNECTING); } catch (JPNotAvailableException ex) { throw new InstantiationException(this, ex); } } private boolean isTargetReachable() { try { testConnection(); } catch (CouldNotPerformException e) { if (e.getCause() instanceof ProcessingException) { return false; } } return true; } protected abstract void testConnection() throws CouldNotPerformException; public void waitForConnectionState(final ConnectionState.State connectionState, final long timeout, final TimeUnit timeUnit) throws InterruptedException { synchronized (connectionStateSyncLock) { while (getOpenhabConnectionState() != connectionState) { connectionStateSyncLock.wait(timeUnit.toMillis(timeout)); } } } public void waitForConnectionState(final ConnectionState.State connectionState) throws InterruptedException { synchronized (connectionStateSyncLock) { while (getOpenhabConnectionState() != connectionState) { connectionStateSyncLock.wait(); } } } private void setConnectState(final ConnectionState.State connectState) { synchronized (connectionStateSyncLock) { // filter non changing states if (connectState == this.openhabConnectionState) { return; } LOGGER.trace("Openhab Connection State changed to: "+connectState); // update state this.openhabConnectionState = connectState; // handle state change switch (connectState) { case CONNECTING: LOGGER.info("Wait for openHAB..."); try { connectionTask = GlobalScheduledExecutorService.scheduleWithFixedDelay(() -> { if (isTargetReachable()) { // set connected setConnectState(State.CONNECTED); // cleanup own task connectionTask.cancel(false); } }, 0, 15, TimeUnit.SECONDS); } catch (NotAvailableException | RejectedExecutionException ex) { // if global executor service is not available we have no chance to connect. LOGGER.warn("Wait for openHAB...", ex); setConnectState(State.DISCONNECTED); } break; case CONNECTED: LOGGER.info("Connection to OpenHAB established."); initSSE(); break; case RECONNECTING: LOGGER.warn("Connection to OpenHAB lost!"); resetConnection(); setConnectState(State.CONNECTING); break; case DISCONNECTED: LOGGER.info("Connection to OpenHAB closed."); resetConnection(); break; } // notify state change connectionStateSyncLock.notifyAll(); // apply next state if required switch (connectState) { case RECONNECTING: setConnectState(State.CONNECTING); break; } } } private void initSSE() { // activate sse source if not already done if (sseSource != null) { LOGGER.warn("SSE already initialized!"); return; } final WebTarget webTarget = restTarget.path(EVENTS_TARGET); sseSource = SseEventSource.target(webTarget).reconnectingEvery(15, TimeUnit.SECONDS).build(); sseSource.open(); final Consumer<InboundSseEvent> evenConsumer = inboundSseEvent -> { // dispatch event try { final JsonObject payload = jsonParser.parse(inboundSseEvent.readData()).getAsJsonObject(); for (Entry<String, ObservableImpl<Object, JsonObject>> topicObserverEntry : topicObservableMap.entrySet()) { try { if (payload.get(TOPIC_KEY).getAsString().matches(topicObserverEntry.getKey())) { topicObserverEntry.getValue().notifyObservers(payload); } } catch (Exception ex) { ExceptionPrinter.printHistory(new CouldNotPerformException("Could not notify listeners on topic[" + topicObserverEntry.getKey() + "]", ex), LOGGER); } } } catch (Exception ex) { ExceptionPrinter.printHistory(new CouldNotPerformException("Could not handle SSE payload!", ex), LOGGER); } }; final Consumer<Throwable> errorHandler = ex -> { ExceptionPrinter.printHistory("Openhab connection error detected!", ex, LOGGER, LogLevel.DEBUG); checkConnectionState(); }; final Runnable reconnectHandler = () -> { checkConnectionState(); }; sseSource.register(evenConsumer, errorHandler, reconnectHandler); } public State getOpenhabConnectionState() { return openhabConnectionState; } public void checkConnectionState() { synchronized (connectionStateSyncLock) { // only validate if connected if (!isConnected()) { return; } // if not reachable init a reconnect if (!isTargetReachable()) { setConnectState(State.RECONNECTING); } } } public boolean isConnected() { return getOpenhabConnectionState() == State.CONNECTED; } public void addSSEObserver(Observer<Object, JsonObject> observer) { addSSEObserver(observer, ""); } public void addSSEObserver(final Observer<Object, JsonObject> observer, final String topicRegex) { synchronized (topicObservableMapLock) { if (topicObservableMap.containsKey(topicRegex)) { topicObservableMap.get(topicRegex).addObserver(observer); return; } final ObservableImpl<Object, JsonObject> observable = new ObservableImpl<>(this); observable.addObserver(observer); topicObservableMap.put(topicRegex, observable); } } public void removeSSEObserver(Observer<Object, JsonObject> observer) { removeSSEObserver(observer, ""); } public void removeSSEObserver(Observer<Object, JsonObject> observer, final String topicFilter) { synchronized (topicObservableMapLock) { if (topicObservableMap.containsKey(topicFilter)) { topicObservableMap.get(topicFilter).removeObserver(observer); } } } private void resetConnection() { // cancel ongoing connection task if (!connectionTask.isDone()) { connectionTask.cancel(false); } // close sse if (sseSource != null) { sseSource.close(); sseSource = null; } } public void validateConnection() throws CouldNotPerformException { if (!isConnected()) { throw new InvalidStateException("Openhab not reachable yet!"); } } private String validateResponse(final Response response) throws CouldNotPerformException, ProcessingException { return validateResponse(response, false); } private String validateResponse(final Response response, final boolean skipConnectionValidation) throws CouldNotPerformException, ProcessingException { final String result = response.readEntity(String.class); if (response.getStatus() == 200 || response.getStatus() == 201 || response.getStatus() == 202) { return result; } else if (response.getStatus() == 404) { if (!skipConnectionValidation) { checkConnectionState(); } throw new NotAvailableException("URL"); } else if (response.getStatus() == 503) { if (!skipConnectionValidation) { checkConnectionState(); } // throw a processing exception to indicate that openHAB is still not fully started, this is used to wait for openHAB throw new ProcessingException("OpenHAB server not ready"); } else { throw new CouldNotPerformException("Response returned with ErrorCode[" + response.getStatus() + "], Result[" + result + "] and ErrorMessage[" + response.getStatusInfo().getReasonPhrase() + "]"); } } protected String get(final String target) throws CouldNotPerformException { return get(target, false); } protected String get(final String target, final boolean skipValidation) throws CouldNotPerformException { try { // handle validation if (!skipValidation) { validateConnection(); } final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().get(); return validateResponse(response, skipValidation); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not get sub-URL[" + target + "]", ex); } } protected String delete(final String target) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().delete(); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not delete sub-URL[" + target + "]", ex); } } protected String putJson(final String target, final Object value) throws CouldNotPerformException { return put(target, gson.toJson(value), MediaType.APPLICATION_JSON_TYPE); } protected String put(final String target, final String value, final MediaType mediaType) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().put(Entity.entity(value, mediaType)); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not put value[" + value + "] on sub-URL[" + target + "]", ex); } } protected String postJson(final String target, final Object value) throws CouldNotPerformException { return post(target, gson.toJson(value), MediaType.APPLICATION_JSON_TYPE); } protected String post(final String target, final String value, final MediaType mediaType) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().post(Entity.entity(value, mediaType)); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not post Value[" + value + "] of MediaType[" + mediaType + "] on sub-URL[" + target + "]", ex); } } public boolean isShutdownInitiated() { return shutdownInitiated; } @Override public void shutdown() { // prepare shutdown shutdownInitiated = true; setConnectState(State.DISCONNECTED); // stop rest service restClient.close(); // stop sse service synchronized (topicObservableMapLock) { for (final Observable<Object, JsonObject> jsonObjectObservable : topicObservableMap.values()) { jsonObjectObservable.shutdown(); } topicObservableMap.clear(); resetConnection(); } } }
Java
#include "gitrepository.h" #include <qtcacheexception.h> #include <git2.h> inline void git_eval(int err){ if (err) { const git_error* err = giterr_last(); throw QtC::QtCacheException(err->message); } } template<typename T> class git_auto { public: git_auto(T* object = NULL) : ref(object) {} ~git_auto(); operator T*() const { return ref; } T** operator &() {return &ref; } private: T* ref; }; git_auto<git_repository>::~git_auto() { git_repository_free(this->ref); } git_auto<git_signature>::~git_auto() { git_signature_free(this->ref); } git_auto<git_index>::~git_auto() { git_index_free(this->ref); } git_auto<git_tree>::~git_auto() { git_tree_free(this->ref); } git_auto<git_reference>::~git_auto() { git_reference_free(this->ref); } git_auto<git_commit>::~git_auto() { git_commit_free(this->ref); } git_auto<git_status_list>::~git_auto() { git_status_list_free(this->ref); } git_auto<git_remote>::~git_auto() { if (this->ref && git_remote_connected(this->ref)) { git_remote_disconnect(this->ref); } git_remote_free(this->ref); } GitRepository::GitRepository(const QString &localDirPath) : m_local_dir_path(localDirPath), m_repo(NULL), m_signature(NULL) { git_libgit2_init(); } GitRepository::~GitRepository() { if (NULL != m_signature) { git_signature_free(m_signature); } if (NULL != m_repo) { git_repository_free(m_repo); } git_libgit2_shutdown(); } bool GitRepository::isOpen() { return NULL != m_repo; } void GitRepository::setRepository(git_repository* repo) { if (NULL != m_repo){ git_repository_free(m_repo); } m_repo = repo; } git_repository* GitRepository::repository() { if (NULL == m_repo){ try{ open(); }catch(...){ try{ init(); }catch(...){ throw; } } } return m_repo; } void GitRepository::open() { git_repository* repo = NULL; git_eval(git_repository_open(&repo, m_local_dir_path.absolutePath().toLocal8Bit())); setRepository(repo); } void GitRepository::init() { git_repository* repo = NULL; git_repository_init_options initopts = GIT_REPOSITORY_INIT_OPTIONS_INIT; initopts.flags = GIT_REPOSITORY_INIT_MKPATH; git_eval(git_repository_init_ext(&repo, m_local_dir_path.absolutePath().toLocal8Bit(), &initopts)); git_auto<git_index> index; git_eval(git_repository_index(&index, repo)); git_oid tree_id; git_eval(git_index_write_tree(&tree_id, index)); git_auto<git_tree> tree; git_eval(git_tree_lookup(&tree, repo, &tree_id)); git_oid commit_id; git_eval(git_commit_create_v(&commit_id, repo, "HEAD", signature(), signature(), NULL, "Initial commit", tree, 0)); setRepository(repo); } void GitRepository::branch(const QString& name) { git_repository* repo = repository(); git_auto<git_reference> branch; int err = git_branch_lookup(&branch, repo, name.toLatin1(), GIT_BRANCH_LOCAL); if (err == GIT_ENOTFOUND){ git_oid parent_id; git_auto<git_commit> parent; git_eval(git_reference_name_to_id(&parent_id, repo, "HEAD")); git_eval(git_commit_lookup(&parent, repo, &parent_id)); git_eval(git_branch_create(&branch, repo, name.toLocal8Bit(), parent, 1)); }else{ git_eval(err); } git_eval(git_repository_set_head(repo, git_reference_name(branch))); git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT; opts.checkout_strategy = GIT_CHECKOUT_FORCE; git_eval(git_checkout_head(repo, &opts)); } void GitRepository::add(const QString& filepath) { git_repository* repo = repository(); git_auto<git_index> index; git_eval(git_repository_index(&index, repo)); git_eval(git_index_add_bypath(index, filepath.toLatin1())); git_index_write(index); git_index_free(index); } void GitRepository::commit(const QString& message) { git_repository* repo = repository(); { git_auto<git_status_list> changes; git_eval(git_status_list_new(&changes, repo, NULL)); if (git_status_list_entrycount(changes) == 0) { return; } } git_auto<git_index> index; git_eval(git_repository_index(&index, repo)); git_oid tree_id; git_eval(git_index_write_tree(&tree_id, index)); git_auto<git_tree> tree; git_eval(git_tree_lookup(&tree, repo, &tree_id)); git_oid parent_id; git_eval(git_reference_name_to_id(&parent_id, repo, "HEAD")); git_auto<git_commit> parent; git_eval(git_commit_lookup(&parent, repo, &parent_id)); git_oid commit_id; git_signature* sig = signature(); git_eval(git_commit_create_v(&commit_id, repo, "HEAD", sig, sig, NULL, message.toLocal8Bit(), tree, 1, parent)); } void GitRepository::clone(const QString& url) { git_repository* repo = NULL; git_clone_options opts = GIT_CLONE_OPTIONS_INIT; opts.checkout_branch = "master"; git_eval(git_clone(&repo, url.toLatin1(), m_local_dir_path.absolutePath().toLocal8Bit(), &opts)); setRepository(repo); } void GitRepository::push() { git_repository* repo = repository(); const char* remote_name = "origin"; git_auto<git_remote> remote; git_eval(git_remote_lookup(&remote, repo, remote_name)); git_eval(git_remote_connect(remote, GIT_DIRECTION_PUSH, NULL, NULL)); git_auto<git_reference> head; git_eval(git_repository_head(&head, repo)); QString refname = QString("+%1:%1").arg(git_reference_name(head)); git_eval(git_remote_add_push(repo, remote_name, refname.toLatin1())); git_eval(git_remote_upload(remote, NULL, NULL)); } void GitRepository::fetch() { git_repository* repo = repository(); const char* remote_name = "origin"; git_auto<git_remote> remote; git_eval(git_remote_lookup(&remote, repo, remote_name)); git_eval(git_remote_connect(remote, GIT_DIRECTION_FETCH, NULL, NULL)); git_eval(git_remote_fetch(remote, NULL, NULL, NULL)); } void GitRepository::setSignature(const QString& authorName, const QString& authorEmail) { git_signature* sig = m_signature; if (sig) { git_signature_free(sig); } git_eval(git_signature_now(&sig, authorName.toLocal8Bit(), authorEmail.toLocal8Bit())); m_signature = sig; } git_signature* GitRepository::signature() { if (!m_signature) { setSignature(); } return m_signature; }
Java
/* * SonarLint for Visual Studio * Copyright (C) 2016-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using SonarLint.VisualStudio.Progress.Controller; namespace SonarLint.VisualStudio.Progress.UnitTests { /// <summary> /// Partial class implementation of <see cref="IProgressStepExecutionEvents"/> /// </summary> public partial class ConfigurableProgressController : IProgressStepExecutionEvents { void IProgressStepExecutionEvents.ProgressChanged(string progressDetailText, double progress) { this.progressChanges.Add(Tuple.Create(progressDetailText, progress)); } } }
Java
<?php /** * @copyright Copyright (c) Metaways Infosystems GmbH, 2011 * @license LGPLv3, http://www.arcavias.com/en/license * @package MShop * @subpackage Common */ /** * Common interface for items that carry sorting informations. * * @package MShop * @subpackage Common */ interface MShop_Common_Item_Position_Interface { /** * Returns the position of the item in the list. * * @return integer Position of the item in the list */ public function getPosition(); /** * Sets the new position of the item in the list. * * @param integer $pos position of the item in the list * @return void */ public function setPosition( $pos ); }
Java
#!/bin/zsh export PATH="${HOME}/bin:${HOME}/script:${PATH}" export HISTSIZE=1000000 if [[ -z "${HOSTNAME}" ]] ; then export HOSTNAME="${HOST:-$(hostname)}" fi if [[ -d "${MYSHELL}/plugins" ]]; then for i in "${MYSHELL}/plugins/"* ; do source "${i}" done fi function prompt_char() { if [ $UID -eq 0 ]; then echo "#"; else echo $; fi } local ret_status="%(?:%{$fg_bold[green]%}$(prompt_char) :%{$fg_bold[red]%}$(prompt_char) %s)" PROMPT='%(!.%{$fg_bold[red]%}.%{$fg_bold[red]%}%m%{$fg_bold[green]%} )%n %{$fg_bold[blue]%}%(!.%1~.%~) $(git_prompt_info)%_${ret_status}%{$reset_color%}' ZSH_THEME_GIT_PROMPT_PREFIX="(%{$fg[red]%}" ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}" ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[blue]%}%{$fg[yellow]%}*%{$fg[blue]%}) " ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[blue]%}) " lsopt="-F" dfopt="-h" if [ -x /usr/bin/dircolors ]; then lsopt="${lsopt} --color=auto" alias grep='grep --color=auto' fi if [[ "$(uname)" == "FreeBSD" ]] || [[ "$(uname)" == "Darwin" ]] ; then lsopt="${lsopt} -GF" else lshelp="$(ls --help)" [ "$(grep -- "--show-control-chars" <<<"${lshelp}")" ] && \ lsopt="${lsopt} --show-control-chars" [ "$(grep -- "--group-directories-first" <<<"${lshelp}")" ] && \ lsopt="${lsopt} --group-directories-first" dfopt="${dfopt} -T -x supermount" fi alias l="ls ${lsopt}" alias la='l -a' alias l1='l -1' alias ll='l -l' alias lla='l -la' alias lsd='l -d */' alias df="df ${dfopt}" unset lshelp lsopt dfopt alias ssu='sudo -H bash --rcfile "${HOME}/.bashrc"' alias myip='dig +short myip.opendns.com @resolver1.opendns.com || wget -qO /dev/stdout "http://icanhazip.com" || curl -s "http://icanhazip.com"' if (( $+commands[ssh] )) ; then alias ssh='ssh -oStrictHostKeyChecking=no' alias ssht='ssh tsaikd@home.tsaikd.org' fi if (( $+commands[vim] )) ; then export EDITOR="${EDITOR:-vim}" fi if (( $+commands[direnv] )) ; then eval "$(direnv hook zsh)" fi if (( $+commands[docker] )) ; then alias dklog="docker logs -f" alias dkre="docker restart -t 0" fi if (( $+commands[gitk] )) ; then alias gitk='gitk --all &' fi if [[ "${TERM}" == "xterm" ]] ; then if (( $+commands[tmux] )) ; then if [[ -z "${TMUX}" ]] ; then tmux attach || tmux fi elif (( $+commands[screen] )) ; then screen -wipe screen -x "$(whoami)" || screen -S "$(whoami)" elif [ "$(uname -s)" != "Darwin" ] ; then [ "$(id -u)" -ne 0 ] && [ -n "$(type -p last)" ] && last -5 fi elif [ "$(uname -s)" != "Darwin" ] ; then [ "$(id -u)" -ne 0 ] && [ -n "$(type -p last)" ] && last -5 fi if (( $+functions[kube_ps1] )); then KUBE_PS1_SUFFIX=") " PROMPT='$(kube_ps1)'${PROMPT} fi # load custom script post login if [ -d "${MYSHELL}/custom/zsh/login-post" ] ; then for i in $(find "${MYSHELL}/custom/zsh/login-post" -iname \*.zsh) ; do source "${i}" done fi [ -f "${HOME}/.zshrc.local" ] && \ source "${HOME}/.zshrc.local" unset i
Java
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- qdeclarativefontloader.cpp --> <title>Qt 4.7: List of All Members for FontLoader</title> <link rel="stylesheet" type="text/css" href="style/offline.css" /> </head> <body> <div class="header" id="qtdocheader"> <div class="content"> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> </div> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> <li><a href="qdeclarativeelements.html">QML Elements</a></li> <li>List of All Members for FontLoader</li> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">List of All Members for FontLoader</h1> <p>This is the complete list of members for <a href="qml-fontloader.html">QML FontLoader Element</a>, including inherited members.</p> <ul> <li class="fn"><span class="name"><b><a href="qml-fontloader.html#name-prop">name</a></b></span></li> <li class="fn"><span class="name"><b><a href="qml-fontloader.html#source-prop">source</a></b></span></li> <li class="fn"><span class="name"><b><a href="qml-fontloader.html#status-prop">status</a></b></span></li> </ul> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2011 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> </body> </html>
Java
#!/bin/sh #cabal install msgpack-rpc ghc --make ping.hs
Java
create schema if not exists toughradius collate utf8mb4_unicode_ci; CREATE USER IF NOT EXISTS raduser@'172.%.%.%' identified by 'radpwd'; GRANT ALL PRIVILEGES ON toughradius.* TO raduser@'172.%.%.%'; ALTER USER 'raduser'@'172.%.%.%' IDENTIFIED WITH mysql_native_password BY 'radpwd'; use toughradius; create table if not exists tr_bras ( id bigint auto_increment primary key, identifier varchar(128) null, name varchar(64) not null, ipaddr varchar(32) null, vendor_id varchar(32) not null, portal_vendor varchar(32) not null, secret varchar(64) not null, coa_port int not null, ac_port int not null, auth_limit int null, acct_limit int null, status enum('enabled', 'disabled') null, remark varchar(512) null, create_time datetime not null ); create index ix_tr_bras_identifier on tr_bras (identifier); create index ix_tr_bras_ipaddr on tr_bras (ipaddr); create table if not exists tr_config ( id bigint auto_increment primary key, type varchar(32) not null, name varchar(128) not null, value varchar(255) null, remark varchar(255) null ); create table if not exists tr_subscribe ( id bigint auto_increment primary key, node_id bigint default 0 not null, subscriber varchar(32) null, realname varchar(32) null, password varchar(128) not null, domain varchar(128) null, addr_pool varchar(128) null, policy varchar(512) null, is_online int null, active_num int null, bind_mac tinyint(1) null, bind_vlan tinyint(1) null, ip_addr varchar(32) null, mac_addr varchar(32) null, in_vlan int null, out_vlan int null, up_rate bigint null, down_rate bigint null, up_peak_rate bigint null, down_peak_rate bigint null, up_rate_code varchar(32) null, down_rate_code varchar(32) null, status enum('enabled', 'disabled') null, remark varchar(512) null, begin_time datetime not null, expire_time datetime not null, create_time datetime not null, update_time datetime null ); create index ix_tr_subscribe_create_time on tr_subscribe (create_time); create index ix_tr_subscribe_expire_time on tr_subscribe (expire_time); create index ix_tr_subscribe_status on tr_subscribe (status); create index ix_tr_subscribe_subscriber on tr_subscribe (subscriber); create index ix_tr_subscribe_update_time on tr_subscribe (update_time); use toughradius; INSERT INTO toughradius.tr_bras (identifier, name, ipaddr, vendor_id, portal_vendor,secret, coa_port,ac_port, auth_limit, acct_limit, STATUS, remark, create_time) VALUES ('radius-tester', 'radius-tester', '127.0.0.1', '14988',"cmccv1", 'secret', 3799,2000, 1000, 1000, NULL, '0', '2019-03-01 14:07:46'); INSERT INTO toughradius.tr_subscribe (node_id, subscriber, realname, password, domain, addr_pool, policy, is_online, active_num, bind_mac, bind_vlan, ip_addr, mac_addr, in_vlan, out_vlan, up_rate, down_rate, up_peak_rate, down_peak_rate, up_rate_code, down_rate_code, status, remark, begin_time, expire_time, create_time, update_time) VALUES (0, 'test01', '', '888888', null, null, null, null, 10, 0, 0, '', '', 0, 0, 10.000, 10.000, 100.000, 100.000, '10', '10', 'enabled', '', '2019-03-01 14:13:02', '2019-03-01 14:13:00', '2019-03-01 14:12:59', '2019-03-01 14:12:56');
Java
/* * ===================================================================================== * * Filename: select-sort.c * * Description: * * Version: 1.0 * Created: 12/23/2016 04:47:42 PM * Revision: none * Compiler: gcc * * Author: YOUR NAME (), * Organization: * * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> int icomp = 0; int iswap = 0; int cmp_fun(int a, int b) { icomp++; return a > b; } int swap(int * a, int * b) { *a = *a ^ *b; *b = *a ^ *b; *a = *a ^ *b; iswap ++; return 1; } int select_sort(int *pList, int len) { if(NULL == pList || len < 0) { return -1; } int i = 0; for(i = 0; i < len; i++) { int iTop = pList[i]; int iPos = i; int j = 0; for(j = i + 1; j < len; j++) { if(cmp_fun(iTop, pList[j])) { iTop = pList[j]; iPos = j; } } if(i != iPos) { swap(&pList[i], &pList[iPos]); } } return 0; } int get_list(int *list, int len) { srand(374676); int i = 0; for(i = 0; i < len; i++) { list[i] = rand() % (len * 20); } return 0; } int check_list(int *list, int len) { int i; int iCnt = 0; for(i = 0; i < len - 1; i++) { if(cmp_fun(list[i], list[i + 1])) { iCnt++; } } return iCnt; } void show_list(int *pList, int len) { int i = 0; for(i = 0; i < len; i++) { printf("%d ", pList[i]); } printf("\n"); } int test_sort(int n) { icomp = 0; iswap = 0; int *pList = (int*)malloc(sizeof(int) * n); get_list(pList, n); //show_list(pList, n); select_sort(pList, n); int iThro = n * (n + 1) / 2; printf("n = %d, tcmp = %d, rcmp = %d, dc = %lf\n", n, iThro, icomp, (double)icomp / iThro); printf("n = %d, tswp = %d, rswp = %d, ds = %lf\n", n, n - 1, iswap, (double)iswap / (n - 1)); int iT = check_list(pList, n); if(iT) { printf("sort faild, [%d]\n", iT); } //show_list(pList, n); free(pList); printf("\n"); return 0; } int main() { int i = 0; for(i = 16; i <= 1024 * 16; i *= 2) { test_sort(i); } return 0; }
Java
## Welcome to GitHub Pages You can use the [editor on GitHub](https://github.com/ldscholar/ldscholar.github.io/edit/master/README.md) to maintain and preview the content for your website in Markdown files. Whenever you commit to this repository, GitHub Pages will run [Jekyll](https://jekyllrb.com/) to rebuild the pages in your site, from the content in your Markdown files. ### Markdown Markdown is a lightweight and easy-to-use syntax for styling your writing. It includes conventions for ```markdown Syntax highlighted code block # Header 1 ## Header 2 ### Header 3 - Bulleted - List 1. Numbered 2. List **Bold** and _Italic_ and `Code` text [Link](url) and ![Image](src) ``` For more details see [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/). ### Jekyll Themes Your Pages site will use the layout and styles from the Jekyll theme you have selected in your [repository settings](https://github.com/ldscholar/ldscholar.github.io/settings). The name of this theme is saved in the Jekyll `_config.yml` configuration file. ### Support or Contact Having trouble with Pages? Check out our [documentation](https://help.github.com/categories/github-pages-basics/) or [contact support](https://github.com/contact) and we’ll help you sort it out.
Java
#include "StructuralInterface.h" StructuralInterface::StructuralInterface (StructuralEntity *parent) : StructuralEntity (parent) { setCategory (Structural::Interface); setStructuralType (Structural::NoType); setResizable (false); setTop (0); setLeft (0); setWidth (ST_DEFAULT_INTERFACE_W); setHeight (ST_DEFAULT_INTERFACE_H); if (!ST_OPT_SHOW_INTERFACES) setHidden (true); } void StructuralInterface::adjust (bool collision, bool recursion) { StructuralEntity::adjust (collision, recursion); // Adjusting position... StructuralEntity *parent = structuralParent (); if (parent || !ST_OPT_WITH_BODY) { if (!collision) { // Tries (10x) to find a position where there is no collision with others // relatives for (int i = 0; i < 10; i++) { bool colliding = false; for (StructuralEntity *ent : StructuralUtil::neighbors (this)) { if (ent != this) { int n = 0, max = 1000; qreal current = 0.0; ent->setSelectable (false); while (collidesWithItem (ent, Qt::IntersectsItemBoundingRect)) { QLineF line = QLineF (left () + width () / 2, top () + height () / 2, ent->width () / 2, ent->height () / 2); line.setAngle (qrand () % 360); current += (double)(qrand () % 100) / 1000.0; setTop (top () + line.pointAt (current / 2).y () - line.p1 ().y ()); setLeft (left () + line.pointAt (current / 2).x () - line.p1 ().x ()); if (++n > max) break; } constrain (); ent->setSelectable (true); } } for (StructuralEntity *ent : StructuralUtil::neighbors (this)) if (collidesWithItem (ent, Qt::IntersectsItemBoundingRect)) colliding = true; if (!colliding) break; } } constrain (); StructuralUtil::adjustEdges (this); } } void StructuralInterface::constrain () { StructuralEntity *parent = structuralParent (); if (parent != nullptr) { QPointF tail (parent->width () / 2, parent->height () / 2); QPointF head (left () + width () / 2, top () + height () / 2); if (tail == head) { head.setX (tail.x ()); head.setY (tail.y () - 10); } QPointF p = head; QLineF line (tail, head); bool status = true; qreal current = 1.0; qreal step = 0.01; if (!parent->contains (p)) { step = -0.01; status = false; } do { current += step; p = line.pointAt (current); } while (parent->contains (p) == status); if (QLineF (p, head).length () > 7) { setTop (p.y () - height () / 2); setLeft (p.x () - width () / 2); } } } void StructuralInterface::draw (QPainter *painter) { int x = ST_DEFAULT_ENTITY_PADDING + ST_DEFAULT_INTERFACE_PADDING; int y = ST_DEFAULT_ENTITY_PADDING + ST_DEFAULT_INTERFACE_PADDING; int w = width () - 2 * ST_DEFAULT_INTERFACE_PADDING; int h = height () - 2 * ST_DEFAULT_INTERFACE_PADDING; painter->drawPixmap (x, y, w, h, QPixmap (StructuralUtil::icon (structuralType ()))); if (!ST_OPT_WITH_BODY && !ST_OPT_USE_FLOATING_INTERFACES) { if (property (ST_ATTR_ENT_AUTOSTART) == ST_VALUE_TRUE) { painter->setPen (QPen (QBrush (QColor (76, 76, 76)), 2)); painter->drawRect (x, y, w, h); } } if (!error ().isEmpty () || !warning ().isEmpty ()) { QString icon; if (!error ().isEmpty ()) icon = QString (ST_DEFAULT_ALERT_ERROR_ICON); else icon = QString (ST_DEFAULT_ALERT_WARNING_ICON); painter->drawPixmap (x + w / 2 - (ST_DEFAULT_ALERT_ICON_W - 3) / 2, y + h / 2 - (ST_DEFAULT_ALERT_ICON_H - 3) / 2, ST_DEFAULT_ALERT_ICON_W - 3, ST_DEFAULT_ALERT_ICON_H - 3, QPixmap (icon)); } if (isMoving ()) { painter->setBrush (QBrush (Qt::NoBrush)); painter->setPen (QPen (QBrush (Qt::black), 0)); int moveX = x + moveLeft () - left (); int moveY = y + moveTop () - top (); int moveW = w; int moveH = h; painter->drawRect (moveX, moveY, moveW, moveH); } }
Java
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.server.authentication; import javax.annotation.concurrent.Immutable; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang.StringUtils.isNotBlank; /** * Display information provided by the Identity Provider to be displayed into the login form. * * @since 5.4 */ @Immutable public final class Display { private final String iconPath; private final String backgroundColor; private Display(Builder builder) { this.iconPath = builder.iconPath; this.backgroundColor = builder.backgroundColor; } /** * URL path to the provider icon, as deployed at runtime, for example "/static/authgithub/github.svg" (in this * case "authgithub" is the plugin key. Source file is "src/main/resources/static/github.svg"). * It can also be an external URL, for example "http://www.mydomain/myincon.png". * * Must not be blank. * <br> * The recommended format is SVG with a size of 24x24 pixels. * Other supported format is PNG, with a size of 40x40 pixels. */ public String getIconPath() { return iconPath; } /** * Background color for the provider button displayed in the login form. * It's a Hexadecimal value, for instance #205081. * <br> * If not provided, the default value is #236a97 */ public String getBackgroundColor() { return backgroundColor; } public static Builder builder() { return new Builder(); } public static class Builder { private String iconPath; private String backgroundColor = "#236a97"; private Builder() { } /** * @see Display#getIconPath() */ public Builder setIconPath(String iconPath) { this.iconPath = iconPath; return this; } /** * @see Display#getBackgroundColor() */ public Builder setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; return this; } public Display build() { checkArgument(isNotBlank(iconPath), "Icon path must not be blank"); validateBackgroundColor(); return new Display(this); } private void validateBackgroundColor() { checkArgument(isNotBlank(backgroundColor), "Background color must not be blank"); checkArgument(backgroundColor.length() == 7 && backgroundColor.indexOf('#') == 0, "Background color must begin with a sharp followed by 6 characters"); } } }
Java
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\thread; use pocketmine\scheduler\AsyncTask; use const PTHREADS_INHERIT_NONE; /** * Specialized Worker class for PocketMine-MP-related use cases. It handles setting up autoloading and error handling. * * Workers are a special type of thread which execute tasks passed to them during their lifetime. Since creating a new * thread has a high resource cost, workers can be kept around and reused for lots of short-lived tasks. * * As a plugin developer, you'll rarely (if ever) actually need to use this class directly. * If you want to run tasks on other CPU cores, check out AsyncTask first. * @see AsyncTask */ abstract class Worker extends \Worker{ use CommonThreadPartsTrait; public function start(int $options = PTHREADS_INHERIT_NONE) : bool{ //this is intentionally not traitified ThreadManager::getInstance()->add($this); if($this->getClassLoaders() === null){ $this->setClassLoaders(); } return parent::start($options); } /** * Stops the thread using the best way possible. Try to stop it yourself before calling this. */ public function quit() : void{ $this->isKilled = true; if(!$this->isShutdown()){ while($this->unstack() !== null); $this->notify(); $this->shutdown(); } ThreadManager::getInstance()->remove($this); } }
Java
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.computation.step; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.codec.digest.DigestUtils; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import org.sonar.api.utils.System2; import org.sonar.batch.protocol.output.BatchReport; import org.sonar.core.persistence.DbSession; import org.sonar.core.persistence.MyBatis; import org.sonar.core.source.db.FileSourceDto; import org.sonar.core.source.db.FileSourceDto.Type; import org.sonar.server.computation.batch.BatchReportReader; import org.sonar.server.computation.component.Component; import org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor; import org.sonar.server.computation.component.TreeRootHolder; import org.sonar.server.computation.source.ComputeFileSourceData; import org.sonar.server.computation.source.CoverageLineReader; import org.sonar.server.computation.source.DuplicationLineReader; import org.sonar.server.computation.source.HighlightingLineReader; import org.sonar.server.computation.source.LineReader; import org.sonar.server.computation.source.ScmLineReader; import org.sonar.server.computation.source.SymbolsLineReader; import org.sonar.server.db.DbClient; import org.sonar.server.source.db.FileSourceDb; import org.sonar.server.util.CloseableIterator; import static org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor.Order.PRE_ORDER; public class PersistFileSourcesStep implements ComputationStep { private final DbClient dbClient; private final System2 system2; private final TreeRootHolder treeRootHolder; private final BatchReportReader reportReader; public PersistFileSourcesStep(DbClient dbClient, System2 system2, TreeRootHolder treeRootHolder, BatchReportReader reportReader) { this.dbClient = dbClient; this.system2 = system2; this.treeRootHolder = treeRootHolder; this.reportReader = reportReader; } @Override public void execute() { // Don't use batch insert for file_sources since keeping all data in memory can produce OOM for big files DbSession session = dbClient.openSession(false); try { new FileSourceVisitor(session).visit(treeRootHolder.getRoot()); } finally { MyBatis.closeQuietly(session); } } private class FileSourceVisitor extends DepthTraversalTypeAwareVisitor { private final DbSession session; private Map<String, FileSourceDto> previousFileSourcesByUuid = new HashMap<>(); private String projectUuid; private FileSourceVisitor(DbSession session) { super(Component.Type.FILE, PRE_ORDER); this.session = session; } @Override public void visitProject(Component project) { this.projectUuid = project.getUuid(); session.select("org.sonar.core.source.db.FileSourceMapper.selectHashesForProject", ImmutableMap.of("projectUuid", projectUuid, "dataType", Type.SOURCE), new ResultHandler() { @Override public void handleResult(ResultContext context) { FileSourceDto dto = (FileSourceDto) context.getResultObject(); previousFileSourcesByUuid.put(dto.getFileUuid(), dto); } }); } @Override public void visitFile(Component file) { int fileRef = file.getRef(); BatchReport.Component component = reportReader.readComponent(fileRef); CloseableIterator<String> linesIterator = reportReader.readFileSource(fileRef); LineReaders lineReaders = new LineReaders(reportReader, fileRef); try { ComputeFileSourceData computeFileSourceData = new ComputeFileSourceData(linesIterator, lineReaders.readers(), component.getLines()); ComputeFileSourceData.Data fileSourceData = computeFileSourceData.compute(); persistSource(fileSourceData, file.getUuid()); } catch (Exception e) { throw new IllegalStateException(String.format("Cannot persist sources of %s", file.getKey()), e); } finally { linesIterator.close(); lineReaders.close(); } } private void persistSource(ComputeFileSourceData.Data fileSourceData, String componentUuid) { FileSourceDb.Data fileData = fileSourceData.getFileSourceData(); byte[] data = FileSourceDto.encodeSourceData(fileData); String dataHash = DigestUtils.md5Hex(data); String srcHash = fileSourceData.getSrcHash(); String lineHashes = fileSourceData.getLineHashes(); FileSourceDto previousDto = previousFileSourcesByUuid.get(componentUuid); if (previousDto == null) { FileSourceDto dto = new FileSourceDto() .setProjectUuid(projectUuid) .setFileUuid(componentUuid) .setDataType(Type.SOURCE) .setBinaryData(data) .setSrcHash(srcHash) .setDataHash(dataHash) .setLineHashes(lineHashes) .setCreatedAt(system2.now()) .setUpdatedAt(system2.now()); dbClient.fileSourceDao().insert(session, dto); session.commit(); } else { // Update only if data_hash has changed or if src_hash is missing (progressive migration) boolean binaryDataUpdated = !dataHash.equals(previousDto.getDataHash()); boolean srcHashUpdated = !srcHash.equals(previousDto.getSrcHash()); if (binaryDataUpdated || srcHashUpdated) { previousDto .setBinaryData(data) .setDataHash(dataHash) .setSrcHash(srcHash) .setLineHashes(lineHashes); // Optimization only change updated at when updating binary data to avoid unnecessary indexation by E/S if (binaryDataUpdated) { previousDto.setUpdatedAt(system2.now()); } dbClient.fileSourceDao().update(previousDto); session.commit(); } } } } private static class LineReaders { private final List<LineReader> readers = new ArrayList<>(); private final List<CloseableIterator<?>> iterators = new ArrayList<>(); LineReaders(BatchReportReader reportReader, int componentRef) { CloseableIterator<BatchReport.Coverage> coverageReportIterator = reportReader.readComponentCoverage(componentRef); BatchReport.Changesets scmReport = reportReader.readChangesets(componentRef); CloseableIterator<BatchReport.SyntaxHighlighting> highlightingIterator = reportReader.readComponentSyntaxHighlighting(componentRef); List<BatchReport.Symbols.Symbol> symbols = reportReader.readComponentSymbols(componentRef); List<BatchReport.Duplication> duplications = reportReader.readComponentDuplications(componentRef); if (coverageReportIterator != null) { iterators.add(coverageReportIterator); readers.add(new CoverageLineReader(coverageReportIterator)); } if (scmReport != null) { readers.add(new ScmLineReader(scmReport)); } if (highlightingIterator != null) { iterators.add(highlightingIterator); readers.add(new HighlightingLineReader(highlightingIterator)); } if (!duplications.isEmpty()) { readers.add(new DuplicationLineReader(duplications)); } if (!symbols.isEmpty()) { readers.add(new SymbolsLineReader(symbols)); } } List<LineReader> readers() { return readers; } void close() { for (CloseableIterator<?> reportIterator : iterators) { reportIterator.close(); } } } @Override public String getDescription() { return "Persist file sources"; } }
Java
package com.wangdaye.common.base.fragment; import com.wangdaye.common.base.activity.LoadableActivity; import java.util.List; /** * Loadable fragment. * */ public abstract class LoadableFragment<T> extends MysplashFragment { /** * {@link LoadableActivity#loadMoreData(List, int, boolean)}. * */ public abstract List<T> loadMoreData(List<T> list, int headIndex, boolean headDirection); }
Java
/* ========================================================================== */ /* === SuiteSparse_config =================================================== */ /* ========================================================================== */ /* Configuration file for SuiteSparse: a Suite of Sparse matrix packages * (AMD, COLAMD, CCOLAMD, CAMD, CHOLMOD, UMFPACK, CXSparse, and others). * * SuiteSparse_config.h provides the definition of the long integer. On most * systems, a C program can be compiled in LP64 mode, in which long's and * pointers are both 64-bits, and int's are 32-bits. Windows 64, however, uses * the LLP64 model, in which int's and long's are 32-bits, and long long's and * pointers are 64-bits. * * SuiteSparse packages that include long integer versions are * intended for the LP64 mode. However, as a workaround for Windows 64 * (and perhaps other systems), the long integer can be redefined. * * If _WIN64 is defined, then the __int64 type is used instead of long. * * The long integer can also be defined at compile time. For example, this * could be added to SuiteSparse_config.mk: * * CFLAGS = -O -D'SuiteSparse_long=long long' \ * -D'SuiteSparse_long_max=9223372036854775801' -D'SuiteSparse_long_idd="lld"' * * This file defines SuiteSparse_long as either long (on all but _WIN64) or * __int64 on Windows 64. The intent is that a SuiteSparse_long is always a * 64-bit integer in a 64-bit code. ptrdiff_t might be a better choice than * long; it is always the same size as a pointer. * * This file also defines the SUITESPARSE_VERSION and related definitions. * * Copyright (c) 2012, Timothy A. Davis. No licensing restrictions apply * to this file or to the SuiteSparse_config directory. * Author: Timothy A. Davis. */ #ifndef _SUITESPARSECONFIG_H #define _SUITESPARSECONFIG_H #ifdef __cplusplus extern "C" { #endif #include <limits.h> #include <stdlib.h> /* ========================================================================== */ /* === SuiteSparse_long ===================================================== */ /* ========================================================================== */ #ifndef SuiteSparse_long #ifdef _WIN64 #define SuiteSparse_long __int64 #define SuiteSparse_long_max _I64_MAX #define SuiteSparse_long_idd "I64d" #else #define SuiteSparse_long long #define SuiteSparse_long_max LONG_MAX #define SuiteSparse_long_idd "ld" #endif #define SuiteSparse_long_id "%" SuiteSparse_long_idd #endif /* For backward compatibility with prior versions of SuiteSparse. The UF_* * macros are deprecated and will be removed in a future version. */ #ifndef UF_long #define UF_long SuiteSparse_long #define UF_long_max SuiteSparse_long_max #define UF_long_idd SuiteSparse_long_idd #define UF_long_id SuiteSparse_long_id #endif /* ========================================================================== */ /* === SuiteSparse_config parameters and functions ========================== */ /* ========================================================================== */ /* SuiteSparse-wide parameters will be placed in this struct. */ typedef struct SuiteSparse_config_struct { void *(*malloc_memory) (size_t) ; /* pointer to malloc */ void *(*realloc_memory) (void *, size_t) ; /* pointer to realloc */ void (*free_memory) (void *) ; /* pointer to free */ void *(*calloc_memory) (size_t, size_t) ; /* pointer to calloc */ } SuiteSparse_config ; void *SuiteSparse_malloc /* pointer to allocated block of memory */ ( size_t nitems, /* number of items to malloc (>=1 is enforced) */ size_t size_of_item, /* sizeof each item */ int *ok, /* TRUE if successful, FALSE otherwise */ SuiteSparse_config *config /* SuiteSparse-wide configuration */ ) ; void *SuiteSparse_free /* always returns NULL */ ( void *p, /* block to free */ SuiteSparse_config *config /* SuiteSparse-wide configuration */ ) ; void SuiteSparse_tic /* start the timer */ ( double tic [2] /* output, contents undefined on input */ ) ; double SuiteSparse_toc /* return time in seconds since last tic */ ( double tic [2] /* input: from last call to SuiteSparse_tic */ ) ; double SuiteSparse_time /* returns current wall clock time in seconds */ ( void ) ; /* determine which timer to use, if any */ #ifndef NTIMER #ifdef _POSIX_C_SOURCE #if _POSIX_C_SOURCE >= 199309L #define SUITESPARSE_TIMER_ENABLED #endif #endif #endif /* ========================================================================== */ /* === SuiteSparse version ================================================== */ /* ========================================================================== */ /* SuiteSparse is not a package itself, but a collection of packages, some of * which must be used together (UMFPACK requires AMD, CHOLMOD requires AMD, * COLAMD, CAMD, and CCOLAMD, etc). A version number is provided here for the * collection itself. The versions of packages within each version of * SuiteSparse are meant to work together. Combining one packge from one * version of SuiteSparse, with another package from another version of * SuiteSparse, may or may not work. * * SuiteSparse contains the following packages: * * SuiteSparse_config version 4.0.0 (version always the same as SuiteSparse) * AMD version 2.3.0 * BTF version 1.2.0 * CAMD version 2.3.0 * CCOLAMD version 2.8.0 * CHOLMOD version 2.0.0 * COLAMD version 2.8.0 * CSparse version 3.1.0 * CXSparse version 3.1.0 * KLU version 1.2.0 * LDL version 2.1.0 * RBio version 2.1.0 * SPQR version 1.3.0 (full name is SuiteSparseQR) * UMFPACK version 5.6.0 * MATLAB_Tools various packages & M-files * * Other package dependencies: * BLAS required by CHOLMOD and UMFPACK * LAPACK required by CHOLMOD * METIS 4.0.1 required by CHOLMOD (optional) and KLU (optional) */ #define SUITESPARSE_DATE "Jun 1, 2012" #define SUITESPARSE_VER_CODE(main,sub) ((main) * 1000 + (sub)) #define SUITESPARSE_MAIN_VERSION 4 #define SUITESPARSE_SUB_VERSION 0 #define SUITESPARSE_SUBSUB_VERSION 0 #define SUITESPARSE_VERSION \ SUITESPARSE_VER_CODE(SUITESPARSE_MAIN_VERSION,SUITESPARSE_SUB_VERSION) #ifdef __cplusplus } #endif #endif
Java
<?php if (!defined('TL_ROOT')) die('You can not access this file directly!'); /** * Contao Open Source CMS * Copyright (C) 2005-2012 Leo Feyer * * Formerly known as TYPOlight Open Source CMS. * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * 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, please visit the Free * Software Foundation website at <http://www.gnu.org/licenses/>. * * PHP version 5 * @copyright Roger Pau 2009 * @copyright Patricio F. Hamann 2010 * @copyright Juan José Olivera 2010 * @copyright Klaus Bogotz 2010 * @copyright Rogelio Jacinto 2011 * @copyright Jasmin S. 2012 * @author Patricio F. Hamann <hamannz@gmail.com> * @author Juan José Olivera <jota.jota.or@gmail.com> * @author Klaus Bogotz 2010 <klbogotz@gr7.org> * @author Rogelio Jacinto <rogelio.jacinto@gmail.com> * @author Jasmin S. <jasmin@faasmedia.com> * @package Spanish * @license LGPL * @filesource */ $GLOBALS['TL_LANG']['tl_newsletter_channel']['title'] = array('Título', 'Por favor introduce el título del canal'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['jumpTo'] = array('Saltar a página', 'Por favor seleccion la página a la que los visitantes serán redirigidos cuando seleccionen una newsletter.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['useSMTP'] = array('Servidor SMTP personalizado', 'Utilizar un servidor SMTP específico para enviar boletines.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtpHost'] = array('Nombre de servidor SMTP', 'Indique el nombre del servidor SMTP.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtpUser'] = array('Nombre de usuario SMTP', 'Permite indicar el nombre de usuario para identificarse con el servidor SMTP.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtpPass'] = array('Contraseña SMTP', 'Permite indicar la contraseña para identificarse con el servidor SMTP.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtpEnc'] = array('Cifrado SMTP', 'Aqui puedes seleccionar un método de cifrado (SSL o TLS).'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtpPort'] = array('Número de puerto SMTP', 'Indique el número de puerto del servidor SMTP.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['tstamp'] = array('Fecha de revisión', 'Fecha y hora de la última revisión'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['title_legend'] = 'Título y redirección'; $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtp_legend'] = 'Configuación SMTP'; $GLOBALS['TL_LANG']['tl_newsletter_channel']['new'] = array('Nuevo canal', 'Crear un canal nuevo'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['show'] = array('Detalles de canal', 'Mostrar los detalles del canal con ID %s'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['edit'] = array('Editar canal', 'Editar canal con ID %s'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['editheader'] = array('Editar ajustes de canal', 'Editar los ajsutes del canal con ID %s'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['copy'] = array('Copiar canal', 'Copiar canal con ID %s'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['delete'] = array('Eliminar canal', 'Eliminar cana con ID %s'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['recipients'] = array('Editar receptores', 'Editar los receptores del canal con ID %s'); ?>
Java
/*--- iGeo - http://igeo.jp Copyright (c) 2002-2013 Satoru Sugihara This file is part of iGeo. iGeo 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, version 3. iGeo 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 iGeo. If not, see <http://www.gnu.org/licenses/>. ---*/ package igeo; import java.awt.*; import igeo.gui.*; /** Class of point object. @author Satoru Sugihara */ public class IPoint extends IGeometry implements IVecI{ //public IVecI pos; public IVec pos; public IPoint(){ pos = new IVec(); initPoint(null); } public IPoint(IVec v){ pos = v; initPoint(null); } public IPoint(IVecI v){ pos = v.get(); initPoint(null); } public IPoint(double x, double y, double z){ pos = new IVec(x,y,z); initPoint(null); } public IPoint(double x, double y){ pos = new IVec(x,y); initPoint(null); } public IPoint(IServerI s){ super(s); pos = new IVec(0,0,0); initPoint(s); } public IPoint(IServerI s, IVec v){ super(s); pos = v; initPoint(s); } public IPoint(IServerI s, IVecI v){ super(s); pos = v.get(); initPoint(s); } public IPoint(IServerI s, double x, double y, double z){ super(s); pos = new IVec(x,y,z); initPoint(s); } public IPoint(IServerI s, double x, double y){ super(s); pos = new IVec(x,y); initPoint(s); } public IPoint(IPoint p){ super(p); pos = p.pos.dup(); initPoint(p.server); //setColor(p.getColor()); } public IPoint(IServerI s, IPoint p){ super(s,p); pos = p.pos.dup(); initPoint(s); //setColor(p.getColor()); } public /*protected*/ void initPoint(IServerI s){ if(pos==null){ IOut.err("null value is set in IPoint"); // return; } // // costly to use instanceof? //if(pos instanceof IVec) parameter = (IVec)pos; //else if(pos instanceof IVecR) parameter = (IVecR)pos; //else if(pos instanceof IVec4) parameter = (IVec4)pos; //else if(pos instanceof IVec4R) parameter = (IVec4R)pos; //addGraphic(new IPointGraphic(this)); if(graphics==null) initGraphic(s); // not init when using copy constructor } public IGraphicObject createGraphic(IGraphicMode m){ if(m.isNone()) return null; return new IPointGraphic(this); } synchronized public double x(){ return pos.x(); } synchronized public double y(){ return pos.y(); } synchronized public double z(){ return pos.z(); } synchronized public IPoint x(double vx){ pos.x(vx); return this; } synchronized public IPoint y(double vy){ pos.y(vy); return this; } synchronized public IPoint z(double vz){ pos.z(vz); return this; } synchronized public IPoint x(IDoubleI vx){ pos.x(vx); return this; } synchronized public IPoint y(IDoubleI vy){ pos.y(vy); return this; } synchronized public IPoint z(IDoubleI vz){ pos.z(vz); return this; } synchronized public IPoint x(IVecI vx){ pos.x(vx); return this; } synchronized public IPoint y(IVecI vy){ pos.y(vy); return this; } synchronized public IPoint z(IVecI vz){ pos.z(vz); return this; } synchronized public IPoint x(IVec2I vx){ pos.x(vx); return this; } synchronized public IPoint y(IVec2I vy){ pos.y(vy); return this; } synchronized public double x(ISwitchE e){ return pos.x(e); } synchronized public double y(ISwitchE e){ return pos.y(e); } synchronized public double z(ISwitchE e){ return pos.z(e); } synchronized public IDouble x(ISwitchR r){ return pos.x(r); } synchronized public IDouble y(ISwitchR r){ return pos.y(r); } synchronized public IDouble z(ISwitchR r){ return pos.z(r); } //synchronized public IVec get(){ return pos.get(); } // when pos is IVecI synchronized public IVec get(){ return pos; } /** passing position field */ synchronized public IVec pos(){ return pos; } /** center is same with position */ synchronized public IVec center(){ return pos(); } synchronized public IPoint dup(){ return new IPoint(this); } synchronized public IVec2 to2d(){ return pos.to2d(); } synchronized public IVec2 to2d(IVecI projectionDir){ return pos.to2d(projectionDir); } synchronized public IVec2 to2d(IVecI xaxis, IVecI yaxis){ return pos.to2d(xaxis,yaxis); } synchronized public IVec2 to2d(IVecI xaxis, IVecI yaxis, IVecI origin){ return pos.to2d(xaxis,yaxis,origin); } synchronized public IVec4 to4d(){ return pos.to4d(); } synchronized public IVec4 to4d(double w){ return pos.to4d(w); } synchronized public IVec4 to4d(IDoubleI w){ return pos.to4d(w); } synchronized public IDouble getX(){ return pos.getX(); } synchronized public IDouble getY(){ return pos.getY(); } synchronized public IDouble getZ(){ return pos.getZ(); } synchronized public IPoint set(IVecI v){ pos.set(v); return this; } synchronized public IPoint set(double x, double y, double z){ pos.set(x,y,z); return this;} synchronized public IPoint set(IDoubleI x, IDoubleI y, IDoubleI z){ pos.set(x,y,z); return this; } synchronized public IPoint add(double x, double y, double z){ pos.add(x,y,z); return this; } synchronized public IPoint add(IDoubleI x, IDoubleI y, IDoubleI z){ pos.add(x,y,z); return this; } synchronized public IPoint add(IVecI v){ pos.add(v); return this; } synchronized public IPoint sub(double x, double y, double z){ pos.sub(x,y,z); return this; } synchronized public IPoint sub(IDoubleI x, IDoubleI y, IDoubleI z){ pos.sub(x,y,z); return this; } synchronized public IPoint sub(IVecI v){ pos.sub(v); return this; } synchronized public IPoint mul(IDoubleI v){ pos.mul(v); return this; } synchronized public IPoint mul(double v){ pos.mul(v); return this; } synchronized public IPoint div(IDoubleI v){ pos.div(v); return this; } synchronized public IPoint div(double v){ pos.div(v); return this; } synchronized public IPoint neg(){ pos.neg(); return this; } synchronized public IPoint rev(){ return neg(); } synchronized public IPoint flip(){ return neg(); } synchronized public IPoint zero(){ pos.zero(); return this; } /** scale add */ synchronized public IPoint add(IVecI v, double f){ pos.add(v,f); return this; } synchronized public IPoint add(IVecI v, IDoubleI f){ pos.add(v,f); return this; } /** scale add alias */ synchronized public IPoint add(double f, IVecI v){ return add(v,f); } synchronized public IPoint add(IDoubleI f, IVecI v){ return add(v,f); } synchronized public double dot(IVecI v){ return pos.dot(v); } synchronized public double dot(double vx, double vy, double vz){ return pos.dot(vx,vy,vz); } synchronized public double dot(ISwitchE e, IVecI v){ return pos.dot(e,v); } synchronized public IDouble dot(ISwitchR r, IVecI v){ return pos.dot(r,v); } // creating IPoint is too much (in terms of memory occupancy) //synchronized public IPoint cross(IVecI v){ return dup().set(pos.cross(v)); } synchronized public IVec cross(IVecI v){ return pos.cross(v); } synchronized public IVec cross(double vx, double vy, double vz){ return pos.cross(vx,vy,vz); } synchronized public double len(){ return pos.len(); } synchronized public double len(ISwitchE e){ return pos.len(e); } synchronized public IDouble len(ISwitchR r){ return pos.len(r); } synchronized public double len2(){ return pos.len2(); } synchronized public double len2(ISwitchE e){ return pos.len2(e); } synchronized public IDouble len2(ISwitchR r){ return pos.len2(r); } synchronized public IPoint len(IDoubleI l){ pos.len(l); return this; } synchronized public IPoint len(double l){ pos.len(l); return this; } synchronized public IPoint unit(){ pos.unit(); return this; } synchronized public double dist(IVecI v){ return pos.dist(v); } synchronized public double dist(double vx, double vy, double vz){ return pos.dist(vx,vy,vz); } synchronized public double dist(ISwitchE e, IVecI v){ return pos.dist(e,v); } synchronized public IDouble dist(ISwitchR r, IVecI v){ return pos.dist(r,v); } synchronized public double dist2(IVecI v){ return pos.dist2(v); } synchronized public double dist2(double vx, double vy, double vz){ return pos.dist2(vx,vy,vz); } synchronized public double dist2(ISwitchE e, IVecI v){ return pos.dist2(e,v); } synchronized public IDouble dist2(ISwitchR r, IVecI v){ return pos.dist2(r,v); } synchronized public boolean eq(IVecI v){ return pos.eq(v); } synchronized public boolean eq(double vx, double vy, double vz){ return pos.eq(vx,vy,vz); } synchronized public boolean eq(ISwitchE e, IVecI v){ return pos.eq(e,v); } synchronized public IBool eq(ISwitchR r, IVecI v){ return pos.eq(r,v); } synchronized public boolean eq(IVecI v, double tolerance){ return pos.eq(v,tolerance); } synchronized public boolean eq(double vx, double vy, double vz, double tolerance){ return pos.eq(vx,vy,vz,tolerance); } synchronized public boolean eq(ISwitchE e, IVecI v, double tolerance){ return pos.eq(e,v,tolerance); } synchronized public IBool eq(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eq(r,v,tolerance); } synchronized public boolean eqX(IVecI v){ return pos.eqX(v); } synchronized public boolean eqY(IVecI v){ return pos.eqY(v); } synchronized public boolean eqZ(IVecI v){ return pos.eqZ(v); } synchronized public boolean eqX(double vx){ return pos.eqX(vx); } synchronized public boolean eqY(double vy){ return pos.eqY(vy); } synchronized public boolean eqZ(double vz){ return pos.eqZ(vz); } synchronized public boolean eqX(ISwitchE e, IVecI v){ return pos.eqX(e,v); } synchronized public boolean eqY(ISwitchE e, IVecI v){ return pos.eqY(e,v); } synchronized public boolean eqZ(ISwitchE e, IVecI v){ return pos.eqZ(e,v); } synchronized public IBool eqX(ISwitchR r, IVecI v){ return pos.eqX(r,v); } synchronized public IBool eqY(ISwitchR r, IVecI v){ return pos.eqY(r,v); } synchronized public IBool eqZ(ISwitchR r, IVecI v){ return pos.eqZ(r,v); } synchronized public boolean eqX(IVecI v, double tolerance){ return pos.eqX(v,tolerance); } synchronized public boolean eqY(IVecI v, double tolerance){ return pos.eqY(v,tolerance); } synchronized public boolean eqZ(IVecI v, double tolerance){ return pos.eqZ(v,tolerance); } synchronized public boolean eqX(double vx, double tolerance){ return pos.eqX(vx,tolerance); } synchronized public boolean eqY(double vy, double tolerance){ return pos.eqY(vy,tolerance); } synchronized public boolean eqZ(double vz, double tolerance){ return pos.eqZ(vz,tolerance); } synchronized public boolean eqX(ISwitchE e, IVecI v, double tolerance){ return pos.eqX(e,v,tolerance); } synchronized public boolean eqY(ISwitchE e, IVecI v, double tolerance){ return pos.eqY(e,v,tolerance); } synchronized public boolean eqZ(ISwitchE e, IVecI v, double tolerance){ return pos.eqZ(e,v,tolerance); } synchronized public IBool eqX(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eqX(r,v,tolerance); } synchronized public IBool eqY(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eqY(r,v,tolerance); } synchronized public IBool eqZ(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eqZ(r,v,tolerance); } synchronized public double angle(IVecI v){ return pos.angle(v); } synchronized public double angle(double vx, double vy, double vz){ return pos.angle(vx,vy,vz); } synchronized public double angle(ISwitchE e, IVecI v){ return pos.angle(e,v); } synchronized public IDouble angle(ISwitchR r, IVecI v){ return pos.angle(r,v); } synchronized public double angle(IVecI v, IVecI axis){ return pos.angle(v,axis); } synchronized public double angle(double vx, double vy, double vz, double axisX, double axisY, double axisZ){ return pos.angle(vx,vy,vz,axisX,axisY,axisZ); } synchronized public double angle(ISwitchE e, IVecI v, IVecI axis){ return pos.angle(e,v,axis); } synchronized public IDouble angle(ISwitchR r, IVecI v, IVecI axis){ return pos.angle(r,v,axis); } synchronized public IPoint rot(IDoubleI angle){ pos.rot(angle); return this; } synchronized public IPoint rot(double angle){ pos.rot(angle); return this; } synchronized public IPoint rot(IVecI axis, IDoubleI angle){ pos.rot(axis,angle); return this; } synchronized public IPoint rot(IVecI axis, double angle){ pos.rot(axis,angle); return this; } synchronized public IPoint rot(double axisX, double axisY, double axisZ, double angle){ pos.rot(axisX,axisY,axisZ,angle); return this; } synchronized public IPoint rot(IVecI center, IVecI axis, double angle){ pos.rot(center, axis,angle); return this; } synchronized public IPoint rot(double centerX, double centerY, double centerZ, double axisX, double axisY, double axisZ, double angle){ pos.rot(centerX, centerY, centerZ, axisX, axisY, axisZ, angle); return this; } synchronized public IPoint rot(IVecI center, IVecI axis, IDoubleI angle){ pos.rot(center, axis,angle); return this; } /** Rotate to destination direction vector. */ synchronized public IPoint rot(IVecI axis, IVecI destDir){ pos.rot(axis,destDir); return this; } /** Rotate to destination point location. */ synchronized public IPoint rot(IVecI center, IVecI axis, IVecI destPt){ pos.rot(center,axis,destPt); return this; } synchronized public IPoint rot2(IDoubleI angle){ pos.rot2(angle); return this; } synchronized public IPoint rot2(double angle){ pos.rot2(angle); return this; } synchronized public IPoint rot2(IVecI center, double angle){ pos.rot2(center, angle); return this; } synchronized public IPoint rot2(double centerX, double centerY, double angle){ pos.rot2(centerX, centerY, angle); return this; } synchronized public IPoint rot2(IVecI center, IDoubleI angle){ pos.rot2(center, angle); return this; } /** Rotate to destination direction vector. */ synchronized public IPoint rot2(IVecI destDir){ pos.rot2(destDir); return this; } /** Rotate to destination point location. */ synchronized public IPoint rot2(IVecI center, IVecI destPt){ pos.rot2(center,destPt); return this; } /** alias of mul */ synchronized public IPoint scale(IDoubleI f){ pos.scale(f); return this; } /** alias of mul */ synchronized public IPoint scale(double f){ pos.scale(f); return this; } synchronized public IPoint scale(IVecI center, IDoubleI f){ pos.scale(center,f); return this; } synchronized public IPoint scale(IVecI center, double f){ pos.scale(center,f); return this; } synchronized public IPoint scale(double centerX, double centerY, double centerZ, double f){ pos.scale(centerX, centerY, centerZ, f); return this; } /** scale only in 1 direction */ synchronized public IPoint scale1d(IVecI axis, double f){ pos.scale1d(axis,f); return this; } synchronized public IPoint scale1d(double axisX, double axisY, double axisZ, double f){ pos.scale1d(axisX,axisY,axisZ,f); return this; } synchronized public IPoint scale1d(IVecI axis, IDoubleI f){ pos.scale1d(axis,f); return this; } synchronized public IPoint scale1d(IVecI center, IVecI axis, double f){ pos.scale1d(center,axis,f); return this; } synchronized public IPoint scale1d(double centerX, double centerY, double centerZ, double axisX, double axisY, double axisZ, double f){ pos.scale1d(centerX,centerY,centerZ,axisX,axisY,axisZ,f); return this; } synchronized public IPoint scale1d(IVecI center, IVecI axis, IDoubleI f){ pos.scale1d(center,axis,f); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(IVecI planeDir){ pos.ref(planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(double planeX, double planeY, double planeZ){ pos.ref(planeX,planeY,planeZ); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(IVecI center, IVecI planeDir){ pos.ref(center,planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(double centerX, double centerY, double centerZ, double planeX, double planeY, double planeZ){ pos.ref(centerX,centerY,centerZ,planeX,planeY,planeZ); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(IVecI planeDir){ pos.ref(planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(double planeX, double planeY, double planeZ){ pos.ref(planeX,planeY,planeZ); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(IVecI center, IVecI planeDir){ pos.ref(center,planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(double centerX, double centerY, double centerZ, double planeX, double planeY, double planeZ){ pos.ref(centerX,centerY,centerZ,planeX,planeY,planeZ); return this; } /** shear operation */ synchronized public IPoint shear(double sxy, double syx, double syz, double szy, double szx, double sxz){ pos.shear(sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shear(IDoubleI sxy, IDoubleI syx, IDoubleI syz, IDoubleI szy, IDoubleI szx, IDoubleI sxz){ pos.shear(sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shear(IVecI center, double sxy, double syx, double syz, double szy, double szx, double sxz){ pos.shear(center,sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shear(IVecI center, IDoubleI sxy, IDoubleI syx, IDoubleI syz, IDoubleI szy, IDoubleI szx, IDoubleI sxz){ pos.shear(center,sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shearXY(double sxy, double syx){ pos.shearXY(sxy,syx); return this; } synchronized public IPoint shearXY(IDoubleI sxy, IDoubleI syx){ pos.shearXY(sxy,syx); return this; } synchronized public IPoint shearXY(IVecI center, double sxy, double syx){ pos.shearXY(center,sxy,syx); return this; } synchronized public IPoint shearXY(IVecI center, IDoubleI sxy, IDoubleI syx){ pos.shearXY(center,sxy,syx); return this; } synchronized public IPoint shearYZ(double syz, double szy){ pos.shearYZ(syz,szy); return this; } synchronized public IPoint shearYZ(IDoubleI syz, IDoubleI szy){ pos.shearYZ(syz,szy); return this; } synchronized public IPoint shearYZ(IVecI center, double syz, double szy){ pos.shearYZ(center,syz,szy); return this; } synchronized public IPoint shearYZ(IVecI center, IDoubleI syz, IDoubleI szy){ pos.shearYZ(center,syz,szy); return this; } synchronized public IPoint shearZX(double szx, double sxz){ pos.shearZX(szx,sxz); return this; } synchronized public IPoint shearZX(IDoubleI szx, IDoubleI sxz){ pos.shearZX(szx,sxz); return this; } synchronized public IPoint shearZX(IVecI center, double szx, double sxz){ pos.shearZX(center,szx,sxz); return this; } synchronized public IPoint shearZX(IVecI center, IDoubleI szx, IDoubleI sxz){ pos.shearZX(center,szx,sxz); return this; } /** translate is alias of add() */ synchronized public IPoint translate(double x, double y, double z){ pos.translate(x,y,z); return this; } synchronized public IPoint translate(IDoubleI x, IDoubleI y, IDoubleI z){ pos.translate(x,y,z); return this; } synchronized public IPoint translate(IVecI v){ pos.translate(v); return this; } synchronized public IPoint transform(IMatrix3I mat){ pos.transform(mat); return this; } synchronized public IPoint transform(IMatrix4I mat){ pos.transform(mat); return this; } synchronized public IPoint transform(IVecI xvec, IVecI yvec, IVecI zvec){ pos.transform(xvec,yvec,zvec); return this; } synchronized public IPoint transform(IVecI xvec, IVecI yvec, IVecI zvec, IVecI translate){ pos.transform(xvec,yvec,zvec,translate); return this; } /** mv() is alias of add() */ synchronized public IPoint mv(double x, double y, double z){ return add(x,y,z); } synchronized public IPoint mv(IDoubleI x, IDoubleI y, IDoubleI z){ return add(x,y,z); } synchronized public IPoint mv(IVecI v){ return add(v); } // method name cp() is used as getting control point method in curve and surface but here used also as copy because of the priority of variable fitting of diversed users' mind set over the clarity of the code organization /** cp() is alias of dup() */ synchronized public IPoint cp(){ return dup(); } /** cp() is alias of dup().add() */ synchronized public IPoint cp(double x, double y, double z){ return dup().add(x,y,z); } synchronized public IPoint cp(IDoubleI x, IDoubleI y, IDoubleI z){ return dup().add(x,y,z); } synchronized public IPoint cp(IVecI v){ return dup().add(v); } // methods creating new instance // returns IPoint?, not IVec? // returns IVec, not IPoint (2011/10/12) //synchronized public IPoint diff(IVecI v){ return dup().sub(v); } synchronized public IVec dif(IVecI v){ return pos.dif(v); } synchronized public IVec dif(double vx, double vy, double vz){ return pos.dif(vx,vy,vz); } synchronized public IVec diff(IVecI v){ return dif(v); } synchronized public IVec diff(double vx, double vy, double vz){ return dif(vx,vy,vz); } //synchronized public IPoint mid(IVecI v){ return dup().add(v).div(2); } synchronized public IVec mid(IVecI v){ return pos.mid(v); } synchronized public IVec mid(double vx, double vy, double vz){ return pos.mid(vx,vy,vz); } //synchronized public IPoint sum(IVecI v){ return dup().add(v); } synchronized public IVec sum(IVecI v){ return pos.sum(v); } synchronized public IVec sum(double vx, double vy, double vz){ return pos.sum(vx,vy,vz); } //synchronized public IPoint sum(IVecI... v){ IPoint ret = this.dup(); for(IVecI vi: v) ret.add(vi); return ret; } synchronized public IVec sum(IVecI... v){ return pos.sum(v); } //synchronized public IPoint bisect(IVecI v){ return dup().unit().add(v.dup().unit()); } synchronized public IVec bisect(IVecI v){ return pos.bisect(v); } synchronized public IVec bisect(double vx, double vy, double vz){ return pos.bisect(vx,vy,vz); } /** weighted sum. @return IVec */ //synchronized public IPoint sum(IVecI v2, double w1, double w2){ return dup().mul(w1).add(v2,w2); } synchronized public IVec sum(IVecI v2, double w1, double w2){ return pos.sum(v2,w1,w2); } //synchronized public IPoint sum(IVecI v2, double w2){ return dup().mul(1.0-w2).add(v2,w2); } synchronized public IVec sum(IVecI v2, double w2){ return pos.sum(v2,w2); } //synchronized public IPoint sum(IVecI v2, IDoubleI w1, IDoubleI w2){ return dup().mul(w1).add(v2,w2); } synchronized public IVec sum(IVecI v2, IDoubleI w1, IDoubleI w2){ return sum(v2,w1,w2); } //synchronized public IPoint sum(IVecI v2, IDoubleI w2){ return dup().mul(new IDouble(1.0).sub(w2)).add(v2,w2); } synchronized public IVec sum(IVecI v2, IDoubleI w2){ return sum(v2,w2); } /** alias of cross. (not unitized ... ?) */ //synchronized public IPoint nml(IVecI v){ return cross(v); } synchronized public IVec nml(IVecI v){ return pos.nml(v); } synchronized public IVec nml(double vx, double vy, double vz){ return pos.nml(vx,vy,vz); } /** create normal vector from 3 points of self, pt1 and pt2 */ //synchronized public IPoint nml(IVecI pt1, IVecI pt2){ return this.diff(pt1).cross(this.diff(pt2)).unit(); } synchronized public IVec nml(IVecI pt1, IVecI pt2){ return pos.nml(pt1,pt2); } synchronized public IVec nml(double vx1, double vy1, double vz1, double vx2, double vy2, double vz2){ return pos.nml(vx1,vy1,vz1,vx2,vy2,vz2); } /** checking x, y, and z is valid number (not Infinite, nor NaN). */ synchronized public boolean isValid(){ if(pos==null){ return false; } return pos.isValid(); } synchronized public String toString(){ if(pos==null) return super.toString(); return pos.toString(); } /** default setting in each object class; to be overridden in a child class */ public IAttribute defaultAttribute(){ IAttribute a = new IAttribute(); a.weight = IConfig.pointSize; return a; } /** set size of dot in graphic ; it's just alias of weight() */ synchronized public IPoint setSize(double sz){ return weight(sz); } synchronized public IPoint size(double sz){ return weight(sz); } /* synchronized public IPoint setSize(double sz){ return size(sz); } synchronized public IPoint size(double sz){ for(int i=0; graphics!=null && i<graphics.size(); i++) if(graphics.get(i) instanceof IPointGraphic) ((IPointGraphic)graphics.get(i)).size(sz); return this; } */ synchronized public double getSize(){ return size(); } public double size(){ if(graphics==null){ IOut.err("no graphics is set"); // return -1; } for(int i=0; graphics!=null && i<graphics.size(); i++) if(graphics.get(i) instanceof IPointGraphic) return ((IPointGraphic)graphics.get(i)).size(); return -1; } synchronized public IPoint name(String nm){ super.name(nm); return this; } synchronized public IPoint layer(ILayer l){ super.layer(l); return this; } synchronized public IPoint layer(String l){ super.layer(l); return this; } synchronized public IPoint attr(IAttribute at){ super.attr(at); return this; } synchronized public IPoint hide(){ super.hide(); return this; } synchronized public IPoint show(){ super.show(); return this; } synchronized public IPoint clr(IColor c){ super.clr(c); return this; } synchronized public IPoint clr(IColor c, int alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(IColor c, float alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(IColor c, double alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(IObject o){ super.clr(o); return this; } synchronized public IPoint clr(Color c){ super.clr(c); return this; } synchronized public IPoint clr(Color c, int alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(Color c, float alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(Color c, double alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(int gray){ super.clr(gray); return this; } synchronized public IPoint clr(float fgray){ super.clr(fgray); return this; } synchronized public IPoint clr(double dgray){ super.clr(dgray); return this; } synchronized public IPoint clr(int gray, int alpha){ super.clr(gray,alpha); return this; } synchronized public IPoint clr(float fgray, float falpha){ super.clr(fgray,falpha); return this; } synchronized public IPoint clr(double dgray, double dalpha){ super.clr(dgray,dalpha); return this; } synchronized public IPoint clr(int r, int g, int b){ super.clr(r,g,b); return this; } synchronized public IPoint clr(float fr, float fg, float fb){ super.clr(fr,fg,fb); return this; } synchronized public IPoint clr(double dr, double dg, double db){ super.clr(dr,dg,db); return this; } synchronized public IPoint clr(int r, int g, int b, int a){ super.clr(r,g,b,a); return this; } synchronized public IPoint clr(float fr, float fg, float fb, float fa){ super.clr(fr,fg,fb,fa); return this; } synchronized public IPoint clr(double dr, double dg, double db, double da){ super.clr(dr,dg,db,da); return this; } synchronized public IPoint hsb(float h, float s, float b, float a){ super.hsb(h,s,b,a); return this; } synchronized public IPoint hsb(double h, double s, double b, double a){ super.hsb(h,s,b,a); return this; } synchronized public IPoint hsb(float h, float s, float b){ super.hsb(h,s,b); return this; } synchronized public IPoint hsb(double h, double s, double b){ super.hsb(h,s,b); return this; } synchronized public IPoint setColor(IColor c){ super.setColor(c); return this; } synchronized public IPoint setColor(IColor c, int alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(IColor c, float alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(IColor c, double alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(Color c){ super.setColor(c); return this; } synchronized public IPoint setColor(Color c, int alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(Color c, float alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(Color c, double alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(int gray){ super.setColor(gray); return this; } synchronized public IPoint setColor(float fgray){ super.setColor(fgray); return this; } synchronized public IPoint setColor(double dgray){ super.setColor(dgray); return this; } synchronized public IPoint setColor(int gray, int alpha){ super.setColor(gray,alpha); return this; } synchronized public IPoint setColor(float fgray, float falpha){ super.setColor(fgray,falpha); return this; } synchronized public IPoint setColor(double dgray, double dalpha){ super.setColor(dgray,dalpha); return this; } synchronized public IPoint setColor(int r, int g, int b){ super.setColor(r,g,b); return this; } synchronized public IPoint setColor(float fr, float fg, float fb){ super.setColor(fr,fg,fb); return this; } synchronized public IPoint setColor(double dr, double dg, double db){ super.setColor(dr,dg,db); return this; } synchronized public IPoint setColor(int r, int g, int b, int a){ super.setColor(r,g,b,a); return this; } synchronized public IPoint setColor(float fr, float fg, float fb, float fa){ super.setColor(fr,fg,fb,fa); return this; } synchronized public IPoint setColor(double dr, double dg, double db, double da){ super.setColor(dr,dg,db,da); return this; } synchronized public IPoint setHSBColor(float h, float s, float b, float a){ super.setHSBColor(h,s,b,a); return this; } synchronized public IPoint setHSBColor(double h, double s, double b, double a){ super.setHSBColor(h,s,b,a); return this; } synchronized public IPoint setHSBColor(float h, float s, float b){ super.setHSBColor(h,s,b); return this; } synchronized public IPoint setHSBColor(double h, double s, double b){ super.setHSBColor(h,s,b); return this; } synchronized public IPoint weight(double w){ super.weight(w); return this; } synchronized public IPoint weight(float w){ super.weight(w); return this; } }
Java
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_CREATERESERVEDINSTANCESLISTINGREQUEST_P_H #define QTAWS_CREATERESERVEDINSTANCESLISTINGREQUEST_P_H #include "ec2request_p.h" #include "createreservedinstanceslistingrequest.h" namespace QtAws { namespace EC2 { class CreateReservedInstancesListingRequest; class CreateReservedInstancesListingRequestPrivate : public Ec2RequestPrivate { public: CreateReservedInstancesListingRequestPrivate(const Ec2Request::Action action, CreateReservedInstancesListingRequest * const q); CreateReservedInstancesListingRequestPrivate(const CreateReservedInstancesListingRequestPrivate &other, CreateReservedInstancesListingRequest * const q); private: Q_DECLARE_PUBLIC(CreateReservedInstancesListingRequest) }; } // namespace EC2 } // namespace QtAws #endif
Java
<?php /** * This file is part of contao-community-alliance/dc-general. * * (c) 2013-2019 Contao Community Alliance. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * This project is provided in good faith and hope to be usable by anyone. * * @package contao-community-alliance/dc-general * @author Christian Schiffler <c.schiffler@cyberspectrum.de> * @author Sven Baumann <baumann.sv@gmail.com> * @copyright 2013-2019 Contao Community Alliance. * @license https://github.com/contao-community-alliance/dc-general/blob/master/LICENSE LGPL-3.0-or-later * @filesource */ namespace ContaoCommunityAlliance\DcGeneral\Data; /** * This class is the base implementation for LanguageInformationCollectionInterface. */ class DefaultLanguageInformationCollection implements LanguageInformationCollectionInterface { /** * The language information stored in this collection. * * @var LanguageInformationInterface[] */ protected $languages = []; /** * {@inheritDoc} */ public function add(LanguageInformationInterface $language) { $this->languages[] = $language; return $this; } /** * Get a iterator for this collection. * * @return \ArrayIterator */ public function getIterator() { return new \ArrayIterator($this->languages); } /** * Count the contained language information. * * @return int */ public function count() { return \count($this->languages); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Test 6</title> <script src="sxz.js"></script> </head> <body> <img src="lena_std.jpg" align="left" alt="original image" /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <canvas id="canvasid" width="512" height="512"></canvas> <script> var canvas = document.getElementById('canvasid'); var sxz = new Sxz(); sxz.Load(sxz, "lena_std.sxz", canvas, Render); function Render(sxz) { sxz.Render(); } </script> </body> </html>
Java
/* * PROJECT: NyARToolkitCS * -------------------------------------------------------------------------------- * * The NyARToolkitCS is C# edition NyARToolKit class library. * Copyright (C)2008-2012 Ryo Iizuka * * This work is based on the ARToolKit developed by * Hirokazu Kato * Mark Billinghurst * HITLab, University of Washington, Seattle * http://www.hitl.washington.edu/artoolkit/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as publishe * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 <http://www.gnu.org/licenses/>. * * For further information please contact. * http://nyatla.jp/nyatoolkit/ * <airmail(at)ebony.plala.or.jp> or <nyatla(at)nyatla.jp> * */ using System; namespace jp.nyatla.nyartoolkit.cs.core { /** * このクラスは、樽型歪み設定/解除クラスです。 */ public interface INyARCameraDistortionFactor { /** * この関数は、座標点を理想座標系から観察座標系へ変換します。 * @param i_in * 変換元の座標 * @param o_out * 変換後の座標を受け取るオブジェクト */ void ideal2Observ(NyARDoublePoint2d i_in, NyARDoublePoint2d o_out); /** * この関数は、座標点を理想座標系から観察座標系へ変換します。 * @param i_in * 変換元の座標 * @param o_out * 変換後の座標を受け取るオブジェクト */ void ideal2Observ(NyARDoublePoint2d i_in, NyARIntPoint2d o_out); /** * この関数は、座標点を理想座標系から観察座標系へ変換します。 * @param i_in * 変換元の座標 * @param o_out * 変換後の座標を受け取るオブジェクト */ void ideal2Observ(double i_x, double i_y, NyARDoublePoint2d o_out); /** * この関数は、座標点を理想座標系から観察座標系へ変換します。 * @param i_x * 変換元の座標 * @param i_y * 変換元の座標 * @param o_out * 変換後の座標を受け取るオブジェクト */ void ideal2Observ(double i_x, double i_y, NyARIntPoint2d o_out); /** * この関数は、複数の座標点を、一括して理想座標系から観察座標系へ変換します。 * i_inとo_outには、同じインスタンスを指定できます。 * @param i_in * 変換元の座標配列 * @param o_out * 変換後の座標を受け取る配列 * @param i_size * 変換する座標の個数。 */ void ideal2ObservBatch(NyARDoublePoint2d[] i_in, NyARDoublePoint2d[] o_out, int i_size); /** * この関数は、複数の座標点を、一括して理想座標系から観察座標系へ変換します。 * i_inとo_outには、同じインスタンスを指定できます。 * @param i_in * 変換元の座標配列 * @param o_out * 変換後の座標を受け取る配列 * @param i_size * 変換する座標の個数。 */ void ideal2ObservBatch(NyARDoublePoint2d[] i_in, NyARIntPoint2d[] o_out, int i_size); /** * この関数は、座標を観察座標系から理想座標系へ変換します。 * @param ix * 変換元の座標 * @param iy * 変換元の座標 * @param o_point * 変換後の座標を受け取るオブジェクト */ void observ2Ideal(double ix, double iy, NyARDoublePoint2d o_point); /** * {@link #observ2Ideal(double, double, NyARDoublePoint2d)}のラッパーです。 * i_inとo_pointには、同じオブジェクトを指定できます。 * @param i_in * @param o_point */ void observ2Ideal(NyARDoublePoint2d i_in, NyARDoublePoint2d o_point); /** * この関数は、観察座標を理想座標へ変換します。 * 入力できる値範囲は、コンストラクタに設定したスクリーンサイズの範囲内です。 * @param ix * 観察座標の値 * @param iy * 観察座標の値 * @param o_point * 理想座標を受け取るオブジェクト。 */ void observ2Ideal(int ix, int iy, NyARDoublePoint2d o_point); /** * 座標配列全てに対して、{@link #observ2Ideal(double, double, NyARDoublePoint2d)}を適応します。 * @param i_in * @param o_out * @param i_size */ void observ2IdealBatch(NyARDoublePoint2d[] i_in, NyARDoublePoint2d[] o_out, int i_size); void observ2IdealBatch(NyARIntPoint2d[] i_in, NyARDoublePoint2d[] o_out, int i_size); } }
Java
/* radare - LGPLv3 - Copyright 2014-2015 - pancake, jvoisin, jfrankowski */ #include <dirent.h> #include <r_core.h> #include <r_lib.h> #include <yara.h> #undef R_API #define R_API static #undef R_IPI #define R_IPI static // true if the plugin has been initialized. static int initialized = false; static bool print_strings = 0; static unsigned int flagidx = 0; static bool io_va = true; #if YR_MAJOR_VERSION < 4 static int callback(int message, void* rule, void* data); #else static int callback(YR_SCAN_CONTEXT* context, int message, void* rule, void* data); #endif static int r_cmd_yara_add (const RCore* core, const char* input); static int r_cmd_yara_add_file (const char* rules_path); static int r_cmd_yara_call(void *user, const char *input); static int r_cmd_yara_clear(); static int r_cmd_yara_init(void *user, const char *cmd); static int r_cmd_yara_help(const RCore* core); static int r_cmd_yara_process(const RCore* core, const char* input); static int r_cmd_yara_scan(const RCore* core, const char* option); static int r_cmd_yara_load_default_rules (const RCore* core); static const char* yara_rule_template = "rule RULE_NAME {\n\tstrings:\n\n\tcondition:\n}"; /* Because of how the rules are compiled, we are not allowed to add more * rules to a compiler once it has compiled. That's why we keep a list * of those compiled rules. */ static RList* rules_list; #if YR_MAJOR_VERSION < 4 static int callback (int message, void *msg_data, void *user_data) { RCore *core = (RCore *) user_data; RPrint *print = core->print; unsigned int ruleidx; st64 offset = 0; ut64 n = 0; YR_RULE* rule = msg_data; if (message == CALLBACK_MSG_RULE_MATCHING) { YR_STRING* string; r_cons_printf("%s\n", rule->identifier); ruleidx = 0; yr_rule_strings_foreach(rule, string) { YR_MATCH* match; yr_string_matches_foreach(string, match) { n = match->base + match->offset; // Find virtual address if needed if (io_va) { RIOMap *map = r_io_map_get_paddr (core->io, n); if (map) { offset = r_io_map_begin (map) - map->delta; } } const char *flag = sdb_fmt ("%s%d_%s_%d", "yara", flagidx, rule->identifier, ruleidx); if (print_strings) { r_cons_printf("0x%08" PFMT64x ": %s : ", n + offset, flag); r_print_bytes(print, match->data, match->data_length, "%02x"); } r_flag_set (core->flags, flag, n + offset, match->data_length); ruleidx++; } } flagidx++; } return CALLBACK_CONTINUE; } static void compiler_callback(int error_level, const char* file_name, int line_number, const char* message, void* user_data) { eprintf ("file: %s line_number: %d.\n%s", file_name, line_number, message); return; } #else static int callback (YR_SCAN_CONTEXT* context, int message, void *msg_data, void *user_data) { RCore *core = (RCore *) user_data; RPrint *print = core->print; unsigned int ruleidx; st64 offset = 0; ut64 n = 0; YR_RULE* rule = msg_data; if (message == CALLBACK_MSG_RULE_MATCHING) { YR_STRING* string; r_cons_printf("%s\n", rule->identifier); ruleidx = 0; yr_rule_strings_foreach(rule, string) { YR_MATCH* match; yr_string_matches_foreach(context, string, match) { n = match->base + match->offset; // Find virtual address if needed if (io_va) { RIOMap *map = r_io_map_get_paddr (core->io, n); if (map) { offset = r_io_map_begin (map) - map->delta; } } const char *flag = sdb_fmt ("%s%d_%s_%d", "yara", flagidx, rule->identifier, ruleidx); if (print_strings) { r_cons_printf("0x%08" PFMT64x ": %s : ", n + offset, flag); r_print_bytes(print, match->data, match->data_length, "%02x"); } r_flag_set (core->flags, flag, n + offset, match->data_length); ruleidx++; } } flagidx++; } return CALLBACK_CONTINUE; } static void compiler_callback(int error_level, const char* file_name, int line_number, const struct YR_RULE *rule, const char* message, void* user_data) { eprintf ("file: %s line_number: %d.\n%s", file_name, line_number, message); return; } #endif static int r_cmd_yara_scan(const RCore* core, const char* option) { RListIter* rules_it; YR_RULES* rules; void* to_scan; int result; r_flag_space_push (core->flags, "yara"); const unsigned int to_scan_size = r_io_size (core->io); io_va = r_config_get_b (core->config, "io.va"); if (to_scan_size < 1) { eprintf ("Invalid file size\n"); return false; } if( *option == '\0') { print_strings = 0; } else if (*option == 'S') { print_strings = 1; } else { print_strings = 0; eprintf ("Invalid option\n"); return false; } to_scan = malloc (to_scan_size); if (!to_scan) { eprintf ("Something went wrong during memory allocation\n"); return false; } result = r_io_pread_at (core->io, 0L, to_scan, to_scan_size); if (!result) { eprintf ("Something went wrong during r_io_read_at\n"); free (to_scan); return false; } r_list_foreach (rules_list, rules_it, rules) { yr_rules_scan_mem (rules, to_scan, to_scan_size, 0, callback, (void *)core, 0); } free (to_scan); return true; } static int r_cmd_yara_show(const char * name) { /* List loaded rules containing name */ RListIter* rules_it; YR_RULES* rules; YR_RULE* rule; r_list_foreach (rules_list, rules_it, rules) { yr_rules_foreach (rules, rule) { if (r_str_casestr (rule->identifier, name)) { r_cons_printf ("%s\n", rule->identifier); } } } return true; } static int r_cmd_yara_tags() { /* List tags from all the different loaded rules */ RListIter* rules_it; RListIter *tags_it; YR_RULES* rules; YR_RULE* rule; const char* tag_name; RList *tag_list = r_list_new(); tag_list->free = free; r_list_foreach (rules_list, rules_it, rules) { yr_rules_foreach(rules, rule) { yr_rule_tags_foreach(rule, tag_name) { if (! r_list_find (tag_list, tag_name, (RListComparator)strcmp)) { r_list_add_sorted (tag_list, strdup (tag_name), (RListComparator)strcmp); } } } } r_cons_printf ("[YARA tags]\n"); r_list_foreach (tag_list, tags_it, tag_name) { r_cons_printf ("%s\n", tag_name); } r_list_free (tag_list); return true; } static int r_cmd_yara_tag (const char * search_tag) { /* List rules with tag search_tag */ RListIter* rules_it; YR_RULES* rules; YR_RULE* rule; const char* tag_name; r_list_foreach (rules_list, rules_it, rules) { yr_rules_foreach (rules, rule) { yr_rule_tags_foreach(rule, tag_name) {eprintf ("Invalid option\n"); if (r_str_casestr (tag_name, search_tag)) { r_cons_printf("%s\n", rule->identifier); break; } } } } return true; } static int r_cmd_yara_list () { /* List all loaded rules */ RListIter* rules_it; YR_RULES* rules; YR_RULE* rule; r_list_foreach (rules_list, rules_it, rules) { yr_rules_foreach (rules, rule) { r_cons_printf("%s\n", rule->identifier); } } return true; } static int r_cmd_yara_clear () { /* Clears all loaded rules */ r_list_free (rules_list); rules_list = r_list_newf((RListFree) yr_rules_destroy); eprintf ("Rules cleared.\n"); return true; } static int r_cmd_yara_add(const RCore* core, const char* input) { /* Add a rule with user input */ YR_COMPILER* compiler = NULL; char* modified_template = NULL; char* old_template = NULL; int result, i, continue_edit; for( i = 0; input[i] != '\0'; i++) { if (input[i] != ' ') { return r_cmd_yara_add_file (input + i); } } if (yr_compiler_create (&compiler) != ERROR_SUCCESS) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); return false; } old_template = strdup(yara_rule_template); do { modified_template = r_core_editor (core, NULL, old_template); free(old_template); old_template = NULL; if (!modified_template) { eprintf("Something happened with the temp file"); goto err_exit; } result = yr_compiler_add_string (compiler, modified_template, NULL); if( result > 0 ) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); continue_edit = r_cons_yesno('y', "Do you want to continue editing the rule? [y]/n\n"); if (!continue_edit) { goto err_exit; } old_template = modified_template; modified_template = NULL; } } while (result > 0); free(modified_template); yr_compiler_destroy (compiler); r_cons_printf ("Rule successfully added.\n"); return true; err_exit: if (compiler) yr_compiler_destroy (compiler); if (modified_template) free (modified_template); if (old_template) free (old_template); return false; } static int r_cmd_yara_add_file(const char* rules_path) { YR_COMPILER* compiler = NULL; YR_RULES* rules; FILE* rules_file = NULL; int result; if (!rules_path) { eprintf ("Please tell me what am I supposed to load\n"); return false; } rules_file = r_sandbox_fopen (rules_path, "r"); if (!rules_file) { eprintf ("Unable to open %s\n", rules_path); return false; } if (yr_compiler_create (&compiler) != ERROR_SUCCESS) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); goto err_exit; } result = yr_compiler_add_file (compiler, rules_file, NULL, rules_path); fclose (rules_file); rules_file = NULL; if (result > 0) { char buf[64]; eprintf ("Error: %s : %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf)), rules_path); goto err_exit; } if (yr_compiler_get_rules (compiler, &rules) != ERROR_SUCCESS) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); goto err_exit; } r_list_append(rules_list, rules); yr_compiler_destroy (compiler); return true; err_exit: if (compiler) yr_compiler_destroy (compiler); if (rules_file) fclose (rules_file); return false; } static int r_cmd_yara_help(const RCore* core) { const char * help_message[] = { "Usage: yara", "", " Yara plugin", "add", " [file]", "Add yara rules from file, or open $EDITOR with yara rule template", "clear", "", "Clear all rules", "help", "", "Show this help", "list", "", "List all rules", "scan", "[S]", "Scan the current file, if S option is given it prints matching strings.", "show", " name", "Show rules containing name", "tag", " name", "List rules with tag 'name'", "tags", "", "List tags from the loaded rules", NULL }; r_core_cmd_help (core, help_message); return true; } static int r_cmd_yara_process(const RCore* core, const char* input) { if (!strncmp (input, "add", 3)) return r_cmd_yara_add (core, input + 3); else if (!strncmp (input, "clear", 4)) return r_cmd_yara_clear (); else if (!strncmp (input, "list", 4)) return r_cmd_yara_list (); else if (!strncmp (input, "scan", 4)) return r_cmd_yara_scan (core, input + 4); else if (!strncmp (input, "show", 4)) return r_cmd_yara_show (input + 5); else if (!strncmp (input, "tags", 4)) return r_cmd_yara_tags (); else if (!strncmp (input, "tag ", 4)) return r_cmd_yara_tag (input + 4); else return r_cmd_yara_help (core); } static int r_cmd_yara_call(void *user, const char *input) { const char *args; RCore* core = (RCore*) user; if (strncmp (input, "yara", 4)) { return false; } if (strncmp (input, "yara ", 5)) { return r_cmd_yara_help (core); } args = input + 4; if (! initialized && !r_cmd_yara_init (core, NULL)) { return false; } if (*args) { args++; } r_cmd_yara_process (core, args); return true; } static int r_cmd_yara_load_default_rules (const RCore* core) { RListIter* iter = NULL; YR_COMPILER* compiler = NULL; YR_RULES* yr_rules; char* filename, *complete_path; char* rules = NULL; char* y3_rule_dir = r_str_newf ("%s%s%s", r_str_home(R2_HOME_PLUGINS), R_SYS_DIR, "rules-yara3"); RList* list = r_sys_dir (y3_rule_dir); if (yr_compiler_create (&compiler) != ERROR_SUCCESS) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); goto err_exit; } yr_compiler_set_callback(compiler, compiler_callback, NULL); r_list_foreach (list, iter, filename) { if (filename[0] != '.') { // skip '.', '..' and hidden files complete_path = r_str_newf ("%s%s%s", y3_rule_dir, R_SYS_DIR, filename); rules = (char*)r_file_gzslurp (complete_path, NULL, true); free (complete_path); complete_path = NULL; if (yr_compiler_add_string (compiler, rules, NULL) > 0) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); } free (rules); rules = NULL; } } r_list_free (list); if (yr_compiler_get_rules (compiler, &yr_rules) != ERROR_SUCCESS) { char buf[64]; eprintf ("Error: %s\n", yr_compiler_get_error_message (compiler, buf, sizeof (buf))); goto err_exit; } r_list_append(rules_list, yr_rules); yr_compiler_destroy (compiler); return true; err_exit: if (y3_rule_dir) free (y3_rule_dir); if (compiler) yr_compiler_destroy (compiler); if (list) r_list_free (list); if (rules) free (rules); return false; } static int r_cmd_yara_init(void *user, const char *cmd) { RCore* core = (RCore *)user; rules_list = r_list_newf((RListFree) yr_rules_destroy); yr_initialize (); r_cmd_yara_load_default_rules (core); initialized = true; flagidx = 0; return true; } static int r_cmd_yara_fini(){ if (initialized) { r_list_free (rules_list); yr_finalize(); initialized = false; } return true; } RCorePlugin r_core_plugin_yara = { .name = "yara", .desc = "YARA integration", .license = "LGPL", .call = r_cmd_yara_call, .init = r_cmd_yara_init, .fini = r_cmd_yara_fini }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_CORE, .data = &r_core_plugin_yara, .version = R2_VERSION }; #endif
Java
# Change Log All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ### Added - Added support for decoding HTML entities (decode_html_entities()) (2018-09-28). - Added serialisation through the [cereal](http://uscilab.github.io/cereal/index.html) C++ library. Library headers have been copied to src/CDM/cereal (2017-02-26). - Added UNICODE normalisation (NFC) through boost::locale. - Changed unsigned long to uint32\_t. - Allowed Tcl functions \(tip\_\*\) to accept either CDM objects wrapped as Tcl value objects, or as SWIG objects. For example, all "tip\_GetType [CDM::Annotation -args token]", "tip\_GetType [CDM::Annotation ann token]" and "tip\_GetType {{} token {} {}}" are valid. ### Changed ### Deprecated ### Removed ### Fixed ### Security
Java
package org.yawlfoundation.yawl.worklet.client; import org.yawlfoundation.yawl.editor.ui.specification.SpecificationModel; import org.yawlfoundation.yawl.engine.YSpecificationID; import java.io.IOException; import java.util.Map; /** * @author Michael Adams * @date 18/02/2016 */ public class TaskIDChangeMap { private Map<String, String> _changedIdentifiers; public TaskIDChangeMap(Map<String, String> changeMap) { _changedIdentifiers = changeMap; } public String getID(String oldID) { String newID = _changedIdentifiers.get(oldID); return newID != null ? newID : oldID; } public String getOldID(String newID) { for (String oldID : _changedIdentifiers.keySet()) { if (_changedIdentifiers.get(oldID).equals(newID)) { return oldID; } } return newID; } // called when a user changes a taskID public void add(String oldID, String newID) { // need to handle the case where this id has been updated // more than once between saves _changedIdentifiers.put(getOldID(oldID), newID); } public void saveChanges() { if (! _changedIdentifiers.isEmpty()) { YSpecificationID specID = SpecificationModel.getHandler(). getSpecification().getSpecificationID(); try { if (WorkletClient.getInstance().updateRdrSetTaskIDs(specID, _changedIdentifiers)) { _changedIdentifiers.clear(); } } catch (IOException ignore) { // } } } }
Java
rori_wood_mite_lair_neutral_small_02 = Lair:new { mobiles = {}, spawnLimit = 15, buildingsVeryEasy = {}, buildingsEasy = {}, buildingsMedium = {}, buildingsHard = {}, buildingsVeryHard = {}, } addLairTemplate("rori_wood_mite_lair_neutral_small_02", rori_wood_mite_lair_neutral_small_02)
Java
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PXPVDSDK_PXPVDMEMCLIENT_H #define PXPVDSDK_PXPVDMEMCLIENT_H #include "PxPvdClient.h" #include "PsHashMap.h" #include "PsMutex.h" #include "PsBroadcast.h" #include "PxProfileEventBufferClient.h" #include "PxProfileMemory.h" namespace physx { class PvdDataStream; namespace pvdsdk { class PvdImpl; class PvdMemClient : public PvdClient, public profile::PxProfileEventBufferClient, public shdfnd::UserAllocated { PX_NOCOPY(PvdMemClient) public: PvdMemClient(PvdImpl& pvd); virtual ~PvdMemClient(); bool isConnected() const; void onPvdConnected(); void onPvdDisconnected(); void flush(); PvdDataStream* getDataStream(); PvdUserRenderer* getUserRender(); // memory event void onAllocation(size_t size, const char* typeName, const char* filename, int line, void* allocatedMemory); void onDeallocation(void* addr); private: PvdImpl& mSDKPvd; PvdDataStream* mPvdDataStream; bool mIsConnected; // mem profile shdfnd::Mutex mMutex; // mem onallocation can called from different threads profile::PxProfileMemoryEventBuffer& mMemEventBuffer; void handleBufferFlush(const uint8_t* inData, uint32_t inLength); void handleClientRemoved(); }; } // namespace pvdsdk } // namespace physx #endif // PXPVDSDK_PXPVDMEMCLIENT_H
Java
/** The GPL License (GPL) Copyright (c) 2012 Andreas Herz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA **/ /** * @class graphiti.Connection * A Connection is the line between two {@link graphiti.Port}s. * * @inheritable * @author Andreas Herz * @extends graphiti.shape.basic.Line */ graphiti.Connection = graphiti.shape.basic.PolyLine.extend({ NAME : "graphiti.Connection", DEFAULT_ROUTER: new graphiti.layout.connection.DirectRouter(), //DEFAULT_ROUTER: new graphiti.layout.connection.ManhattanConnectionRouter(), //DEFAULT_ROUTER: new graphiti.layout.connection.BezierConnectionRouter(), //DEFAULT_ROUTER: new graphiti.layout.connection.ConnectionRouter(), /** * @constructor * Creates a new figure element which are not assigned to any canvas. */ init: function() { this._super(); this.sourcePort = null; this.targetPort = null; this.oldPoint=null; this.sourceDecorator = null; /*:graphiti.ConnectionDecorator*/ this.targetDecorator = null; /*:graphiti.ConnectionDecorator*/ // decoration of the polyline // this.startDecoSet = null; this.endDecoSet=null; this.regulated = false; this.draggable = false; this.selectable = false; //this.Activator = new g.Buttons.Activate(); //this.Repressor = new g.Buttons.Inhibit(); //this.remove = new g.Buttons.Remove(); //this.addFigure(this.remove, new graphiti.layout.locator.ConnectionLocator()); this.sourceAnchor = new graphiti.ConnectionAnchor(this); this.targetAnchor = new graphiti.ConnectionAnchor(this); this.router = this.DEFAULT_ROUTER; this.setColor("#4cbf2f"); this.setStroke(3); }, /** * @private **/ disconnect : function() { if (this.sourcePort !== null) { this.sourcePort.detachMoveListener(this); this.fireSourcePortRouteEvent(); } if (this.targetPort !== null) { this.targetPort.detachMoveListener(this); this.fireTargetPortRouteEvent(); } }, /** * @private **/ reconnect : function() { if (this.sourcePort !== null) { this.sourcePort.attachMoveListener(this); this.fireSourcePortRouteEvent(); } if (this.targetPort !== null) { this.targetPort.attachMoveListener(this); this.fireTargetPortRouteEvent(); } this.routingRequired =true; this.repaint(); }, /** * You can't drag&drop the resize handles of a connector. * @type boolean **/ isResizeable : function() { return this.isDraggable(); }, /** * @method * Add a child figure to the Connection. The hands over figure doesn't support drag&drop * operations. It's only a decorator for the connection.<br> * Mainly for labels or other fancy decorations :-) * * @param {graphiti.Figure} figure the figure to add as decoration to the connection. * @param {graphiti.layout.locator.ConnectionLocator} locator the locator for the child. **/ addFigure : function(child, locator) { // just to ensure the right interface for the locator. // The base class needs only 'graphiti.layout.locator.Locator'. if(!(locator instanceof graphiti.layout.locator.ConnectionLocator)){ throw "Locator must implement the class graphiti.layout.locator.ConnectionLocator"; } this._super(child, locator); }, /** * @method * Set the ConnectionDecorator for this object. * * @param {graphiti.decoration.connection.Decorator} the new source decorator for the connection **/ setSourceDecorator:function( decorator) { this.sourceDecorator = decorator; this.routingRequired = true; this.repaint(); }, /** * @method * Get the current source ConnectionDecorator for this object. * * @type graphiti.ConnectionDecorator **/ getSourceDecorator:function() { return this.sourceDecorator; }, /** * @method * Set the ConnectionDecorator for this object. * * @param {graphiti.decoration.connection.Decorator} the new target decorator for the connection **/ setTargetDecorator:function( decorator) { this.targetDecorator = decorator; this.routingRequired =true; this.repaint(); }, /** * @method * Get the current target ConnectionDecorator for this object. * * @type graphiti.ConnectionDecorator **/ getTargetDecorator:function() { return this.targetDecorator; }, /** * @method * Set the ConnectionAnchor for this object. An anchor is responsible for the endpoint calculation * of an connection. * * @param {graphiti.ConnectionAnchor} the new source anchor for the connection **/ setSourceAnchor:function(/*:graphiti.ConnectionAnchor*/ anchor) { this.sourceAnchor = anchor; this.sourceAnchor.setOwner(this.sourcePort); this.routingRequired =true; this.repaint(); }, /** * @method * Set the ConnectionAnchor for this object. * * @param {graphiti.ConnectionAnchor} the new target anchor for the connection **/ setTargetAnchor:function(/*:graphiti.ConnectionAnchor*/ anchor) { this.targetAnchor = anchor; this.targetAnchor.setOwner(this.targetPort); this.routingRequired =true; this.repaint(); }, /** * @method * Set the ConnectionRouter. * **/ setRouter:function(/*:graphiti.ConnectionRouter*/ router) { if(router !==null){ this.router = router; } else{ this.router = new graphiti.layout.connection.NullRouter(); } this.routingRequired =true; // repaint the connection with the new router this.repaint(); }, /** * @method * Return the current active router of this connection. * * @type graphiti.ConnectionRouter **/ getRouter:function() { return this.router; }, /** * @method * Calculate the path of the polyline * * @private */ calculatePath: function(){ if(this.sourcePort===null || this.targetPort===null){ return; } this._super(); }, /** * @private **/ repaint:function(attributes) { if(this.repaintBlocked===true || this.shape===null){ return; } if(this.sourcePort===null || this.targetPort===null){ return; } this._super(attributes); // paint the decorator if any exists // if(this.getSource().getParent().isMoving===false && this.getTarget().getParent().isMoving===false ) { if(this.targetDecorator!==null && this.endDecoSet===null){ this.endDecoSet= this.targetDecorator.paint(this.getCanvas().paper); } if(this.sourceDecorator!==null && this.startDecoSet===null){ this.startDecoSet= this.sourceDecorator.paint(this.getCanvas().paper); } } // translate/transform the decorations to the end/start of the connection // and rotate them as well // if(this.startDecoSet!==null){ this.startDecoSet.transform("r"+this.getStartAngle()+"," + this.getStartX() + "," + this.getStartY()+" t" + this.getStartX() + "," + this.getStartY()); } if(this.endDecoSet!==null){ this.endDecoSet.transform("r"+this.getEndAngle()+"," + this.getEndX() + "," + this.getEndY()+" t" + this.getEndX() + "," + this.getEndY()); } }, postProcess: function(postPorcessCache){ this.router.postProcess(this, this.getCanvas(), postPorcessCache); }, /** * @method * Called by the framework during drag&drop operations. * * @param {graphiti.Figure} draggedFigure The figure which is currently dragging * * @return {Boolean} true if this port accepts the dragging port for a drop operation * @template **/ onDragEnter : function( draggedFigure ) { this.setGlow(true); return true; }, /** * @method * Called if the DragDrop object leaving the current hover figure. * * @param {graphiti.Figure} draggedFigure The figure which is currently dragging * @template **/ onDragLeave:function( draggedFigure ) { this.setGlow(false); }, /** * Return the recalculated position of the start point if we have set an anchor. * * @return graphiti.geo.Point **/ getStartPoint:function() { if(this.isMoving===false){ return this.sourceAnchor.getLocation(this.targetAnchor.getReferencePoint()); } else{ return this._super(); } }, /** * Return the recalculated position of the start point if we have set an anchor. * * @return graphiti.geo.Point **/ getEndPoint:function() { if(this.isMoving===false){ return this.targetAnchor.getLocation(this.sourceAnchor.getReferencePoint()); } else{ return this._super(); } }, /** * @method * Set the new source port of this connection. This enforce a repaint of the connection. * * @param {graphiti.Port} port The new source port of this connection. * **/ setSource:function( port) { if(this.sourcePort!==null){ this.sourcePort.detachMoveListener(this); } this.sourcePort = port; if(this.sourcePort===null){ return; } this.routingRequired = true; this.sourceAnchor.setOwner(this.sourcePort); this.fireSourcePortRouteEvent(); this.sourcePort.attachMoveListener(this); this.setStartPoint(port.getAbsoluteX(), port.getAbsoluteY()); }, /** * @method * Returns the source port of this connection. * * @type graphiti.Port **/ getSource:function() { return this.sourcePort; }, /** * @method * Set the target port of this connection. This enforce a repaint of the connection. * * @param {graphiti.Port} port The new target port of this connection **/ setTarget:function( port) { if(this.targetPort!==null){ this.targetPort.detachMoveListener(this); } this.targetPort = port; if(this.targetPort===null){ return; } this.routingRequired = true; this.targetAnchor.setOwner(this.targetPort); this.fireTargetPortRouteEvent(); this.targetPort.attachMoveListener(this); this.setEndPoint(port.getAbsoluteX(), port.getAbsoluteY()); }, /** * @method * Returns the target port of this connection. * * @type graphiti.Port **/ getTarget:function() { return this.targetPort; }, /** * **/ onOtherFigureIsMoving:function(/*:graphiti.Figure*/ figure) { if(figure===this.sourcePort){ this.setStartPoint(this.sourcePort.getAbsoluteX(), this.sourcePort.getAbsoluteY()); } else{ this.setEndPoint(this.targetPort.getAbsoluteX(), this.targetPort.getAbsoluteY()); } this._super(figure); }, /** * Returns the angle of the connection at the output port (source) * **/ getStartAngle:function() { // return a good default value if the connection is not routed at the // moment if( this.lineSegments.getSize()===0){ return 0; } var p1 = this.lineSegments.get(0).start; var p2 = this.lineSegments.get(0).end; // if(this.router instanceof graphiti.layout.connection.BezierConnectionRouter) // { // p2 = this.lineSegments.get(5).end; // } var length = Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); var angle = -(180/Math.PI) *Math.asin((p1.y-p2.y)/length); if(angle<0) { if(p2.x<p1.x){ angle = Math.abs(angle) + 180; } else{ angle = 360- Math.abs(angle); } } else { if(p2.x<p1.x){ angle = 180-angle; } } return angle; }, getEndAngle:function() { // return a good default value if the connection is not routed at the // moment if (this.lineSegments.getSize() === 0) { return 90; } var p1 = this.lineSegments.get(this.lineSegments.getSize()-1).end; var p2 = this.lineSegments.get(this.lineSegments.getSize()-1).start; // if(this.router instanceof graphiti.layout.connection.BezierConnectionRouter) // { // p2 = this.lineSegments.get(this.lineSegments.getSize()-5).end; // } var length = Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); var angle = -(180/Math.PI) *Math.asin((p1.y-p2.y)/length); if(angle<0) { if(p2.x<p1.x){ angle = Math.abs(angle) + 180; } else{ angle = 360- Math.abs(angle); } } else { if(p2.x<p1.x){ angle = 180-angle; } } return angle; }, /** * @private **/ fireSourcePortRouteEvent:function() { // enforce a repaint of all connections which are related to this port // this is required for a "FanConnectionRouter" or "ShortesPathConnectionRouter" // var connections = this.sourcePort.getConnections(); for(var i=0; i<connections.getSize();i++) { connections.get(i).repaint(); } }, /** * @private **/ fireTargetPortRouteEvent:function() { // enforce a repaint of all connections which are related to this port // this is required for a "FanConnectionRouter" or "ShortesPathConnectionRouter" // var connections = this.targetPort.getConnections(); for(var i=0; i<connections.getSize();i++) { connections.get(i).repaint(); } }, /** * @method * Returns the Command to perform the specified Request or null. * * @param {graphiti.command.CommandType} request describes the Command being requested * @return {graphiti.command.Command} null or a Command **/ createCommand:function( request) { if(request.getPolicy() === graphiti.command.CommandType.MOVE_BASEPOINT) { // DragDrop of a connection doesn't create a undo command at this point. This will be done in // the onDrop method return new graphiti.command.CommandReconnect(this); } return this._super(request); }, /** * @method * Return an objects with all important attributes for XML or JSON serialization * * @returns {Object} */ getPersistentAttributes : function() { var memento = this._super(); delete memento.x; delete memento.y; delete memento.width; delete memento.height; memento.source = { node:this.getSource().getParent().getId(), port: this.getSource().getName() }; memento.target = { node:this.getTarget().getParent().getId(), port:this.getTarget().getName() }; return memento; }, /** * @method * Read all attributes from the serialized properties and transfer them into the shape. * * @param {Object} memento * @returns */ setPersistentAttributes : function(memento) { this._super(memento); // no extra param to read. // Reason: done by the Layoute/Router }, onClick: function() { // wait to be implemented /*$("#right-container").css({right: '0px'}); var hasClassIn = $("#collapseTwo").hasClass('in'); if(!hasClassIn) { $("#collapseOne").toggleClass('in'); $("#collapseOne").css({height: '0'}); $("#collapseTwo").toggleClass('in'); $("#collapseTwo").css({height: "auto"}); } $("#exogenous-factors-config").css({"display": "none"}); $("#protein-config").css({"display": "none"}); $("#component-config").css({"display": "none"}); $("#arrow-config").css({"display": "block"});*/ /*if (this.TYPE == "Activator") { this.TYPE = "Inhibit"; this.setColor(new graphiti.util.Color("#43B967")); } else { this.TYPE = "Activator"; this.setColor(new graphiti.util.Color("#E14545")); }*/ }, /*onDoubleClick: function() { this.getCanvas().removeFigure(this); }*/ });
Java
/* Logic.h -- part of the VaRGB library. Copyright (C) 2013 Pat Deegan. http://www.flyingcarsandstuff.com/projects/vargb/ Created on: 2013-03-05 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See file LICENSE.txt for further informations on licensing terms. ***************************** OVERVIEW ***************************** Unlike the atomic curves "logical" curves, based on the vargb::Curve::Logic class here, don't specify how the red, green and blue values change with time. Instead, these curves act to combine or otherwise transform other curves. The name "Logic Curve" is mainly historical, as these curves started out as simply AND-combined and OR-combined curves. Now additional derivatives exist, such as Shift and Threshold, but whatevs. Logic curves need at least one, or optionally two, curves on which to operate. These are stored in the (protected member) curves[]. The methods are constructed to always check both children for required updates etc, so in cases where you are only operating on a single child curve, the second curve is a static Dummy curve, which basically never requires an update and never terminates. */ #ifndef LOGIC_H_ #define LOGIC_H_ #include "../VaRGBConfig.h" #include "../Curve.h" #include "Dummy.h" namespace vargb { namespace Curve { #define VARGB_CURVE_LOGIC_NUMCURVES 2 class Logic : public vargb::Curve::Curve { public: /* * Logic Curve constructor * Takes one, or two, pointers to other curves on which to operate. */ Logic(vargb::Curve::Curve * curve_a, vargb::Curve::Curve * curve_b=NULL); #ifdef VaRGB_CLASS_DESTRUCTORS_ENABLE virtual ~Logic() {} #endif virtual bool completed(); virtual void settingsUpdated(); virtual void start(IlluminationSettings* initial_settings = NULL); virtual void setTick(VaRGBTimeValue setTo, IlluminationSettings* initial_settings = NULL); virtual void tick(uint8_t num = 1); virtual void reset(); protected: /* * childUpdated() * This base class will check the children to see if they've been updated * after every tick. If this happens to be the case, the childUpdated() * method will be called so the Logic curve instance can do its thing. * * This is an abstract method, which you must override in any derived classes. */ virtual void childUpdated() = 0; vargb::Curve::Curve * curves[VARGB_CURVE_LOGIC_NUMCURVES]; private: static Dummy dummy_curve; }; } /* namespace Curve */ } /* namespace vargb */ #endif /* LOGIC_H_ */
Java
package idare.imagenode.internal.GUI.DataSetController; import idare.imagenode.ColorManagement.ColorScalePane; import idare.imagenode.Interfaces.DataSets.DataSet; import idare.imagenode.Interfaces.Layout.DataSetLayoutProperties; import idare.imagenode.internal.GUI.DataSetController.DataSetSelectionModel.ColorPaneBox; import idare.imagenode.internal.GUI.DataSetController.DataSetSelectionModel.ComboBoxRenderer; import javax.swing.JTable; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; /** * A DataSetSelectionTable, that is specific to the {@link DataSetSelectionModel}, using its unique renderers and editors. * @author Thomas Pfau * */ public class DataSetSelectionTable extends JTable { DataSetSelectionModel tablemodel; public DataSetSelectionTable(DataSetSelectionModel mod) { super(mod); tablemodel = mod; } /** * Move the selected entry (we assume single selection) down one row. * If the selected row is already the top row, nothing happens. */ public void moveEntryUp() { int row = getSelectedRow(); if(row > 0) { tablemodel.moveRowUp(row); } getSelectionModel().setSelectionInterval(row-1, row-1); } /** * Move the selected entry (we assume single selection) down one row. * If the selected row is already the last row, nothing happens. */ public void moveEntryDown() { int row = getSelectedRow(); if(row >= 0 & row < getRowCount()-1 ) { tablemodel.moveRowDown(row); } getSelectionModel().setSelectionInterval(row+1, row+1); } @Override public TableCellEditor getCellEditor(int row, int column) { Object value = super.getValueAt(row, column); if(value != null) { // we need very specific Editors for ColorScales and Dataset Properties. if(value instanceof DataSetLayoutProperties) { return tablemodel.getPropertiesEditor(row); } if(value instanceof ColorScalePane) { return tablemodel.getColorScaleEditor(row); } if(value instanceof DataSet) { return tablemodel.getDataSetEditor(row); } return getDefaultEditor(value.getClass()); } return super.getCellEditor(row, column); } @Override public TableCellRenderer getCellRenderer(int row, int column) { Object value = super.getValueAt(row, column); if(value != null) { // we need very specific renderers for ColorScales and Dataset Properties. if(value instanceof ComboBoxRenderer || value instanceof DataSetLayoutProperties) { TableCellRenderer current = tablemodel.getPropertiesRenderer(row); if(current != null) return current; else return super.getCellRenderer(row, column); } if(value instanceof ColorPaneBox|| value instanceof ColorScalePane) { TableCellRenderer current = tablemodel.getColorScaleRenderer(row); if(current != null) return current; else return super.getCellRenderer(row, column); } return getDefaultRenderer(value.getClass()); } return super.getCellRenderer(row, column); } }
Java
// mksysnum_linux.pl /usr/include/asm/unistd_64.h // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build amd64,linux package unix const ( SYS_READ = 0 SYS_WRITE = 1 SYS_OPEN = 2 SYS_CLOSE = 3 SYS_STAT = 4 SYS_FSTAT = 5 SYS_LSTAT = 6 SYS_POLL = 7 SYS_LSEEK = 8 SYS_MMAP = 9 SYS_MPROTECT = 10 SYS_MUNMAP = 11 SYS_BRK = 12 SYS_RT_SIGACTION = 13 SYS_RT_SIGPROCMASK = 14 SYS_RT_SIGRETURN = 15 SYS_IOCTL = 16 SYS_PREAD64 = 17 SYS_PWRITE64 = 18 SYS_READV = 19 SYS_WRITEV = 20 SYS_ACCESS = 21 SYS_PIPE = 22 SYS_SELECT = 23 SYS_SCHED_YIELD = 24 SYS_MREMAP = 25 SYS_MSYNC = 26 SYS_MINCORE = 27 SYS_MADVISE = 28 SYS_SHMGET = 29 SYS_SHMAT = 30 SYS_SHMCTL = 31 SYS_DUP = 32 SYS_DUP2 = 33 SYS_PAUSE = 34 SYS_NANOSLEEP = 35 SYS_GETITIMER = 36 SYS_ALARM = 37 SYS_SETITIMER = 38 SYS_GETPID = 39 SYS_SENDFILE = 40 SYS_SOCKET = 41 SYS_CONNECT = 42 SYS_ACCEPT = 43 SYS_SENDTO = 44 SYS_RECVFROM = 45 SYS_SENDMSG = 46 SYS_RECVMSG = 47 SYS_SHUTDOWN = 48 SYS_BIND = 49 SYS_LISTEN = 50 SYS_GETSOCKNAME = 51 SYS_GETPEERNAME = 52 SYS_SOCKETPAIR = 53 SYS_SETSOCKOPT = 54 SYS_GETSOCKOPT = 55 SYS_CLONE = 56 SYS_FORK = 57 SYS_VFORK = 58 SYS_EXECVE = 59 SYS_EXIT = 60 SYS_WAIT4 = 61 SYS_KILL = 62 SYS_UNAME = 63 SYS_SEMGET = 64 SYS_SEMOP = 65 SYS_SEMCTL = 66 SYS_SHMDT = 67 SYS_MSGGET = 68 SYS_MSGSND = 69 SYS_MSGRCV = 70 SYS_MSGCTL = 71 SYS_FCNTL = 72 SYS_FLOCK = 73 SYS_FSYNC = 74 SYS_FDATASYNC = 75 SYS_TRUNCATE = 76 SYS_FTRUNCATE = 77 SYS_GETDENTS = 78 SYS_GETCWD = 79 SYS_CHDIR = 80 SYS_FCHDIR = 81 SYS_RENAME = 82 SYS_MKDIR = 83 SYS_RMDIR = 84 SYS_CREAT = 85 SYS_LINK = 86 SYS_UNLINK = 87 SYS_SYMLINK = 88 SYS_READLINK = 89 SYS_CHMOD = 90 SYS_FCHMOD = 91 SYS_CHOWN = 92 SYS_FCHOWN = 93 SYS_LCHOWN = 94 SYS_UMASK = 95 SYS_GETTIMEOFDAY = 96 SYS_GETRLIMIT = 97 SYS_GETRUSAGE = 98 SYS_SYSINFO = 99 SYS_TIMES = 100 SYS_PTRACE = 101 SYS_GETUID = 102 SYS_SYSLOG = 103 SYS_GETGID = 104 SYS_SETUID = 105 SYS_SETGID = 106 SYS_GETEUID = 107 SYS_GETEGID = 108 SYS_SETPGID = 109 SYS_GETPPID = 110 SYS_GETPGRP = 111 SYS_SETSID = 112 SYS_SETREUID = 113 SYS_SETREGID = 114 SYS_GETGROUPS = 115 SYS_SETGROUPS = 116 SYS_SETRESUID = 117 SYS_GETRESUID = 118 SYS_SETRESGID = 119 SYS_GETRESGID = 120 SYS_GETPGID = 121 SYS_SETFSUID = 122 SYS_SETFSGID = 123 SYS_GETSID = 124 SYS_CAPGET = 125 SYS_CAPSET = 126 SYS_RT_SIGPENDING = 127 SYS_RT_SIGTIMEDWAIT = 128 SYS_RT_SIGQUEUEINFO = 129 SYS_RT_SIGSUSPEND = 130 SYS_SIGALTSTACK = 131 SYS_UTIME = 132 SYS_MKNOD = 133 SYS_USELIB = 134 SYS_PERSONALITY = 135 SYS_USTAT = 136 SYS_STATFS = 137 SYS_FSTATFS = 138 SYS_SYSFS = 139 SYS_GETPRIORITY = 140 SYS_SETPRIORITY = 141 SYS_SCHED_SETPARAM = 142 SYS_SCHED_GETPARAM = 143 SYS_SCHED_SETSCHEDULER = 144 SYS_SCHED_GETSCHEDULER = 145 SYS_SCHED_GET_PRIORITY_MAX = 146 SYS_SCHED_GET_PRIORITY_MIN = 147 SYS_SCHED_RR_GET_INTERVAL = 148 SYS_MLOCK = 149 SYS_MUNLOCK = 150 SYS_MLOCKALL = 151 SYS_MUNLOCKALL = 152 SYS_VHANGUP = 153 SYS_MODIFY_LDT = 154 SYS_PIVOT_ROOT = 155 SYS__SYSCTL = 156 SYS_PRCTL = 157 SYS_ARCH_PRCTL = 158 SYS_ADJTIMEX = 159 SYS_SETRLIMIT = 160 SYS_CHROOT = 161 SYS_SYNC = 162 SYS_ACCT = 163 SYS_SETTIMEOFDAY = 164 SYS_MOUNT = 165 SYS_UMOUNT2 = 166 SYS_SWAPON = 167 SYS_SWAPOFF = 168 SYS_REBOOT = 169 SYS_SENTRUSTOSTNAME = 170 SYS_SETDOMAINNAME = 171 SYS_IOPL = 172 SYS_IOPERM = 173 SYS_CREATE_MODULE = 174 SYS_INIT_MODULE = 175 SYS_DELETE_MODULE = 176 SYS_GET_KERNEL_SYMS = 177 SYS_QUERY_MODULE = 178 SYS_QUOTACTL = 179 SYS_NFSSERVCTL = 180 SYS_GETPMSG = 181 SYS_PUTPMSG = 182 SYS_AFS_SYSCALL = 183 SYS_TUXCALL = 184 SYS_SECURITY = 185 SYS_GETTID = 186 SYS_READAHEAD = 187 SYS_SETXATTR = 188 SYS_LSETXATTR = 189 SYS_FSETXATTR = 190 SYS_GETXATTR = 191 SYS_LGETXATTR = 192 SYS_FGETXATTR = 193 SYS_LISTXATTR = 194 SYS_LLISTXATTR = 195 SYS_FLISTXATTR = 196 SYS_REMOVEXATTR = 197 SYS_LREMOVEXATTR = 198 SYS_FREMOVEXATTR = 199 SYS_TKILL = 200 SYS_TIME = 201 SYS_FUTEX = 202 SYS_SCHED_SETAFFINITY = 203 SYS_SCHED_GETAFFINITY = 204 SYS_SET_THREAD_AREA = 205 SYS_IO_SETUP = 206 SYS_IO_DESTROY = 207 SYS_IO_GETEVENTS = 208 SYS_IO_SUBMIT = 209 SYS_IO_CANCEL = 210 SYS_GET_THREAD_AREA = 211 SYS_LOOKUP_DCOOKIE = 212 SYS_EPOLL_CREATE = 213 SYS_EPOLL_CTL_OLD = 214 SYS_EPOLL_WAIT_OLD = 215 SYS_REMAP_FILE_PAGES = 216 SYS_GETDENTS64 = 217 SYS_SET_TID_ADDRESS = 218 SYS_RESTART_SYSCALL = 219 SYS_SEMTIMEDOP = 220 SYS_FADVISE64 = 221 SYS_TIMER_CREATE = 222 SYS_TIMER_SETTIME = 223 SYS_TIMER_GETTIME = 224 SYS_TIMER_GETOVERRUN = 225 SYS_TIMER_DELETE = 226 SYS_CLOCK_SETTIME = 227 SYS_CLOCK_GETTIME = 228 SYS_CLOCK_GETRES = 229 SYS_CLOCK_NANOSLEEP = 230 SYS_EXIT_GROUP = 231 SYS_EPOLL_WAIT = 232 SYS_EPOLL_CTL = 233 SYS_TGKILL = 234 SYS_UTIMES = 235 SYS_VSERVER = 236 SYS_MBIND = 237 SYS_SET_MEMPOLICY = 238 SYS_GET_MEMPOLICY = 239 SYS_MQ_OPEN = 240 SYS_MQ_UNLINK = 241 SYS_MQ_TIMEDSEND = 242 SYS_MQ_TIMEDRECEIVE = 243 SYS_MQ_NOTIFY = 244 SYS_MQ_GETSETATTR = 245 SYS_KEXEC_LOAD = 246 SYS_WAITID = 247 SYS_ADD_KEY = 248 SYS_REQUEST_KEY = 249 SYS_KEYCTL = 250 SYS_IOPRIO_SET = 251 SYS_IOPRIO_GET = 252 SYS_INOTIFY_INIT = 253 SYS_INOTIFY_ADD_WATCH = 254 SYS_INOTIFY_RM_WATCH = 255 SYS_MIGRATE_PAGES = 256 SYS_OPENAT = 257 SYS_MKDIRAT = 258 SYS_MKNODAT = 259 SYS_FCHOWNAT = 260 SYS_FUTIMESAT = 261 SYS_NEWFSTATAT = 262 SYS_UNLINKAT = 263 SYS_RENAMEAT = 264 SYS_LINKAT = 265 SYS_SYMLINKAT = 266 SYS_READLINKAT = 267 SYS_FCHMODAT = 268 SYS_FACCESSAT = 269 SYS_PSELECT6 = 270 SYS_PPOLL = 271 SYS_UNSHARE = 272 SYS_SET_ROBUST_LIST = 273 SYS_GET_ROBUST_LIST = 274 SYS_SPLICE = 275 SYS_TEE = 276 SYS_SYNC_FILE_RANGE = 277 SYS_VMSPLICE = 278 SYS_MOVE_PAGES = 279 SYS_UTIMENSAT = 280 SYS_EPOLL_PWAIT = 281 SYS_SIGNALFD = 282 SYS_TIMERFD_CREATE = 283 SYS_EVENTFD = 284 SYS_FALLOCATE = 285 SYS_TIMERFD_SETTIME = 286 SYS_TIMERFD_GETTIME = 287 SYS_ACCEPT4 = 288 SYS_SIGNALFD4 = 289 SYS_EVENTFD2 = 290 SYS_EPOLL_CREATE1 = 291 SYS_DUP3 = 292 SYS_PIPE2 = 293 SYS_INOTIFY_INIT1 = 294 SYS_PREADV = 295 SYS_PWRITEV = 296 SYS_RT_TGSIGQUEUEINFO = 297 SYS_PERF_EVENT_OPEN = 298 SYS_RECVMMSG = 299 SYS_FANOTIFY_INIT = 300 SYS_FANOTIFY_MARK = 301 SYS_PRLIMIT64 = 302 SYS_NAME_TO_HANDLE_AT = 303 SYS_OPEN_BY_HANDLE_AT = 304 SYS_CLOCK_ADJTIME = 305 SYS_SYNCFS = 306 SYS_SENDMMSG = 307 SYS_SETNS = 308 SYS_GETCPU = 309 SYS_PROCESS_VM_READV = 310 SYS_PROCESS_VM_WRITEV = 311 )
Java
/* Mesquite source code. Copyright 1997-2009 W. Maddison and D. Maddison. Version 2.7, August 2009. Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code. The commenting leaves much to be desired. Please approach this source code with the spirit of helping out. Perhaps with your help we can be more than a few, and make Mesquite better. Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. Mesquite's web site is http://mesquiteproject.org This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.lib; import java.util.*; import java.io.*; import org.dom4j.*; import org.dom4j.io.*; public class XMLUtil { /*.................................................................................................................*/ public static Element addFilledElement(Element containingElement, String name, String content) { if (content == null || name == null) return null; Element element = DocumentHelper.createElement(name); element.addText(content); containingElement.add(element); return element; } /*.................................................................................................................*/ public static Element addFilledElement(Element containingElement, String name, CDATA cdata) { if (cdata == null || name == null) return null; Element element = DocumentHelper.createElement(name); element.add(cdata); containingElement.add(element); return element; } public static String getTextFromElement(Element containingElement, String name){ Element e = containingElement.element(name); if (e == null) return null; else return e.getText(); } /*.................................................................................................................*/ public static String getDocumentAsXMLString(Document doc, boolean escapeText) { try { String encoding = doc.getXMLEncoding(); if (encoding == null) encoding = "UTF-8"; Writer osw = new StringWriter(); OutputFormat opf = new OutputFormat(" ", true, encoding); XMLWriter writer = new XMLWriter(osw, opf); writer.setEscapeText(escapeText); writer.write(doc); writer.close(); return osw.toString(); } catch (IOException e) { MesquiteMessage.warnProgrammer("XML Document could not be returned as string."); } return null; } /*.................................................................................................................*/ public static String getElementAsXMLString(Element doc, String encoding, boolean escapeText) { try { Writer osw = new StringWriter(); OutputFormat opf = new OutputFormat(" ", true, encoding); XMLWriter writer = new XMLWriter(osw, opf); writer.setEscapeText(escapeText); writer.write(doc); writer.close(); return osw.toString(); } catch (IOException e) { MesquiteMessage.warnProgrammer("XML Document could not be returned as string."); } return null; } /*.................................................................................................................*/ public static String getDocumentAsXMLString(Document doc) { return getDocumentAsXMLString(doc,true); } /*.................................................................................................................*/ public static String getDocumentAsXMLString2(Document doc) { try { String encoding = doc.getXMLEncoding(); //if (encoding == null) // encoding = "UTF-8"; Writer osw = new StringWriter(); OutputFormat opf = new OutputFormat(" ", true); XMLWriter writer = new XMLWriter(osw, opf); writer.write(doc); writer.close(); return osw.toString(); } catch (IOException e) { MesquiteMessage.warnProgrammer("XML Document could not be returned as string."); } return null; } /*.................................................................................................................*/ public static Document getDocumentFromString(String rootElementName, String contents) { Document doc = null; try { doc = DocumentHelper.parseText(contents); } catch (Exception e) { return null; } if (doc == null || doc.getRootElement() == null) { return null; } else if (!StringUtil.blank(rootElementName) && !doc.getRootElement().getName().equals(rootElementName)) { return null; } return doc; } /*.................................................................................................................*/ public static Document getDocumentFromString(String contents) { return getDocumentFromString("",contents); } /*.................................................................................................................*/ public static Element getRootXMLElementFromString(String rootElementName, String contents) { Document doc = getDocumentFromString(rootElementName, contents); if (doc==null) return null; return doc.getRootElement(); } /*.................................................................................................................*/ public static Element getRootXMLElementFromString(String contents) { return getRootXMLElementFromString("",contents); } /*.................................................................................................................*/ public static Element getRootXMLElementFromURL(String rootElementName, String url) { SAXReader saxReader = new SAXReader(); Document doc = null; try { doc = saxReader.read(url); } catch (Exception e) { return null; } if (doc == null || doc.getRootElement() == null) { return null; } else if (!StringUtil.blank(rootElementName) && !doc.getRootElement().getName().equals(rootElementName)) { return null; } Element root = doc.getRootElement(); return root; } /*.................................................................................................................*/ public static Element getRootXMLElementFromURL(String url) { return getRootXMLElementFromURL("",url); } /*.................................................................................................................*/ public static void readXMLPreferences(MesquiteModule module, XMLPreferencesProcessor xmlPrefProcessor, String contents) { Element root = getRootXMLElementFromString("mesquite",contents); if (root==null) return; Element element = root.element(module.getXMLModuleName()); if (element != null) { Element versionElement = element.element("version"); if (versionElement == null) return ; else { int version = MesquiteInteger.fromString(element.elementText("version")); boolean acceptableVersion = (module.getXMLPrefsVersion()==version || !module.xmlPrefsVersionMustMatch()); if (acceptableVersion) processPreferencesFromXML(xmlPrefProcessor, element); else return; } } } /*.................................................................................................................*/ public static void processPreferencesFromXML ( XMLPreferencesProcessor xmlPrefProcessor, Element element) { List prefElement = element.elements(); for (Iterator iter = prefElement.iterator(); iter.hasNext();) { // this is going through all of the notices Element messageElement = (Element) iter.next(); xmlPrefProcessor.processSingleXMLPreference(messageElement.getName(), messageElement.getText()); } } }
Java
/* * XAdES4j - A Java library for generation and verification of XAdES signatures. * Copyright (C) 2010 Luis Goncalves. * * XAdES4j is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or any later version. * * XAdES4j 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 XAdES4j. If not, see <http://www.gnu.org/licenses/>. */ package xades4j.xml.marshalling; import java.util.EnumMap; import java.util.List; import xades4j.properties.IdentifierType; import xades4j.properties.ObjectIdentifier; import xades4j.properties.data.BaseCertRefsData; import xades4j.properties.data.CertRef; import xades4j.xml.bind.xades.XmlCertIDListType; import xades4j.xml.bind.xades.XmlCertIDType; import xades4j.xml.bind.xades.XmlDigestAlgAndValueType; import xades4j.xml.bind.xades.XmlIdentifierType; import xades4j.xml.bind.xades.XmlObjectIdentifierType; import xades4j.xml.bind.xades.XmlQualifierType; import xades4j.xml.bind.xmldsig.XmlDigestMethodType; import xades4j.xml.bind.xmldsig.XmlX509IssuerSerialType; /** * @author Luís */ class ToXmlUtils { ToXmlUtils() { } private static final EnumMap<IdentifierType, XmlQualifierType> identifierTypeConv; static { identifierTypeConv = new EnumMap(IdentifierType.class); identifierTypeConv.put(IdentifierType.OIDAsURI, XmlQualifierType.OID_AS_URI); identifierTypeConv.put(IdentifierType.OIDAsURN, XmlQualifierType.OID_AS_URN); } static XmlObjectIdentifierType getXmlObjectId(ObjectIdentifier objId) { XmlObjectIdentifierType xmlObjId = new XmlObjectIdentifierType(); // Object identifier XmlIdentifierType xmlId = new XmlIdentifierType(); xmlId.setValue(objId.getIdentifier()); // If it is IdentifierType.URI the converter returns null, which is the // same as not specifying a qualifier. xmlId.setQualifier(identifierTypeConv.get(objId.getIdentifierType())); xmlObjId.setIdentifier(xmlId); return xmlObjId; } /**/ static XmlCertIDListType getXmlCertRefList(BaseCertRefsData certRefsData) { XmlCertIDListType xmlCertRefListProp = new XmlCertIDListType(); List<XmlCertIDType> xmlCertRefList = xmlCertRefListProp.getCert(); XmlDigestAlgAndValueType certDigest; XmlDigestMethodType certDigestMethod; XmlX509IssuerSerialType issuerSerial; XmlCertIDType certID; for (CertRef certRef : certRefsData.getCertRefs()) { certDigestMethod = new XmlDigestMethodType(); certDigestMethod.setAlgorithm(certRef.digestAlgUri); certDigest = new XmlDigestAlgAndValueType(); certDigest.setDigestMethod(certDigestMethod); certDigest.setDigestValue(certRef.digestValue); issuerSerial = new XmlX509IssuerSerialType(); issuerSerial.setX509IssuerName(certRef.issuerDN); issuerSerial.setX509SerialNumber(certRef.serialNumber); certID = new XmlCertIDType(); certID.setCertDigest(certDigest); certID.setIssuerSerial(issuerSerial); xmlCertRefList.add(certID); } return xmlCertRefListProp; } }
Java
/* * This file is part of RskJ * Copyright (C) 2017 RSK Labs Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 <http://www.gnu.org/licenses/>. */ package co.rsk.core; import com.google.common.primitives.UnsignedBytes; import org.ethereum.rpc.TypeConverter; import org.ethereum.util.ByteUtil; import org.ethereum.vm.DataWord; import java.util.Arrays; import java.util.Comparator; /** * Immutable representation of an RSK address. * It is a simple wrapper on the raw byte[]. * * @author Ariel Mendelzon */ public class RskAddress { /** * This is the size of an RSK address in bytes. */ public static final int LENGTH_IN_BYTES = 20; private static final RskAddress NULL_ADDRESS = new RskAddress(); /** * This compares using the lexicographical order of the sender unsigned bytes. */ public static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR = Comparator.comparing( RskAddress::getBytes, UnsignedBytes.lexicographicalComparator()); private final byte[] bytes; /** * @param address a data word containing an address in the last 20 bytes. */ public RskAddress(DataWord address) { this(address.getLast20Bytes()); } /** * @param address the hex-encoded 20 bytes long address, with or without 0x prefix. */ public RskAddress(String address) { this(TypeConverter.stringHexToByteArray(address)); } /** * @param bytes the 20 bytes long raw address bytes. */ public RskAddress(byte[] bytes) { if (bytes.length != LENGTH_IN_BYTES) { throw new RuntimeException(String.format("An RSK address must be %d bytes long", LENGTH_IN_BYTES)); } this.bytes = bytes; } /** * This instantiates the contract creation address. */ private RskAddress() { this.bytes = new byte[0]; } /** * @return the null address, which is the receiver of contract creation transactions. */ public static RskAddress nullAddress() { return NULL_ADDRESS; } public byte[] getBytes() { return bytes; } public String toHexString() { return ByteUtil.toHexString(bytes); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } RskAddress otherSender = (RskAddress) other; return Arrays.equals(bytes, otherSender.bytes); } @Override public int hashCode() { return Arrays.hashCode(bytes); } /** * @return a DEBUG representation of the address, mainly used for logging. */ @Override public String toString() { return toHexString(); } public String toJsonString() { if (NULL_ADDRESS.equals(this)) { return null; } return TypeConverter.toUnformattedJsonHex(this.getBytes()); } }
Java
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "deleterepositoryresponse.h" #include "deleterepositoryresponse_p.h" #include <QDebug> #include <QNetworkReply> #include <QXmlStreamReader> namespace QtAws { namespace ECRPublic { /*! * \class QtAws::ECRPublic::DeleteRepositoryResponse * \brief The DeleteRepositoryResponse class provides an interace for ECRPublic DeleteRepository responses. * * \inmodule QtAwsECRPublic * * <fullname>Amazon Elastic Container Registry Public</fullname> * * Amazon Elastic Container Registry (Amazon ECR) is a managed container image registry service. Amazon ECR provides both * public and private registries to host your container images. You can use the familiar Docker CLI, or their preferred * client, to push, pull, and manage images. Amazon ECR provides a secure, scalable, and reliable registry for your Docker * or Open Container Initiative (OCI) images. Amazon ECR supports public repositories with this API. For information about * the Amazon ECR API for private repositories, see <a * href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/Welcome.html">Amazon Elastic Container Registry API * * \sa ECRPublicClient::deleteRepository */ /*! * Constructs a DeleteRepositoryResponse object for \a reply to \a request, with parent \a parent. */ DeleteRepositoryResponse::DeleteRepositoryResponse( const DeleteRepositoryRequest &request, QNetworkReply * const reply, QObject * const parent) : ECRPublicResponse(new DeleteRepositoryResponsePrivate(this), parent) { setRequest(new DeleteRepositoryRequest(request)); setReply(reply); } /*! * \reimp */ const DeleteRepositoryRequest * DeleteRepositoryResponse::request() const { Q_D(const DeleteRepositoryResponse); return static_cast<const DeleteRepositoryRequest *>(d->request); } /*! * \reimp * Parses a successful ECRPublic DeleteRepository \a response. */ void DeleteRepositoryResponse::parseSuccess(QIODevice &response) { //Q_D(DeleteRepositoryResponse); QXmlStreamReader xml(&response); /// @todo } /*! * \class QtAws::ECRPublic::DeleteRepositoryResponsePrivate * \brief The DeleteRepositoryResponsePrivate class provides private implementation for DeleteRepositoryResponse. * \internal * * \inmodule QtAwsECRPublic */ /*! * Constructs a DeleteRepositoryResponsePrivate object with public implementation \a q. */ DeleteRepositoryResponsePrivate::DeleteRepositoryResponsePrivate( DeleteRepositoryResponse * const q) : ECRPublicResponsePrivate(q) { } /*! * Parses a ECRPublic DeleteRepository response element from \a xml. */ void DeleteRepositoryResponsePrivate::parseDeleteRepositoryResponse(QXmlStreamReader &xml) { Q_ASSERT(xml.name() == QLatin1String("DeleteRepositoryResponse")); Q_UNUSED(xml) ///< @todo } } // namespace ECRPublic } // namespace QtAws
Java
#pragma once #include <type_traits> #include <limits> #include <utility> namespace sio { template<typename T> struct is_bit_enum: public std::false_type {}; template<typename Enum, std::enable_if_t<std::is_enum<Enum>{}, int> = 0> class bitfield { public: using integer = std::underlying_type_t<Enum>; private: integer bits; public: constexpr bitfield() noexcept: bits(0) {} constexpr bitfield(Enum bit) noexcept: bits(static_cast<integer>(bit)) {} explicit constexpr bitfield(integer value) noexcept: bits(value) {} bitfield &operator|=(bitfield rhs) noexcept { bits |= rhs.bits; return *this; } bitfield &operator&=(bitfield rhs) noexcept { bits &= rhs.bits; return *this; } bitfield &operator^=(bitfield rhs) noexcept { bits ^= rhs.bits; return *this; } constexpr bitfield operator|(bitfield rhs) const noexcept { return bitfield { bits | rhs.bits }; } constexpr bitfield operator&(bitfield rhs) const noexcept { return bitfield { bits & rhs.bits }; } constexpr bitfield operator^(bitfield rhs) const noexcept { return bitfield { bits ^ rhs.bits }; } constexpr bitfield operator~() const noexcept { return bitfield { ~bits }; } constexpr operator bool() const noexcept { return !!bits; } constexpr bool operator==(bitfield rhs) const noexcept { return bits == rhs.bits; } constexpr bool operator!=(bitfield rhs) const noexcept { return bits != rhs.bits; } }; template<typename Writer, typename Enum> void write(Writer &&w, bitfield<Enum> field) { bool first = true; for (int i = std::numeric_limits<typename bitfield<Enum>::integer>::digits-1; i >= 0; --i) { Enum bit = static_cast<Enum>(1 << i); if (field & bit) { if (!first) { write(std::forward<Writer>(w), " | "); } else { first = false; } write(std::forward<Writer>(w), bit); } } } } // namespace sio template<typename Enum, std::enable_if_t<sio::is_bit_enum<Enum>{}, int> = 0> sio::bitfield<Enum> operator|(Enum lhs, sio::bitfield<decltype(lhs)> rhs) { return rhs | lhs; } template<typename Enum, std::enable_if_t<sio::is_bit_enum<Enum>{}, int> = 0> sio::bitfield<Enum> operator&(Enum lhs, sio::bitfield<decltype(lhs)> rhs) { return rhs & lhs; } template<typename Enum, std::enable_if_t<sio::is_bit_enum<Enum>{}, int> = 0> sio::bitfield<Enum> operator^(Enum lhs, sio::bitfield<decltype(lhs)> rhs) { return rhs ^ lhs; } template<typename Enum, std::enable_if_t<sio::is_bit_enum<Enum>{}, int> = 0> sio::bitfield<Enum> operator~(Enum lhs) { return ~sio::bitfield<Enum>(lhs); }
Java
package com.hyenawarrior.oldnorsedictionary.modelview.meaning_panel import android.app.Activity import android.view.{View, ViewGroup} import android.widget.{EditText, TextView} import com.hyenawarrior.oldnorsedictionary.R import com.hyenawarrior.oldnorsedictionary.modelview.{ClickListener, DynamicListView, EditTextTypeListener} import com.hyenawarrior.oldnorsedictionary.new_word.pages.MeaningDef /** * Created by HyenaWarrior on 2017.07.22.. */ class MeaningDefListView(activity: Activity, hostView: ViewGroup) extends DynamicListView[MeaningDef](hostView, R.layout.meaning_record, activity) { private var meanings: Map[View, (String, String, ExampleRecordView)] = Map() override protected def applyToView(optElem: Option[MeaningDef], meaningRecordView: View): Unit = { val elem = optElem getOrElse MeaningDef("", "", Seq()) val btnRemove = meaningRecordView.findViewById[View](R.id.ibRemove) btnRemove setOnClickListener ClickListener(onRemoveMeaningDef(meaningRecordView)) val etMeaning = meaningRecordView.findViewById[EditText](R.id.et_setmeaning_Desc) etMeaning.setText(elem.meaning, TextView.BufferType.EDITABLE) etMeaning addTextChangedListener new EditTextTypeListener(onMeaningChange(meaningRecordView)) val etNote = meaningRecordView.findViewById[EditText](R.id.et_setmeaning_Note) etNote.setText(elem.note, TextView.BufferType.EDITABLE) etNote addTextChangedListener new EditTextTypeListener(onNoteChange(meaningRecordView)) val subControlOfHost = meaningRecordView.findViewById[ViewGroup](R.id.tl_setmeaning_Examples) val exRecHandler = new ExampleRecordView(activity, subControlOfHost) for(exStr <- elem.examples) { exRecHandler add exStr } meanings = meanings + ((meaningRecordView, (elem.meaning, elem.note, exRecHandler))) } private def onRemoveMeaningDef(meaningRecordView: View)(): Unit = { meanings = meanings - meaningRecordView remove(meaningRecordView) } private def onMeaningChange(meaningRecordView: View)(text: String): Unit = { val item = meanings(meaningRecordView) val newEntry = (meaningRecordView, (text, item._2, item._3)) meanings = (meanings - meaningRecordView) + newEntry } private def onNoteChange(meaningRecordView: View)(text: String): Unit = { val item = meanings(meaningRecordView) val newEntry = (meaningRecordView, (item._1, text, item._3)) meanings = (meanings - meaningRecordView) + newEntry } def fetch(): List[MeaningDef] = meanings.values.map { case (meaning, note, exs) => MeaningDef(meaning, note, exs.fetch()) } .toList }
Java
#include <bits/stdc++.h> using namespace std; #define DEBUG // comment this line to pull out print statements #ifdef DEBUG // completely copied from http://saadahmad.ca/cc-preprocessor-metaprogramming-2/ const char NEWLINE[] = "\n"; const char TAB[] = "\t"; #define EMPTY() #define DEFER(...) __VA_ARGS__ EMPTY() #define DEFER2(...) __VA_ARGS__ DEFER(EMPTY) () #define DEFER3(...) __VA_ARGS__ DEFER2(EMPTY) () #define EVAL_1(...) __VA_ARGS__ #define EVAL_2(...) EVAL_1(EVAL_1(__VA_ARGS__)) #define EVAL_3(...) EVAL_2(EVAL_2(__VA_ARGS__)) #define EVAL_4(...) EVAL_3(EVAL_3(__VA_ARGS__)) #define EVAL_5(...) EVAL_4(EVAL_4(__VA_ARGS__)) #define EVAL_6(...) EVAL_5(EVAL_5(__VA_ARGS__)) #define EVAL_7(...) EVAL_6(EVAL_6(__VA_ARGS__)) #define EVAL_8(...) EVAL_7(EVAL_7(__VA_ARGS__)) #define EVAL(...) EVAL_8(__VA_ARGS__) #define NOT_0 EXISTS(1) #define NOT(x) TRY_EXTRACT_EXISTS ( CAT(NOT_, x), 0 ) #define IS_ENCLOSED(x, ...) TRY_EXTRACT_EXISTS ( IS_ENCLOSED_TEST x, 0 ) #define ENCLOSE_EXPAND(...) EXPANDED, ENCLOSED, (__VA_ARGS__) ) EAT ( #define GET_CAT_EXP(a, b) (a, ENCLOSE_EXPAND b, DEFAULT, b ) #define CAT_WITH_ENCLOSED(a, b) a b #define CAT_WITH_DEFAULT(a, b) a ## b #define CAT_WITH(a, _, f, b) CAT_WITH_ ## f (a, b) #define EVAL_CAT_WITH(...) CAT_WITH __VA_ARGS__ #define CAT(a, b) EVAL_CAT_WITH ( GET_CAT_EXP(a, b) ) #define IF_1(true, ...) true #define IF_0(true, ...) __VA_ARGS__ #define IF(value) CAT(IF_, value) #define HEAD(x, ...) x #define TAIL(x, ...) __VA_ARGS__ #define TEST_LAST EXISTS(1) #define IS_LIST_EMPTY(...) TRY_EXTRACT_EXISTS( DEFER(HEAD) (__VA_ARGS__ EXISTS(1)) , 0) #define IS_LIST_NOT_EMPTY(...) NOT(IS_LIST_EMPTY(__VA_ARGS__)) #define DOES_VALUE_EXIST_EXISTS(...) 1 #define DOES_VALUE_EXIST_DOESNT_EXIST 0 #define DOES_VALUE_EXIST(x) CAT(DOES_VALUE_EXIST_, x) #define TRY_EXTRACT_EXISTS(value, ...) IF ( DOES_VALUE_EXIST(TEST_EXISTS(value)) ) \ ( EXTRACT_VALUE(value), __VA_ARGS__ ) #define EXTRACT_VALUE_EXISTS(...) __VA_ARGS__ #define EXTRACT_VALUE(value) CAT(EXTRACT_VALUE_, value) #define EAT(...) #define EXPAND_TEST_EXISTS(...) EXPANDED, EXISTS(__VA_ARGS__) ) EAT ( #define GET_TEST_EXISTS_RESULT(x) ( CAT(EXPAND_TEST_, x), DOESNT_EXIST ) #define GET_TEST_EXIST_VALUE_(expansion, existValue) existValue #define GET_TEST_EXIST_VALUE(x) GET_TEST_EXIST_VALUE_ x #define TEST_EXISTS(x) GET_TEST_EXIST_VALUE ( GET_TEST_EXISTS_RESULT(x) ) #define ENCLOSE(...) ( __VA_ARGS__ ) #define REM_ENCLOSE_(...) __VA_ARGS__ #define REM_ENCLOSE(...) REM_ENCLOSE_ __VA_ARGS__ #define IF_ENCLOSED_1(true, ...) true #define IF_ENCLOSED_0(true, ...) __VA_ARGS__ #define IF_ENCLOSED(...) CAT(IF_ENCLOSED_, IS_ENCLOSED(__VA_ARGS__)) #define OPT_REM_ENCLOSE(...) \ IF_ENCLOSED (__VA_ARGS__) ( REM_ENCLOSE(__VA_ARGS__), __VA_ARGS__ ) #define FOR_EACH_INDIRECT() FOR_EACH_NO_EVAL #define FOR_EACH_NO_EVAL(fVisitor, ...) \ IF ( IS_LIST_NOT_EMPTY( __VA_ARGS__ ) ) \ ( \ fVisitor( OPT_REM_ENCLOSE(HEAD(__VA_ARGS__)) ) \ DEFER2 ( FOR_EACH_INDIRECT )() (fVisitor, TAIL(__VA_ARGS__)) \ ) #define FOR_EACH(fVisitor, ...) \ EVAL(FOR_EACH_NO_EVAL(fVisitor, __VA_ARGS__)) #define STRINGIFY(x) #x #define DUMP_VAR(x) std::cout << STRINGIFY(x) << ": " << x << TAB; #define debug(...) FOR_EACH(DUMP_VAR, __VA_ARGS__); std::cout << NEWLINE; #define dbg(block) block #else #define debug(...) #define dbg(block) #endif const double EPS = 1E-9; // --- GEOMETRY --- // --- points, lines, functions for lines and points, triangles, // --- circles. // -- insert geometry.hh here for geometric functions // --- END GEOMETRY --- typedef vector<int> vi; typedef vector<pair<int,int>> vii; #define UN(v) SORT(v),v.erase(unique(v.begin(),v.end()),v.end()) #define SORT(c) sort((c).begin(),(c).end()) #define FOR(i,a,b) for (int i=(a); i < (b); i++) #define REP(i,n) FOR(i,0,(int)n) #define CL(a,b) memset(a,b,sizeof(a)) #define CL2d(a,b,x,y) memset(a, b, sizeof(a[0][0])*x*y) /* global variables */ int W, N; int l, w; int i, j, k; char Ws[20], Ns[20]; int total_area; char line[100]; //char answers[10000][21]; char answers[100000]; int ans, ansb; int tlen, clen; /* global variables */ void dump() { // dump data } bool getInput() { if (feof(stdin)) return false; return true; } void process() { // int a = 2, b = 5, c = 3; // debug(a, b, c); // debugging example // printf("%d\n", total_area/W); } int main() { ios_base::sync_with_stdio(false); char digits[10]; fgets_unlocked(line, 99, stdin); do { for (i = 0; line[i] != '\n'; ++i) { Ws[i] = line[i]; } Ws[i] = 0; for (k = 0; k < i-1; ++k) { W += Ws[k]-'0'; W *= 10; } W += Ws[k]-'0'; fgets_unlocked(line, 99, stdin); for (j = 0; line[j] != '\n'; ++j) { Ns[j] = line[j]; } for (k = 0; k < j-1; ++k) { N += Ns[k]-'0'; N *= 10; } N += Ns[k]-'0'; REP(counter, N) { l = w = 0; fgets_unlocked(line, 99, stdin); for (i = 0; line[i] != ' '; ++i) { Ws[i] = line[i]; } Ws[i+1] = 0; for (k = 0; k < i-1; ++k) { l += Ws[k]-'0'; l *= 10; } l += Ws[k]-'0'; while (line[i] == ' ') { ++i; } for (j = 0; line[i] != '\n' && line[i] != 0; ++i, ++j) { Ns[j] = line[i]; } Ns[j+1] = 0; for (k = 0; k < j-1; ++k) { w += Ns[k]-'0'; w *= 10; } w += Ns[k]-'0'; total_area += l*w; } ans = total_area/W, ansb = ans; digits[9] = '\n'; clen = 9; while (ans != 0) { digits[--clen] = (ans%10)+'0'; ans /= 10; } memcpy(&answers[tlen], &digits[clen], 10-clen); tlen += 10-clen; /* CLEAR GLOBAL VARIABLES! */ total_area = 0; W = 0; N = 0; l = 0; w = 0; /* CLEAR GLOBAL VARIABLES! */ fgets_unlocked(line, 99, stdin); } while (!feof_unlocked(stdin)); fwrite_unlocked(&answers, sizeof(char), tlen, stdout); return 0; }
Java
XCC = xmpcc XRUN = mpiexec TESTS = $(wildcard *.c) EXES = $(TESTS:.c=.x) OBJS = $(TESTS:.c=.o) .PHONY: clean all default run submit showlog cleanlog all default: $(EXES) .SUFFIXES: .x .c.x: $(XCC) -o $@ $< run: $(XRUN) -n 1 ./coarray_translation.x $(XRUN) -n 2 ./coarray_scalar.x $(XRUN) -n 2 ./coarray_vector.x $(XRUN) -n 2 ./coarray_stride.x $(XRUN) -n 2 ./coarray_scalar_mput.x $(XRUN) -n 2 ./coarray_scalar_mget.x $(XRUN) -n 2 ./coarray_scalar_mget_2.x $(XRUN) -n 2 ./coarray_put_1dim.x $(XRUN) -n 2 ./coarray_put_2dims.x $(XRUN) -n 2 ./coarray_put_3dims.x $(XRUN) -n 2 ./coarray_put_4dims.x $(XRUN) -n 2 ./coarray_get_1dim.x $(XRUN) -n 2 ./coarray_get_2dims.x $(XRUN) -n 2 ./coarray_get_3dims.x $(XRUN) -n 2 ./coarray_get_4dims.x $(XRUN) -n 1 ./coarray_local_put.x $(XRUN) -n 1 ./coarray_local_get.x RUN: mkdir RUN RUN/%.x:: %.x cp $< $@ RUN/go.sh: go.template Makefile cp $< $@ && grep XRUN Makefile | sed -e 's/(XRUN)/{XRUN}/' -e 's/ *= */=/' | grep -v Makefile >>$@ submit: all RUN RUN/go.sh $(EXES:%=RUN/%) cd RUN; pjsub go.sh showlog: cat RUN/go.sh.e* RUN/go.sh.o* cleanlog: rm -rf RUN clean: cleanlog rm -f $(EXES) $(OBJS)
Java
# -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <yukuan.jiang@gmail.com>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines
Java
/** \file millionaire_prob.cpp \author sreeram.sadasivam@cased.de \copyright ABY - A Framework for Efficient Mixed-protocol Secure Two-party Computation Copyright (C) 2019 Engineering Cryptographic Protocols Group, TU Darmstadt This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ABY 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 <http://www.gnu.org/licenses/>. \brief Implementation of the millionaire problem using ABY Framework. */ #include "millionaire_prob.h" #include "../../../abycore/circuit/booleancircuits.h" #include "../../../abycore/sharing/sharing.h" int32_t test_millionaire_prob_circuit(e_role role, const std::string& address, uint16_t port, seclvl seclvl, uint32_t bitlen, uint32_t nthreads, e_mt_gen_alg mt_alg, e_sharing sharing) { /** Step 1: Create the ABYParty object which defines the basis of all the operations which are happening. Operations performed are on the basis of the role played by this object. */ ABYParty* party = new ABYParty(role, address, port, seclvl, bitlen, nthreads, mt_alg); /** Step 2: Get to know all the sharing types available in the program. */ std::vector<Sharing*>& sharings = party->GetSharings(); /** Step 3: Create the circuit object on the basis of the sharing type being inputed. */ Circuit* circ = sharings[sharing]->GetCircuitBuildRoutine(); /** Step 4: Creating the share objects - s_alice_money, s_bob_money which is used as input to the computation function. Also s_out which stores the output. */ share *s_alice_money, *s_bob_money, *s_out; /** Step 5: Initialize Alice's and Bob's money with random values. Both parties use the same seed, to be able to verify the result. In a real example each party would only supply one input value. */ uint32_t alice_money, bob_money, output; srand(time(NULL)); alice_money = rand(); bob_money = rand(); /** Step 6: Copy the randomly generated money into the respective share objects using the circuit object method PutINGate() for my inputs and PutDummyINGate() for the other parties input. Also mention who is sharing the object. */ //s_alice_money = circ->PutINGate(alice_money, bitlen, CLIENT); //s_bob_money = circ->PutINGate(bob_money, bitlen, SERVER); if(role == SERVER) { s_alice_money = circ->PutDummyINGate(bitlen); s_bob_money = circ->PutINGate(bob_money, bitlen, SERVER); } else { //role == CLIENT s_alice_money = circ->PutINGate(alice_money, bitlen, CLIENT); s_bob_money = circ->PutDummyINGate(bitlen); } /** Step 7: Call the build method for building the circuit for the problem by passing the shared objects and circuit object. Don't forget to type cast the circuit object to type of share */ s_out = BuildMillionaireProbCircuit(s_alice_money, s_bob_money, (BooleanCircuit*) circ); /** Step 8: Modify the output receiver based on the role played by the server and the client. This step writes the output to the shared output object based on the role. */ s_out = circ->PutOUTGate(s_out, ALL); /** Step 9: Executing the circuit using the ABYParty object evaluate the problem. */ party->ExecCircuit(); /** Step 10:Type casting the value to 32 bit unsigned integer for output. */ output = s_out->get_clear_value<uint32_t>(); std::cout << "Testing Millionaire's Problem in " << get_sharing_name(sharing) << " sharing: " << std::endl; std::cout << "\nAlice Money:\t" << alice_money; std::cout << "\nBob Money:\t" << bob_money; std::cout << "\nCircuit Result:\t" << (output ? ALICE : BOB); std::cout << "\nVerify Result: \t" << ((alice_money > bob_money) ? ALICE : BOB) << "\n"; delete party; return 0; } share* BuildMillionaireProbCircuit(share *s_alice, share *s_bob, BooleanCircuit *bc) { share* out; /** Calling the greater than equal function in the Boolean circuit class.*/ out = bc->PutGTGate(s_alice, s_bob); return out; }
Java
<?php /* dvdetect DVD detection, analysis & DVDETECT lookup library Copyright (C) 2013-2015 Norbert Schlia <nschlia@dvdetect.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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 <http://www.gnu.org/licenses/>. */ /*! \file functions.search.inc.php * * \brief PHP function collection */ function addVideoStream($mysqli, $tagDVDVIDEOSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDVIDEOSTREAM->attributes(); $Type = value_or_null($attributes["Type"]); $ID = value_or_null($attributes["ID"]); $VideoCodingMode = value_or_null($attributes["VideoCodingMode"]); $VideoStandard = value_or_null($attributes["VideoStandard"]); $VideoAspect = value_or_null($attributes["VideoAspect"]); $AutomaticPanScanDisallowed = value_or_null($attributes["AutomaticPanScanDisallowed"]); $CCForLine21Field1InGOP = value_or_null($attributes["CCForLine21Field1InGOP"]); $CCForLine21Field2InGOP = value_or_null($attributes["CCForLine21Field2InGOP"]); $CBR = value_or_null($attributes["CBR"]); $Resolution = value_or_null($attributes["Resolution"]); $LetterBoxed = value_or_null($attributes["LetterBoxed"]); $SourceFilm = value_or_null($attributes["SourceFilm"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "INSERT INTO DVDVIDEOSTREAM (DVDVMGMKey, DVDVTSKey, Type, ID, VideoCodingMode, VideoStandard, VideoAspect, AutomaticPanScanDisallowed, CCForLine21Field1InGOP, CCForLine21Field2InGOP, CBR, Resolution, LetterBoxed, SourceFilm) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iisisssiiiisii", $idDVDVMGM, $idDVDVTS, $Type, $ID, $VideoCodingMode, $VideoStandard, $VideoAspect, $AutomaticPanScanDisallowed, $CCForLine21Field1InGOP, $CCForLine21Field2InGOP, $CBR, $Resolution, $LetterBoxed, $SourceFilm)) { $ResponseText = "Error binding parameters for DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function updateVideoStream($mysqli, $tagDVDVIDEOSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDVIDEOSTREAM->attributes(); $Type = value_or_null($attributes["Type"]); $ID = value_or_null($attributes["ID"]); $VideoCodingMode = value_or_null($attributes["VideoCodingMode"]); $VideoStandard = value_or_null($attributes["VideoStandard"]); $VideoAspect = value_or_null($attributes["VideoAspect"]); $AutomaticPanScanDisallowed = value_or_null($attributes["AutomaticPanScanDisallowed"]); $CCForLine21Field1InGOP = value_or_null($attributes["CCForLine21Field1InGOP"]); $CCForLine21Field2InGOP = value_or_null($attributes["CCForLine21Field2InGOP"]); $CBR = value_or_null($attributes["CBR"]); $Resolution = value_or_null($attributes["Resolution"]); $LetterBoxed = value_or_null($attributes["LetterBoxed"]); $SourceFilm = value_or_null($attributes["SourceFilm"]); if ($idDVDVMGM == null) { $Type = "VMG"; } $strSQL = "UPDATE DVDVIDEOSTREAM SET ID = ?, VideoCodingMode = ?, VideoStandard = ?, VideoAspect = ?, AutomaticPanScanDisallowed = ?, CCForLine21Field1InGOP = ?, CCForLine21Field2InGOP = ?, CBR = ?, Resolution = ?, LetterBoxed = ?, SourceFilm = ? "; if ($idDVDVMGM != null) { $strSQL .= "WHERE DVDVMGMKey = ? AND DVDVTSKey IS NULL AND Type = ?;"; } else { $strSQL .= "WHERE DVDVMGMKey IS NULL AND DVDVTSKey = ? AND Type = ?;"; } $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if ($idDVDVMGM != null) { if (!$stmt->bind_param("isssiiiisiiis", $ID, $VideoCodingMode, $VideoStandard, $VideoAspect, $AutomaticPanScanDisallowed, $CCForLine21Field1InGOP, $CCForLine21Field2InGOP, $CBR, $Resolution, $LetterBoxed, $SourceFilm, $idDVDVMGM, $Type)) { $ResponseText = "Error binding parameters for DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } else { if (!$stmt->bind_param("isssiiiisiiis", $ID, $VideoCodingMode, $VideoStandard, $VideoAspect, $AutomaticPanScanDisallowed, $CCForLine21Field1InGOP, $CCForLine21Field2InGOP, $CBR, $Resolution, $LetterBoxed, $SourceFilm, $idDVDVTS, $Type)) { $ResponseText = "Error binding parameters for DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function addAudioStream($mysqli, $tagDVDAUDIOSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDAUDIOSTREAM->attributes(); $Number = value_or_null($attributes["Number"]); $Type = value_or_null($attributes["Type"]); $ID = value_or_null($attributes["ID"]); $Channels = value_or_null($attributes["Channels"]); $SampleRate = value_or_null($attributes["SampleRate"]); $Quantisation = value_or_null($attributes["Quantisation"]); $MultichannelExtPresent = value_or_null($attributes["MultichannelExtPresent"]); $CodingMode = value_or_null($attributes["CodingMode"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "INSERT INTO DVDAUDIOSTREAM (DVDVMGMKey, DVDVTSKey, Number, Type, ID, SampleRate, Channels, Quantisation, CodingMode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiisiiiss", $idDVDVMGM, $idDVDVTS, $Number, $Type, $ID, $SampleRate, $Channels, $Quantisation, $CodingMode)) { $ResponseText = "Error binding parameters for DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function updateAudioStream($mysqli, $tagDVDAUDIOSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDAUDIOSTREAM->attributes(); $Number = value_or_null($attributes["Number"]); $Type = value_or_null($attributes["Type"]); $ID = value_or_null($attributes["ID"]); $Channels = value_or_null($attributes["Channels"]); $SampleRate = value_or_null($attributes["SampleRate"]); $Quantisation = value_or_null($attributes["Quantisation"]); $MultichannelExtPresent = value_or_null($attributes["MultichannelExtPresent"]); $CodingMode = value_or_null($attributes["CodingMode"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "UPDATE DVDAUDIOSTREAM SET ID = ?, SampleRate = ?, Channels = ?, Quantisation = ?, CodingMode = ? "; if ($idDVDVMGM != null) { $strSQL .= "WHERE DVDVMGMKey = ? AND DVDVTSKey IS NULL AND Number = ? AND Type = ?;"; } else { $strSQL .= "WHERE DVDVMGMKey IS NULL AND DVDVTSKey = ? AND Number = ? AND Type = ?;"; } $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if ($idDVDVMGM != null) { if (!$stmt->bind_param("iiissiis", $ID, $SampleRate, $Channels, $Quantisation, $CodingMode, $idDVDVMGM, $Number, $Type)) { $ResponseText = "Error binding parameters for DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } else { if (!$stmt->bind_param("iiissiis", $ID, $SampleRate, $Channels, $Quantisation, $CodingMode, $idDVDVTS, $Number, $Type)) { $ResponseText = "Error binding parameters for DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function addAudioStreamEx($mysqli, $audiostreamExTag, $idDVDVTS) { $attributes = $audiostreamExTag->attributes(); $Number = value_or_null($attributes["Number"]); $Type = value_or_null($attributes["Type"]); $SuitableForDolbySurroundDecoding = value_or_null($attributes["SuitableForDolbySurroundDecoding"]); $KaraokeVersion = value_or_null($attributes["KaraokeVersion"]); $ApplicationMode = value_or_null($attributes["ApplicationMode"]); $MCIntroPresent = value_or_null($attributes["MCIntroPresent"]); $LanguageCodePresent = value_or_null($attributes["LanguageCodePresent"]); $LanguageCode = value_or_null($attributes["LanguageCode"]); $CodeExtPresent = value_or_null($attributes["CodeExtPresent"]); $CodeExt = value_or_null($attributes["CodeExt"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "INSERT INTO DVDAUDIOSTREAMEX (DVDVTSKey, Number, SuitableForDolbySurroundDecoding, KaraokeVersion, ApplicationMode, MCIntroPresent, LanguageCodePresent, LanguageCode, CodeExtPresent, CodeExt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiiisiisii", $idDVDVTS, $Number, $SuitableForDolbySurroundDecoding, $KaraokeVersion, $ApplicationMode, $MCIntroPresent, $LanguageCodePresent, $LanguageCode, $CodeExtPresent, $CodeExt)) { $ResponseText = "Error binding parameters for DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function updateAudioStreamEx($mysqli, $audiostreamExTag, $idDVDVTS) { $attributes = $audiostreamExTag->attributes(); $Number = value_or_null($attributes["Number"]); $SuitableForDolbySurroundDecoding = value_or_null($attributes["SuitableForDolbySurroundDecoding"]); $KaraokeVersion = value_or_null($attributes["KaraokeVersion"]); $ApplicationMode = value_or_null($attributes["ApplicationMode"]); $MCIntroPresent = value_or_null($attributes["MCIntroPresent"]); $LanguageCodePresent = value_or_null($attributes["LanguageCodePresent"]); $LanguageCode = value_or_null($attributes["LanguageCode"]); $CodeExtPresent = value_or_null($attributes["CodeExtPresent"]); $CodeExt = value_or_null($attributes["CodeExt"]); $strSQL = "UPDATE DVDAUDIOSTREAMEX SET SuitableForDolbySurroundDecoding = ?, KaraokeVersion = ?, ApplicationMode = ?, MCIntroPresent = ?, LanguageCodePresent = ?, LanguageCode = ?, CodeExtPresent = ?, CodeExt = ? WHERE DVDVTSKey = ? AND Number = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("isiisiiiii", $SuitableForDolbySurroundDecoding, $KaraokeVersion, $ApplicationMode, $MCIntroPresent, $LanguageCodePresent, $LanguageCode, $CodeExtPresent, $CodeExt, $idDVDVTS, $Number)) { $ResponseText = "Error binding parameters for DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function addSubPictureStream($mysqli, $tagDVDSUBPICSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDSUBPICSTREAM->attributes(); $Number = value_or_null($attributes["Number"]); $ID = value_or_null($attributes["ID"]); $Type = value_or_null($attributes["Type"]); $CodingMode = value_or_null($attributes["CodingMode"]); $LanguageCodePresent = value_or_null($attributes["LanguageCodePresent"]); $LanguageCode = value_or_null($attributes["LanguageCode"]); $CodeExtPresent = value_or_null($attributes["CodeExtPresent"]); $CodeExt = value_or_null($attributes["CodeExt"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "INSERT INTO DVDSUBPICSTREAM (DVDVMGMKey, DVDVTSKey, Number, ID, Type, CodingMode, LanguageCodePresent, LanguageCode, CodeExtPresent, CodeExt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiissiisii", $idDVDVMGM, $idDVDVTS, $Number, $ID, $Type, $CodingMode, $LanguageCodePresent, $LanguageCode, $CodeExtPresent, $CodeExt)) { $ResponseText = "Error binding parameters for DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function updateSubPictureStream($mysqli, $tagDVDSUBPICSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDSUBPICSTREAM->attributes(); $Number = value_or_null($attributes["Number"]); $ID = value_or_null($attributes["ID"]); $Type = value_or_null($attributes["Type"]); $CodingMode = value_or_null($attributes["CodingMode"]); $LanguageCodePresent = value_or_null($attributes["LanguageCodePresent"]); $LanguageCode = value_or_null($attributes["LanguageCode"]); $CodeExtPresent = value_or_null($attributes["CodeExtPresent"]); $CodeExt = value_or_null($attributes["CodeExt"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "UPDATE DVDSUBPICSTREAM SET ID = ?, CodingMode = ?, LanguageCodePresent = ?, LanguageCode = ?, CodeExtPresent = ?, CodeExt = ? "; if ($idDVDVMGM != null) { $strSQL .= "WHERE DVDVMGMKey = ? AND DVDVTSKey IS NULL AND Number = ? AND Type = ?;"; } else { $strSQL .= "WHERE DVDVMGMKey IS NULL AND DVDVTSKey = ? AND Number = ? AND Type = ?;"; } $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if ($idDVDVMGM != null) { if (!$stmt->bind_param("siisiiiis", $ID, $CodingMode, $LanguageCodePresent, $LanguageCode, $CodeExtPresent, $CodeExt, $idDVDVMGM, $Number, $Type)) { $ResponseText = "Error binding parameters for DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } else { if (!$stmt->bind_param("siisiiiis", $ID, $CodingMode, $LanguageCodePresent, $LanguageCode, $CodeExtPresent, $CodeExt, $idDVDVTS, $Number, $Type)) { $ResponseText = "Error binding parameters for DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function addFileset($mysqli, $tagDVDFILE, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDFILE->attributes(); $FileSetNo = value_or_null($attributes["Number"]); $Type = value_or_null($attributes["Type"]); $VobNo = value_or_null($attributes["VobNo"]); $Size = value_or_null($attributes["Size"]); $Date = value_or_null($attributes["Date"]); $strSQL = "INSERT INTO DVDFILE (DVDVMGMKey, DVDVTSKey, FileSetNo, Type, VobNo, Size, Date) VALUES (?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiisiis", $idDVDVMGM, $idDVDVTS, $FileSetNo, $Type, $VobNo, $Size, $Date)) { $ResponseText = "Error binding parameters for DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function updateFileset($mysqli, $tagDVDFILE, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDFILE->attributes(); $FileSetNo = value_or_null($attributes["Number"]); $Type = value_or_null($attributes["Type"]); $VobNo = value_or_null($attributes["VobNo"]); $Size = value_or_null($attributes["Size"]); $Date = value_or_null($attributes["Date"]); $strSQL = "UPDATE `DVDFILE` SET `Type` = ?, `VobNo` = ?, `Size` = ?, `Date` = ? "; if ($idDVDVMGM != null) { $strSQL .= "WHERE DVDVMGMKey = ? AND DVDVTSKey IS NULL AND FileSetNo = ?;"; } else { $strSQL .= "WHERE DVDVMGMKey IS NULL AND DVDVTSKey = ? AND FileSetNo = ?;"; } $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if ($idDVDVMGM != null) { if (!$stmt->bind_param("siisii", $Type, $VobNo, $Size, $Date, $idDVDVMGM, $FileSetNo)) { $ResponseText = "Error binding parameters for DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } else { if (!$stmt->bind_param("siisii", $Type, $VobNo, $Size, $Date, $idDVDVTS, $FileSetNo)) { $ResponseText = "Error binding parameters for DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function submit($mysqli, $xml, $XmlVersion) { /* query_server($mysqli, "TRUNCATE TABLE `DVDAUDIOSTREAM`;"); query_server($mysqli, "TRUNCATE TABLE `DVDAUDIOSTREAMEX`;"); query_server($mysqli, "TRUNCATE TABLE `DVDSUBPICSTREAM`;"); query_server($mysqli, "TRUNCATE TABLE `DVDVIDEOSTREAM`;"); query_server($mysqli, "TRUNCATE TABLE `DVDFILE`;"); query_server($mysqli, "TRUNCATE TABLE `DVDPTTVMG`;"); query_server($mysqli, "TRUNCATE TABLE `DVDPTTVTS`;"); query_server($mysqli, "TRUNCATE TABLE `DVDUNIT`;"); query_server($mysqli, "TRUNCATE TABLE `DVDCELL`;"); query_server($mysqli, "TRUNCATE TABLE `DVDPROGRAM`;"); query_server($mysqli, "TRUNCATE TABLE `DVDPGC`;"); query_server($mysqli, "TRUNCATE TABLE `DVDVTS`;"); query_server($mysqli, "TRUNCATE TABLE `DVDVMGM`;"); */ // Start a transaction query_server($mysqli, "START TRANSACTION;"); foreach ($xml->DVD as $tagDVDVMGM) { $attributes = $tagDVDVMGM->attributes(); $Hash = value_or_null($attributes["Hash"]); $SubmitterIP = value_or_null($_SERVER['REMOTE_ADDR']); $Album = value_or_null($tagDVDVMGM->Album); $OriginalAlbum = value_or_null($tagDVDVMGM->OriginalAlbum); $AlbumArtist = value_or_null($tagDVDVMGM->AlbumArtist); $Genre = value_or_null($tagDVDVMGM->Genre); $Cast = value_or_null($tagDVDVMGM->Cast); $Crew = value_or_null($tagDVDVMGM->Crew); $Director = value_or_null($tagDVDVMGM->Director); $Screenplay = value_or_null($tagDVDVMGM->Screenplay); $Producer = value_or_null($tagDVDVMGM->Producer); $Editing = value_or_null($tagDVDVMGM->Editing); $Cinematography = value_or_null($tagDVDVMGM->Cinematography); $Country = value_or_null($tagDVDVMGM->Country); $OriginalLanguage = value_or_null($tagDVDVMGM->OriginalLanguage); $ReleaseDate = date_or_null($tagDVDVMGM->ReleaseDate); $SpecialFeatures = value_or_null($tagDVDVMGM->SpecialFeatures); $EAN_UPC = value_or_null($tagDVDVMGM->EAN_UPC); $Storyline = value_or_null($tagDVDVMGM->Storyline); $Submitter = value_or_null($tagDVDVMGM->Submitter); $Client = value_or_null($tagDVDVMGM->Client); $Remarks = value_or_null($tagDVDVMGM->Remarks); $Keywords = value_or_null($tagDVDVMGM->Keywords); $RegionProhibited1 = value_or_null($attributes["RegionProhibited1"]); $RegionProhibited2 = value_or_null($attributes["RegionProhibited2"]); $RegionProhibited3 = value_or_null($attributes["RegionProhibited3"]); $RegionProhibited4 = value_or_null($attributes["RegionProhibited4"]); $RegionProhibited5 = value_or_null($attributes["RegionProhibited5"]); $RegionProhibited6 = value_or_null($attributes["RegionProhibited6"]); $RegionProhibited7 = value_or_null($attributes["RegionProhibited7"]); $RegionProhibited8 = value_or_null($attributes["RegionProhibited8"]); $VersionNumberMajor = value_or_null($attributes["VersionNumberMajor"]); $VersionNumberMinor = value_or_null($attributes["VersionNumberMinor"]); $NumberOfVolumes = value_or_null($attributes["NumberOfVolumes"]); $VolumeNumber = value_or_null($attributes["VolumeNumber"]); $SideID = value_or_null($attributes["SideID"]); if ($Submitter == DEFSUBMITTER) { $Submitter = null; } // Check if dataset exists $found = FALSE; /* Feature #884: deactivated unstable feature for rev 0.40 $strSQL = "SELECT `idDVDVMGM`, `RowLastChanged`, `RowCreationDate`, `Submitter`, `SubmitterIP` FROM `DVDVMGM` ". "WHERE `Hash` = '" . $Hash . "' AND `Active` = 1 " . "ORDER BY `Revision` DESC;"; $rsDVDVMGM = query_server($mysqli, $strSQL); if (is_array($Cols = $rsDVDVMGM->fetch_row())) { $idDVDVMGM = $Cols[0]; $RowLastChanged = $Cols[1]; $RowCreationDate = $Cols[2]; $LastSubmitter = $Cols[3]; $LastSubmitterIP = $Cols[4]; // TODO: maybe check submission time if ($Submitter == $LastSubmitter && $SubmitterIP == $LastSubmitterIP) { $found = TRUE; } } $rsDVDVMGM->close(); */ if (!$found) { // Not found: insert new $strSQL = "INSERT INTO `DVDVMGM` (`Hash`, `Album`, `AlbumArtist`, `Genre`, `Cast`, `Crew`, `Director`, `Country`, `ReleaseDate`, `SpecialFeatures`, `EAN_UPC`, `Storyline`, `Remarks`, `Submitter`, `SubmitterIP`, `Client`, `Keywords`, `RegionProhibited1`, `RegionProhibited2`, `RegionProhibited3`, `RegionProhibited4`, `RegionProhibited5`, `RegionProhibited6`, `RegionProhibited7`, `RegionProhibited8`, `VersionNumberMajor`, `VersionNumberMinor`, `NumberOfVolumes`, `VolumeNumber`, `SideID`, `OriginalAlbum`, `Screenplay`, `Producer`, `Editing`, `Cinematography`, `OriginalLanguage`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("sssssssssssssssssiiiiiiiiiiiiissssss", $Hash, $Album, $AlbumArtist, $Genre, $Cast, $Crew, $Director, $Country, $ReleaseDate, $SpecialFeatures, $EAN_UPC, $Storyline, $Remarks, $Submitter, $SubmitterIP, $Client, $Keywords, $RegionProhibited1, $RegionProhibited2, $RegionProhibited3, $RegionProhibited4, $RegionProhibited5, $RegionProhibited6, $RegionProhibited7, $RegionProhibited8, $VersionNumberMajor, $VersionNumberMinor, $NumberOfVolumes, $VolumeNumber, $SideID, $OriginalAlbum, $Screenplay, $Producer, $Editing, $Cinematography, $OriginalLanguage)) { $ResponseText = "Error binding parameters for DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); $stmt = null; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); $stmt = null; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDVMGM = $mysqli->insert_id; $stmt->close(); $stmt = null; // Physical structure $tagPhysical = $tagDVDVMGM->physical; foreach ($tagPhysical->DVDVTS as $tagDVDVTS) { // Insert DVDVTS (Video Title Set) $attributes = $tagDVDVTS->attributes(); $TitleSetNo = $attributes["TitleSetNo"]; $VersionNumberMajor = value_or_null($attributes["VersionNumberMajor"]); $VersionNumberMinor = value_or_null($attributes["VersionNumberMinor"]); $strSQL = "INSERT INTO `DVDVTS` (`DVDVMGMKey`, `TitleSetNo`, `VersionNumberMajor`, `VersionNumberMinor`) VALUES (?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiii", $idDVDVMGM, $TitleSetNo, $VersionNumberMajor, $VersionNumberMinor)) { $ResponseText = "Error binding parameters for DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDVTS = $mysqli->insert_id; $stmt->close(); foreach ($tagDVDVTS->DVDPGC as $tagDVDPGC) { // Insert DVDPGC (Program Chain) $attributes = $tagDVDPGC->attributes(); $ProgramChainNo = value_or_null($attributes["Number"]); $EntryPGC = value_or_null($attributes["EntryPGC"]); $strSQL = "INSERT INTO `DVDPGC` (`DVDVTSKey`, `ProgramChainNo`, `EntryPGC`) VALUES (?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iii", $idDVDVTS, $ProgramChainNo, $EntryPGC)) { $ResponseText = "Error binding parameters for DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDPGC = $mysqli->insert_id; $stmt->close(); foreach ($tagDVDPGC->DVDPROGRAM as $tagDVDPROGRAM) { // Insert DVDPGC (Program) $attributes = $tagDVDPROGRAM->attributes(); $ProgramNo = value_or_null($attributes["Number"]); $strSQL = "INSERT INTO `DVDPROGRAM` (`DVDPGCKey`, `ProgramNo`) VALUES (?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for chapter table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("ii", $idDVDPGC, $ProgramNo)) { $ResponseText = "Error binding parameters for chapter table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on chapter table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDPROGRAM = $mysqli->insert_id; $stmt->close(); foreach ($tagDVDPROGRAM->DVDCELL as $tagDVDCELL) { // Insert DVDCELL (Cell) $attributes = $tagDVDCELL->attributes(); $CellNo = value_or_null($attributes["Number"]); $CellType = value_or_null($attributes["CellType"]); $BlockType = value_or_null($attributes["BlockType"]); $SeamlessMultiplex = value_or_null($attributes["SeamlessMultiplex"]); $Interleaved = value_or_null($attributes["Interleaved"]); $SCRdiscontinuity = value_or_null($attributes["SCRdiscontinuity"]); $SeamlessAngleLinkedInDSI = value_or_null($attributes["SeamlessAngleLinkedInDSI"]); $VOBStillMode = value_or_null($attributes["VOBStillMode"]); $StopsTrickPlay = value_or_null($attributes["StopsTrickPlay"]); $CellStillTime = value_or_null($attributes["CellStillTime"]); $CellCommand = value_or_null($attributes["CellCommand"]); $PlayTime = value_or_null($attributes["PlayTime"]); $FrameRate = value_or_null($attributes["FrameRate"]); $FirstVOBUStartSector = value_or_null($attributes["FirstVOBUStartSector"]); $FirstILVUEndSector = value_or_null($attributes["FirstILVUEndSector"]); $LastVOBUStartSector = value_or_null($attributes["LastVOBUStartSector"]); $LastVOBUEndSector = value_or_null($attributes["LastVOBUEndSector"]); $VOBidn = value_or_null($attributes["VOBidn"]); $CELLidn = value_or_null($attributes["CELLidn"]); $NumberOfVOBIds = value_or_null($attributes["NumberOfVOBIds"]); $strSQL = "INSERT INTO `DVDCELL` (`DVDPROGRAMKey`, `CellNo`, `CellType`, `BlockType`, `SeamlessMultiplex`, `Interleaved`, `SCRdiscontinuity`, `SeamlessAngleLinkedInDSI`, `VOBStillMode`, `StopsTrickPlay`, `CellStillTime`, `CellCommand`, `PlayTime`, `FrameRate`, `FirstVOBUStartSector`, `FirstILVUEndSector`, `LastVOBUStartSector`, `LastVOBUEndSector`, `VOBidn`, `CELLidn`, `NumberOfVOBIds`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iissiiiiiiiiiiiiiiiii", $idDVDPROGRAM, $CellNo, $CellType, $BlockType, $SeamlessMultiplex, $Interleaved, $SCRdiscontinuity, $SeamlessAngleLinkedInDSI, $VOBStillMode, $StopsTrickPlay, $CellStillTime, $CellCommand, $PlayTime, $FrameRate, $FirstVOBUStartSector, $FirstILVUEndSector, $LastVOBUStartSector, $LastVOBUEndSector, $VOBidn, $CELLidn, $NumberOfVOBIds)) { $ResponseText = "Error binding parameters for DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDCELL = $mysqli->insert_id; $stmt->close(); foreach ($tagDVDCELL->DVDUNIT as $tagDVDUNIT) { // Insert DVDUNIT (Unit) $attributes = $tagDVDUNIT->attributes(); $UnitNo = value_or_null($attributes["Number"]); $StartSector = value_or_null($attributes["StartSector"]); $EndSector = value_or_null($attributes["EndSector"]); $strSQL = "INSERT INTO `DVDUNIT` (`DVDCELLKey`, `UnitNo`, `StartSector`, `EndSector`) VALUES (?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiii", $idDVDCELL, $UnitNo, $StartSector, $EndSector)) { $ResponseText = "Error binding parameters for DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } //$idDVDUNIT = $mysqli->insert_id; $stmt->close(); } } } } // DVDVIDEOSTREAM foreach ($tagDVDVTS->DVDVIDEOSTREAM as $tagDVDVIDEOSTREAM) { addVideoStream($mysqli, $tagDVDVIDEOSTREAM, null, $idDVDVTS); } // DVDAUDIOSTREAM foreach ($tagDVDVTS->DVDAUDIOSTREAM as $tagDVDAUDIOSTREAM) { addAudioStream($mysqli, $tagDVDAUDIOSTREAM, null, $idDVDVTS); } // DVDAUDIOSTREAMEX foreach ($tagDVDVTS->DVDAUDIOSTREAMEX as $audiostreamExTag) { addAudioStreamEx($mysqli, $audiostreamExTag, $idDVDVTS); } // DVDSUBPICSTREAM foreach ($tagDVDVTS->DVDSUBPICSTREAM as $tagDVDSUBPICSTREAM) { addSubpictureStream($mysqli, $tagDVDSUBPICSTREAM, null, $idDVDVTS); } // Fileset foreach ($tagDVDVTS->DVDFILE as $tagDVDFILE) { addFileset($mysqli, $tagDVDFILE, null, $idDVDVTS); } } // Virtual structure $tagVirtual = $tagDVDVMGM->virtual; foreach ($tagVirtual->DVDPTTVMG as $tagDVDPTTVMG) { // Insert DVDPTTVMG (Video Title Set) $attributes = $tagDVDPTTVMG->attributes(); $Title = value_or_null($tagDVDPTTVMG->Title); $TitleSetNo = value_or_null($attributes["TitleSetNo"]); $PlaybackType = value_or_null($attributes["PlaybackType"]); $NumberOfVideoAngles = value_or_null($attributes["NumberOfVideoAngles"]); $ParentalMgmMaskVMG = value_or_null($attributes["ParentalMgmMaskVMG"]); $ParentalMgmMaskVTS = value_or_null($attributes["ParentalMgmMaskVTS"]); $NumberOfVideoAngles = value_or_null($attributes["NumberOfVideoAngles"]); $VideoTitleSetNo = value_or_null($attributes["VideoTitleSetNo"]); $TitleNo = value_or_null($attributes["TitleNo"]); $strSQL = "INSERT INTO `DVDPTTVMG` (`DVDVMGMKey`, `TitleSetNo`, `Title`, `PlaybackType`, `NumberOfVideoAngles`, `ParentalMgmMaskVMG`, `ParentalMgmMaskVTS`, `VideoTitleSetNo`, `TitleNo`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iisiiiiii", $idDVDVMGM, $TitleSetNo, $Title, $PlaybackType, $NumberOfVideoAngles, $ParentalMgmMaskVMG, $ParentalMgmMaskVTS, $VideoTitleSetNo, $TitleNo)) { $ResponseText = "Error binding parameters for DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDPTTVMG = $mysqli->insert_id; $stmt->close(); foreach ($tagDVDPTTVMG->DVDPTTVTS as $tagDVDPTTVTS) { // Insert DVDPTTVTS (Chapter) $attributes = $tagDVDPTTVTS->attributes(); $Title = value_or_null($tagDVDPTTVTS->Title); $Artist = value_or_null($tagDVDPTTVTS->Artist); $ProgramChainNo = value_or_null($attributes["ProgramChainNo"]); $ProgramNo = value_or_null($attributes["ProgramNo"]); $PttTitleSetNo = value_or_null($attributes["PttTitleSetNo"]); $PttChapterNo = value_or_null($attributes["Number"]); $TitleSetNo = value_or_null($attributes["TitleSetNo"]); $strSQL = "INSERT INTO `DVDPTTVTS` (`DVDPTTVMGKey`, `Artist`, `Title`, `ProgramChainNo`, `ProgramNo`, `PttTitleSetNo`, `PttChapterNo`, `TitleSetNo`) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("issiiiii", $idDVDPTTVMG, $Artist, $Title, $ProgramChainNo, $ProgramNo, $PttTitleSetNo, $PttChapterNo, $TitleSetNo)) { $ResponseText = "Error binding parameters for DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } //$idDVDPTTVTS = $mysqli->insert_id; $stmt->close(); } } // DVDVIDEOSTREAM foreach ($tagDVDVMGM->DVDVIDEOSTREAM as $tagDVDVIDEOSTREAM) { addVideoStream($mysqli, $tagDVDVIDEOSTREAM, $idDVDVMGM, null); } // DVDAUDIOSTREAM foreach ($tagDVDVMGM->DVDAUDIOSTREAM as $tagDVDAUDIOSTREAM) { addAudioStream($mysqli, $tagDVDAUDIOSTREAM, $idDVDVMGM, null); } // DVDSUBPICSTREAM foreach ($tagDVDVMGM->DVDSUBPICSTREAM as $tagDVDSUBPICSTREAM) { addSubpictureStream($mysqli, $tagDVDSUBPICSTREAM, $idDVDVMGM, null); } // Fileset foreach ($tagDVDVMGM->DVDFILE as $tagDVDFILE) { addFileset($mysqli, $tagDVDFILE, $idDVDVMGM, null); } } else { // Found: do an update $strSQL = "UPDATE `DVDVMGM` SET `Album` = ?, `AlbumArtist` = ?, `Genre` = ?, `Cast` = ?, `Crew` = ?, `Director` = ?, `Country` = ?, `ReleaseDate` = ?, `SpecialFeatures` = ?, `EAN_UPC` = ?, `Storyline` = ?, `Remarks` = ?, `Submitter` = ?, `SubmitterIP` = ?, `Client` = ?, `Keywords` = ?, `RegionProhibited1` = ?, `RegionProhibited2` = ?, `RegionProhibited3` = ?, `RegionProhibited4` = ?, `RegionProhibited5` = ?, `RegionProhibited6` = ?, `RegionProhibited7` = ?, `RegionProhibited8` = ?, `VersionNumberMajor` = ?, `VersionNumberMinor` = ?, `NumberOfVolumes` = ?, `VolumeNumber` = ?, `OriginalAlbum` = ?, `Screenplay` = ?, `Producer` = ?, `Editing` = ?, `Cinematography` = ?, `OriginalLanguage` = ?, `SideID` = ? WHERE `idDVDVMGM` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("ssssssssssssssssiiiiiiiiiiiissssssii", $Album, $AlbumArtist, $Genre, $Cast, $Crew, $Director, $Country, $ReleaseDate, $SpecialFeatures, $EAN_UPC, $Storyline, $Remarks, $Submitter, $SubmitterIP, $Client, $Keywords, $RegionProhibited1, $RegionProhibited2, $RegionProhibited3, $RegionProhibited4, $RegionProhibited5, $RegionProhibited6, $RegionProhibited7, $RegionProhibited8, $VersionNumberMajor, $VersionNumberMinor, $NumberOfVolumes, $VolumeNumber, $OriginalAlbum, $Screenplay, $Producer, $Editing, $Cinematography, $OriginalLanguage, $SideID, $idDVDVMGM)) { $ResponseText = "Error binding parameters for DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); $stmt = null; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); $stmt = null; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); $stmt = null; // Physical structure $tagPhysical = $tagDVDVMGM->physical; foreach ($tagPhysical->DVDVTS as $tagDVDVTS) { // Update DVDVTS (Video Title Set) $attributes = $tagDVDVTS->attributes(); $TitleSetNo = $attributes["TitleSetNo"]; $VersionNumberMajor = value_or_null($attributes["VersionNumberMajor"]); $VersionNumberMinor = value_or_null($attributes["VersionNumberMinor"]); $idDVDVTS = getPrimaryKey($mysqli, "DVDVTS", "idDVDVTS", "`DVDVMGMKey` = $idDVDVMGM AND `TitleSetNo` = $TitleSetNo"); $strSQL = "UPDATE `DVDVTS` SET `TitleSetNo` = ?, `VersionNumberMajor` = ?, `VersionNumberMinor` = ? WHERE `idDVDVTS` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiii", $TitleSetNo, $VersionNumberMajor, $VersionNumberMinor, $idDVDVTS)) { $ResponseText = "Error binding parameters for DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); foreach ($tagDVDVTS->DVDPGC as $tagDVDPGC) { // Update DVDPGC (Program Chain) $attributes = $tagDVDPGC->attributes(); $ProgramChainNo = value_or_null($attributes["Number"]); $EntryPGC = value_or_null($attributes["EntryPGC"]); $idDVDPGC = getPrimaryKey($mysqli, "DVDPGC", "idDVDPGC", "`DVDVTSKey` = $idDVDVTS AND `ProgramChainNo` = $ProgramChainNo"); $strSQL = "UPDATE `DVDPGC` SET `EntryPGC` = ? WHERE `idDVDPGC` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("ii", $EntryPGC, $idDVDPGC)) { $ResponseText = "Error binding parameters for DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); foreach ($tagDVDPGC->DVDPROGRAM as $tagDVDPROGRAM) { // Update DVDPGC (Program) $attributes = $tagDVDPROGRAM->attributes(); $ProgramNo = value_or_null($attributes["Number"]); // Nothing to update... $idDVDPROGRAM = getPrimaryKey($mysqli, "DVDPROGRAM", "idDVDPROGRAM", "`DVDPGCKey` = $idDVDPGC AND `ProgramNo` = $ProgramNo"); foreach ($tagDVDPROGRAM->DVDCELL as $tagDVDCELL) { // Update DVDCELL (Cell) $attributes = $tagDVDCELL->attributes(); $CellNo = value_or_null($attributes["Number"]); $CellType = value_or_null($attributes["CellType"]); $BlockType = value_or_null($attributes["BlockType"]); $SeamlessMultiplex = value_or_null($attributes["SeamlessMultiplex"]); $Interleaved = value_or_null($attributes["Interleaved"]); $SCRdiscontinuity = value_or_null($attributes["SCRdiscontinuity"]); $SeamlessAngleLinkedInDSI = value_or_null($attributes["SeamlessAngleLinkedInDSI"]); $VOBStillMode = value_or_null($attributes["VOBStillMode"]); $StopsTrickPlay = value_or_null($attributes["StopsTrickPlay"]); $CellStillTime = value_or_null($attributes["CellStillTime"]); $CellCommand = value_or_null($attributes["CellCommand"]); $PlayTime = value_or_null($attributes["PlayTime"]); $FrameRate = value_or_null($attributes["FrameRate"]); $FirstVOBUStartSector = value_or_null($attributes["FirstVOBUStartSector"]); $FirstILVUEndSector = value_or_null($attributes["FirstILVUEndSector"]); $LastVOBUStartSector = value_or_null($attributes["LastVOBUStartSector"]); $LastVOBUEndSector = value_or_null($attributes["LastVOBUEndSector"]); $VOBidn = value_or_null($attributes["VOBidn"]); $CELLidn = value_or_null($attributes["CELLidn"]); $NumberOfVOBIds = value_or_null($attributes["NumberOfVOBIds"]); $idDVDCELL = getPrimaryKey($mysqli, "DVDCELL", "idDVDCELL", "`DVDPROGRAMKey` = $idDVDPROGRAM AND `CellNo` = $CellNo"); $strSQL = "UPDATE `DVDCELL` SET `CellType` = ?, `BlockType` = ?, `SeamlessMultiplex` = ?, `Interleaved` = ?, `SCRdiscontinuity` = ?, `SeamlessAngleLinkedInDSI` = ?, `VOBStillMode` = ?, `StopsTrickPlay` = ?, `CellStillTime` = ?, `CellCommand` = ?, `PlayTime` = ?, `FrameRate` = ?, `FirstVOBUStartSector` = ?, `FirstILVUEndSector` = ?, `LastVOBUStartSector` = ?, `LastVOBUEndSector` = ?, `VOBidn` = ?, `CELLidn` = ?, `NumberOfVOBIds` = ? WHERE `idDVDCELL` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("ssiiiiiiiiiiiiiiiiii", $CellType, $BlockType, $SeamlessMultiplex, $Interleaved, $SCRdiscontinuity, $SeamlessAngleLinkedInDSI, $VOBStillMode, $StopsTrickPlay, $CellStillTime, $CellCommand, $PlayTime, $FrameRate, $FirstVOBUStartSector, $FirstILVUEndSector, $LastVOBUStartSector, $LastVOBUEndSector, $VOBidn, $CELLidn, $NumberOfVOBIds, $idDVDCELL)) { $ResponseText = "Error binding parameters for DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); foreach ($tagDVDCELL->DVDUNIT as $tagDVDUNIT) { // Update DVDUNIT (Unit) $attributes = $tagDVDUNIT->attributes(); $UnitNo = value_or_null($attributes["Number"]); $StartSector = value_or_null($attributes["StartSector"]); $EndSector = value_or_null($attributes["EndSector"]); $strSQL = "UPDATE `DVDUNIT` SET `StartSector` = ?, `EndSector` = ? WHERE `DVDCELLKey` = ? AND `UnitNo` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiii", $StartSector, $EndSector, $idDVDCELL, $UnitNo)) { $ResponseText = "Error binding parameters for DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } //$idDVDUNIT = $mysqli->insert_id; $stmt->close(); } } } } // DVDVIDEOSTREAM foreach ($tagDVDVTS->DVDVIDEOSTREAM as $tagDVDVIDEOSTREAM) { updateVideoStream($mysqli, $tagDVDVIDEOSTREAM, null, $idDVDVTS); } // DVDAUDIOSTREAM foreach ($tagDVDVTS->DVDAUDIOSTREAM as $tagDVDAUDIOSTREAM) { updateAudioStream($mysqli, $tagDVDAUDIOSTREAM, null, $idDVDVTS); } // DVDAUDIOSTREAMEX foreach ($tagDVDVTS->DVDAUDIOSTREAMEX as $audiostreamExTag) { updateAudioStreamEx($mysqli, $audiostreamExTag, $idDVDVTS); } // DVDSUBPICSTREAM foreach ($tagDVDVTS->DVDSUBPICSTREAM as $tagDVDSUBPICSTREAM) { updateSubpictureStream($mysqli, $tagDVDSUBPICSTREAM, null, $idDVDVTS); } // Fileset foreach ($tagDVDVTS->DVDFILE as $tagDVDFILE) { updateFileset($mysqli, $tagDVDFILE, null, $idDVDVTS); } } // Virtual structure $tagVirtual = $tagDVDVMGM->virtual; foreach ($tagVirtual->DVDPTTVMG as $tagDVDPTTVMG) { // Update DVDPTTVMG (Video Title Set) $attributes = $tagDVDPTTVMG->attributes(); $Title = value_or_null($tagDVDPTTVMG->Title); $TitleSetNo = value_or_null($attributes["TitleSetNo"]); $PlaybackType = value_or_null($attributes["PlaybackType"]); $NumberOfVideoAngles = value_or_null($attributes["NumberOfVideoAngles"]); $ParentalMgmMaskVMG = value_or_null($attributes["ParentalMgmMaskVMG"]); $ParentalMgmMaskVTS = value_or_null($attributes["ParentalMgmMaskVTS"]); $NumberOfVideoAngles = value_or_null($attributes["NumberOfVideoAngles"]); $VideoTitleSetNo = value_or_null($attributes["VideoTitleSetNo"]); $TitleNo = value_or_null($attributes["TitleNo"]); $idDVDPTTVMG = getPrimaryKey($mysqli, "DVDPTTVMG", "idDVDPTTVMG", "`DVDVMGMKey` = $idDVDVMGM AND `TitleSetNo` = $TitleSetNo"); $strSQL = "UPDATE `DVDPTTVMG` SET `Title` = ?, `PlaybackType` = ?, `NumberOfVideoAngles` = ?, `ParentalMgmMaskVMG` = ?, `ParentalMgmMaskVTS` = ?, `VideoTitleSetNo` = ?, `TitleNo` = ? WHERE `idDVDPTTVMG` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("siiiiiii", $Title, $PlaybackType, $NumberOfVideoAngles, $ParentalMgmMaskVMG, $ParentalMgmMaskVTS, $VideoTitleSetNo, $TitleNo, $idDVDPTTVMG)) { $ResponseText = "Error binding parameters for DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); foreach ($tagDVDPTTVMG->DVDPTTVTS as $tagDVDPTTVTS) { // Update DVDPTTVTS (Chapter) $attributes = $tagDVDPTTVTS->attributes(); $Title = value_or_null($tagDVDPTTVTS->Title); $Artist = value_or_null($tagDVDPTTVTS->Artist); $ProgramChainNo = value_or_null($attributes["ProgramChainNo"]); $ProgramNo = value_or_null($attributes["ProgramNo"]); $PttTitleSetNo = value_or_null($attributes["PttTitleSetNo"]); $PttChapterNo = value_or_null($attributes["Number"]); $TitleSetNo = value_or_null($attributes["TitleSetNo"]); $strSQL = "UPDATE `DVDPTTVTS` SET `Artist` = ?, `Title` = ?, `ProgramChainNo` = ?, `ProgramNo` = ?, `PttTitleSetNo` = ?, TitleSetNo = ? WHERE `DVDPTTVMGKey` = ? AND `PttChapterNo` = ? ;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("ssiiiiii", $Artist, $Title, $ProgramChainNo, $ProgramNo, $PttTitleSetNo, $TitleSetNo, $idDVDPTTVMG, $PttChapterNo)) { $ResponseText = "Error binding parameters for DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } //$idDVDPTTVTS = $mysqli->insert_id; $stmt->close(); } } // DVDVIDEOSTREAM foreach ($tagDVDVMGM->DVDVIDEOSTREAM as $tagDVDVIDEOSTREAM) { updateVideoStream($mysqli, $tagDVDVIDEOSTREAM, $idDVDVMGM, null); } // DVDAUDIOSTREAM foreach ($tagDVDVMGM->DVDAUDIOSTREAM as $tagDVDAUDIOSTREAM) { updateAudioStream($mysqli, $tagDVDAUDIOSTREAM, $idDVDVMGM, null); } // DVDSUBPICSTREAM foreach ($tagDVDVMGM->DVDSUBPICSTREAM as $tagDVDSUBPICSTREAM) { updateSubpictureStream($mysqli, $tagDVDSUBPICSTREAM, $idDVDVMGM, null); } // Fileset foreach ($tagDVDVMGM->DVDFILE as $tagDVDFILE) { updateFileset($mysqli, $tagDVDFILE, $idDVDVMGM, null); } } } // Commit the transaction $rs = query_server($mysqli, "COMMIT;"); } ?>
Java
/*********************************************************************** Copyright (c) 2006-2011, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, (subject to the limitations in the disclaimer below) 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. - Neither the name of Skype Limited, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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 OWNER 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. ***********************************************************************/ #include "SKP_Silk_main_FLP.h" #include "SKP_Silk_tuning_parameters.h" /* Compute gain to make warped filter coefficients have a zero mean log frequency response on a */ /* non-warped frequency scale. (So that it can be implemented with a minimum-phase monic filter.) */ SKP_INLINE SKP_float warped_gain( const SKP_float *coefs, SKP_float lambda, SKP_int order ) { SKP_int i; SKP_float gain; lambda = -lambda; gain = coefs[ order - 1 ]; for( i = order - 2; i >= 0; i-- ) { gain = lambda * gain + coefs[ i ]; } return (SKP_float)( 1.0f / ( 1.0f - lambda * gain ) ); } /* Convert warped filter coefficients to monic pseudo-warped coefficients and limit maximum */ /* amplitude of monic warped coefficients by using bandwidth expansion on the true coefficients */ SKP_INLINE void warped_true2monic_coefs( SKP_float *coefs_syn, SKP_float *coefs_ana, SKP_float lambda, SKP_float limit, SKP_int order ) { SKP_int i, iter, ind = 0; SKP_float tmp, maxabs, chirp, gain_syn, gain_ana; /* Convert to monic coefficients */ for( i = order - 1; i > 0; i-- ) { coefs_syn[ i - 1 ] -= lambda * coefs_syn[ i ]; coefs_ana[ i - 1 ] -= lambda * coefs_ana[ i ]; } gain_syn = ( 1.0f - lambda * lambda ) / ( 1.0f + lambda * coefs_syn[ 0 ] ); gain_ana = ( 1.0f - lambda * lambda ) / ( 1.0f + lambda * coefs_ana[ 0 ] ); for( i = 0; i < order; i++ ) { coefs_syn[ i ] *= gain_syn; coefs_ana[ i ] *= gain_ana; } /* Limit */ for( iter = 0; iter < 10; iter++ ) { /* Find maximum absolute value */ maxabs = -1.0f; for( i = 0; i < order; i++ ) { tmp = SKP_max( SKP_abs_float( coefs_syn[ i ] ), SKP_abs_float( coefs_ana[ i ] ) ); if( tmp > maxabs ) { maxabs = tmp; ind = i; } } if( maxabs <= limit ) { /* Coefficients are within range - done */ return; } /* Convert back to true warped coefficients */ for( i = 1; i < order; i++ ) { coefs_syn[ i - 1 ] += lambda * coefs_syn[ i ]; coefs_ana[ i - 1 ] += lambda * coefs_ana[ i ]; } gain_syn = 1.0f / gain_syn; gain_ana = 1.0f / gain_ana; for( i = 0; i < order; i++ ) { coefs_syn[ i ] *= gain_syn; coefs_ana[ i ] *= gain_ana; } /* Apply bandwidth expansion */ chirp = 0.99f - ( 0.8f + 0.1f * iter ) * ( maxabs - limit ) / ( maxabs * ( ind + 1 ) ); SKP_Silk_bwexpander_FLP( coefs_syn, order, chirp ); SKP_Silk_bwexpander_FLP( coefs_ana, order, chirp ); /* Convert to monic warped coefficients */ for( i = order - 1; i > 0; i-- ) { coefs_syn[ i - 1 ] -= lambda * coefs_syn[ i ]; coefs_ana[ i - 1 ] -= lambda * coefs_ana[ i ]; } gain_syn = ( 1.0f - lambda * lambda ) / ( 1.0f + lambda * coefs_syn[ 0 ] ); gain_ana = ( 1.0f - lambda * lambda ) / ( 1.0f + lambda * coefs_ana[ 0 ] ); for( i = 0; i < order; i++ ) { coefs_syn[ i ] *= gain_syn; coefs_ana[ i ] *= gain_ana; } } SKP_assert( 0 ); } /* Compute noise shaping coefficients and initial gain values */ void SKP_Silk_noise_shape_analysis_FLP( SKP_Silk_encoder_state_FLP *psEnc, /* I/O Encoder state FLP */ SKP_Silk_encoder_control_FLP *psEncCtrl, /* I/O Encoder control FLP */ const SKP_float *pitch_res, /* I LPC residual from pitch analysis */ const SKP_float *x /* I Input signal [frame_length + la_shape] */ ) { SKP_Silk_shape_state_FLP *psShapeSt = &psEnc->sShape; SKP_int k, nSamples; SKP_float SNR_adj_dB, HarmBoost, HarmShapeGain, Tilt; SKP_float nrg, pre_nrg, log_energy, log_energy_prev, energy_variation; SKP_float delta, BWExp1, BWExp2, gain_mult, gain_add, strength, b, warping; SKP_float x_windowed[ SHAPE_LPC_WIN_MAX ]; SKP_float auto_corr[ MAX_SHAPE_LPC_ORDER + 1 ]; const SKP_float *x_ptr, *pitch_res_ptr; /* Point to start of first LPC analysis block */ x_ptr = x - psEnc->sCmn.la_shape; /****************/ /* CONTROL SNR */ /****************/ /* Reduce SNR_dB values if recent bitstream has exceeded TargetRate */ psEncCtrl->current_SNR_dB = psEnc->SNR_dB - 0.05f * psEnc->BufferedInChannel_ms; /* Reduce SNR_dB if inband FEC used */ if( psEnc->speech_activity > LBRR_SPEECH_ACTIVITY_THRES ) { psEncCtrl->current_SNR_dB -= psEnc->inBandFEC_SNR_comp; } /****************/ /* GAIN CONTROL */ /****************/ /* Input quality is the average of the quality in the lowest two VAD bands */ psEncCtrl->input_quality = 0.5f * ( psEncCtrl->input_quality_bands[ 0 ] + psEncCtrl->input_quality_bands[ 1 ] ); /* Coding quality level, between 0.0 and 1.0 */ psEncCtrl->coding_quality = SKP_sigmoid( 0.25f * ( psEncCtrl->current_SNR_dB - 18.0f ) ); /* Reduce coding SNR during low speech activity */ b = 1.0f - psEnc->speech_activity; SNR_adj_dB = psEncCtrl->current_SNR_dB - BG_SNR_DECR_dB * psEncCtrl->coding_quality * ( 0.5f + 0.5f * psEncCtrl->input_quality ) * b * b; if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) { /* Reduce gains for periodic signals */ SNR_adj_dB += HARM_SNR_INCR_dB * psEnc->LTPCorr; } else { /* For unvoiced signals and low-quality input, adjust the quality slower than SNR_dB setting */ SNR_adj_dB += ( -0.4f * psEncCtrl->current_SNR_dB + 6.0f ) * ( 1.0f - psEncCtrl->input_quality ); } /*************************/ /* SPARSENESS PROCESSING */ /*************************/ /* Set quantizer offset */ if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) { /* Initally set to 0; may be overruled in process_gains(..) */ psEncCtrl->sCmn.QuantOffsetType = 0; psEncCtrl->sparseness = 0.0f; } else { /* Sparseness measure, based on relative fluctuations of energy per 2 milliseconds */ nSamples = 2 * psEnc->sCmn.fs_kHz; energy_variation = 0.0f; log_energy_prev = 0.0f; pitch_res_ptr = pitch_res; for( k = 0; k < FRAME_LENGTH_MS / 2; k++ ) { nrg = ( SKP_float )nSamples + ( SKP_float )SKP_Silk_energy_FLP( pitch_res_ptr, nSamples ); log_energy = SKP_Silk_log2( nrg ); if( k > 0 ) { energy_variation += SKP_abs_float( log_energy - log_energy_prev ); } log_energy_prev = log_energy; pitch_res_ptr += nSamples; } psEncCtrl->sparseness = SKP_sigmoid( 0.4f * ( energy_variation - 5.0f ) ); /* Set quantization offset depending on sparseness measure */ if( psEncCtrl->sparseness > SPARSENESS_THRESHOLD_QNT_OFFSET ) { psEncCtrl->sCmn.QuantOffsetType = 0; } else { psEncCtrl->sCmn.QuantOffsetType = 1; } /* Increase coding SNR for sparse signals */ SNR_adj_dB += SPARSE_SNR_INCR_dB * ( psEncCtrl->sparseness - 0.5f ); } /*******************************/ /* Control bandwidth expansion */ /*******************************/ /* More BWE for signals with high prediction gain */ strength = FIND_PITCH_WHITE_NOISE_FRACTION * psEncCtrl->predGain; /* between 0.0 and 1.0 */ BWExp1 = BWExp2 = BANDWIDTH_EXPANSION / ( 1.0f + strength * strength ); delta = LOW_RATE_BANDWIDTH_EXPANSION_DELTA * ( 1.0f - 0.75f * psEncCtrl->coding_quality ); BWExp1 -= delta; BWExp2 += delta; /* BWExp1 will be applied after BWExp2, so make it relative */ BWExp1 /= BWExp2; if( psEnc->sCmn.warping_Q16 > 0 ) { /* Slightly more warping in analysis will move quantization noise up in frequency, where it's better masked */ warping = (SKP_float)psEnc->sCmn.warping_Q16 / 65536.0f + 0.01f * psEncCtrl->coding_quality; } else { warping = 0.0f; } /********************************************/ /* Compute noise shaping AR coefs and gains */ /********************************************/ for( k = 0; k < NB_SUBFR; k++ ) { /* Apply window: sine slope followed by flat part followed by cosine slope */ SKP_int shift, slope_part, flat_part; flat_part = psEnc->sCmn.fs_kHz * 5; slope_part = ( psEnc->sCmn.shapeWinLength - flat_part ) / 2; SKP_Silk_apply_sine_window_FLP( x_windowed, x_ptr, 1, slope_part ); shift = slope_part; SKP_memcpy( x_windowed + shift, x_ptr + shift, flat_part * sizeof(SKP_float) ); shift += flat_part; SKP_Silk_apply_sine_window_FLP( x_windowed + shift, x_ptr + shift, 2, slope_part ); /* Update pointer: next LPC analysis block */ x_ptr += psEnc->sCmn.subfr_length; if( psEnc->sCmn.warping_Q16 > 0 ) { /* Calculate warped auto correlation */ SKP_Silk_warped_autocorrelation_FLP( auto_corr, x_windowed, warping, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder ); } else { /* Calculate regular auto correlation */ SKP_Silk_autocorrelation_FLP( auto_corr, x_windowed, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder + 1 ); } /* Add white noise, as a fraction of energy */ auto_corr[ 0 ] += auto_corr[ 0 ] * SHAPE_WHITE_NOISE_FRACTION; /* Convert correlations to prediction coefficients, and compute residual energy */ nrg = SKP_Silk_levinsondurbin_FLP( &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], auto_corr, psEnc->sCmn.shapingLPCOrder ); psEncCtrl->Gains[ k ] = ( SKP_float )sqrt( nrg ); if( psEnc->sCmn.warping_Q16 > 0 ) { /* Adjust gain for warping */ psEncCtrl->Gains[ k ] *= warped_gain( &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], warping, psEnc->sCmn.shapingLPCOrder ); } /* Bandwidth expansion for synthesis filter shaping */ SKP_Silk_bwexpander_FLP( &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder, BWExp2 ); /* Compute noise shaping filter coefficients */ SKP_memcpy( &psEncCtrl->AR1[ k * MAX_SHAPE_LPC_ORDER ], &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder * sizeof( SKP_float ) ); /* Bandwidth expansion for analysis filter shaping */ SKP_Silk_bwexpander_FLP( &psEncCtrl->AR1[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder, BWExp1 ); /* Ratio of prediction gains, in energy domain */ SKP_Silk_LPC_inverse_pred_gain_FLP( &pre_nrg, &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder ); SKP_Silk_LPC_inverse_pred_gain_FLP( &nrg, &psEncCtrl->AR1[ k * MAX_SHAPE_LPC_ORDER ], psEnc->sCmn.shapingLPCOrder ); psEncCtrl->GainsPre[ k ] = 1.0f - 0.7f * ( 1.0f - pre_nrg / nrg ); /* Convert to monic warped prediction coefficients and limit absolute values */ warped_true2monic_coefs( &psEncCtrl->AR2[ k * MAX_SHAPE_LPC_ORDER ], &psEncCtrl->AR1[ k * MAX_SHAPE_LPC_ORDER ], warping, 3.999f, psEnc->sCmn.shapingLPCOrder ); } /*****************/ /* Gain tweaking */ /*****************/ /* Increase gains during low speech activity and put lower limit on gains */ gain_mult = ( SKP_float )pow( 2.0f, -0.16f * SNR_adj_dB ); gain_add = ( SKP_float )pow( 2.0f, 0.16f * NOISE_FLOOR_dB ) + ( SKP_float )pow( 2.0f, 0.16f * RELATIVE_MIN_GAIN_dB ) * psEnc->avgGain; for( k = 0; k < NB_SUBFR; k++ ) { psEncCtrl->Gains[ k ] *= gain_mult; psEncCtrl->Gains[ k ] += gain_add; psEnc->avgGain += psEnc->speech_activity * GAIN_SMOOTHING_COEF * ( psEncCtrl->Gains[ k ] - psEnc->avgGain ); } /************************************************/ /* Decrease level during fricatives (de-essing) */ /************************************************/ gain_mult = 1.0f + INPUT_TILT + psEncCtrl->coding_quality * HIGH_RATE_INPUT_TILT; if( psEncCtrl->input_tilt <= 0.0f && psEncCtrl->sCmn.sigtype == SIG_TYPE_UNVOICED ) { SKP_float essStrength = -psEncCtrl->input_tilt * psEnc->speech_activity * ( 1.0f - psEncCtrl->sparseness ); if( psEnc->sCmn.fs_kHz == 24 ) { gain_mult *= ( SKP_float )pow( 2.0f, -0.16f * DE_ESSER_COEF_SWB_dB * essStrength ); } else if( psEnc->sCmn.fs_kHz == 16 ) { gain_mult *= (SKP_float)pow( 2.0f, -0.16f * DE_ESSER_COEF_WB_dB * essStrength ); } else { SKP_assert( psEnc->sCmn.fs_kHz == 12 || psEnc->sCmn.fs_kHz == 8 ); } } for( k = 0; k < NB_SUBFR; k++ ) { psEncCtrl->GainsPre[ k ] *= gain_mult; } /************************************************/ /* Control low-frequency shaping and noise tilt */ /************************************************/ /* Less low frequency shaping for noisy inputs */ strength = LOW_FREQ_SHAPING * ( 1.0f + LOW_QUALITY_LOW_FREQ_SHAPING_DECR * ( psEncCtrl->input_quality_bands[ 0 ] - 1.0f ) ); if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) { /* Reduce low frequencies quantization noise for periodic signals, depending on pitch lag */ /*f = 400; freqz([1, -0.98 + 2e-4 * f], [1, -0.97 + 7e-4 * f], 2^12, Fs); axis([0, 1000, -10, 1])*/ for( k = 0; k < NB_SUBFR; k++ ) { b = 0.2f / psEnc->sCmn.fs_kHz + 3.0f / psEncCtrl->sCmn.pitchL[ k ]; psEncCtrl->LF_MA_shp[ k ] = -1.0f + b; psEncCtrl->LF_AR_shp[ k ] = 1.0f - b - b * strength; } Tilt = - HP_NOISE_COEF - (1 - HP_NOISE_COEF) * HARM_HP_NOISE_COEF * psEnc->speech_activity; } else { b = 1.3f / psEnc->sCmn.fs_kHz; psEncCtrl->LF_MA_shp[ 0 ] = -1.0f + b; psEncCtrl->LF_AR_shp[ 0 ] = 1.0f - b - b * strength * 0.6f; for( k = 1; k < NB_SUBFR; k++ ) { psEncCtrl->LF_MA_shp[ k ] = psEncCtrl->LF_MA_shp[ 0 ]; psEncCtrl->LF_AR_shp[ k ] = psEncCtrl->LF_AR_shp[ 0 ]; } Tilt = -HP_NOISE_COEF; } /****************************/ /* HARMONIC SHAPING CONTROL */ /****************************/ /* Control boosting of harmonic frequencies */ HarmBoost = LOW_RATE_HARMONIC_BOOST * ( 1.0f - psEncCtrl->coding_quality ) * psEnc->LTPCorr; /* More harmonic boost for noisy input signals */ HarmBoost += LOW_INPUT_QUALITY_HARMONIC_BOOST * ( 1.0f - psEncCtrl->input_quality ); if( USE_HARM_SHAPING && psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) { /* Harmonic noise shaping */ HarmShapeGain = HARMONIC_SHAPING; /* More harmonic noise shaping for high bitrates or noisy input */ HarmShapeGain += HIGH_RATE_OR_LOW_QUALITY_HARMONIC_SHAPING * ( 1.0f - ( 1.0f - psEncCtrl->coding_quality ) * psEncCtrl->input_quality ); /* Less harmonic noise shaping for less periodic signals */ HarmShapeGain *= ( SKP_float )sqrt( psEnc->LTPCorr ); } else { HarmShapeGain = 0.0f; } /*************************/ /* Smooth over subframes */ /*************************/ for( k = 0; k < NB_SUBFR; k++ ) { psShapeSt->HarmBoost_smth += SUBFR_SMTH_COEF * ( HarmBoost - psShapeSt->HarmBoost_smth ); psEncCtrl->HarmBoost[ k ] = psShapeSt->HarmBoost_smth; psShapeSt->HarmShapeGain_smth += SUBFR_SMTH_COEF * ( HarmShapeGain - psShapeSt->HarmShapeGain_smth ); psEncCtrl->HarmShapeGain[ k ] = psShapeSt->HarmShapeGain_smth; psShapeSt->Tilt_smth += SUBFR_SMTH_COEF * ( Tilt - psShapeSt->Tilt_smth ); psEncCtrl->Tilt[ k ] = psShapeSt->Tilt_smth; } }
Java
/* Galois, a framework to exploit amorphous data-parallelism in irregular programs. Copyright (C) 2010, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. File: GNode.java */ package galois.objects.graph; import galois.objects.GObject; import galois.objects.Lockable; import galois.objects.Mappable; import galois.runtime.Replayable; /** * A node in a graph. * * @param <N> the type of the data stored in each node */ public interface GNode<N> extends Replayable, Lockable, Mappable<GNode<N>>, GObject { /** * Retrieves the node data associated with the vertex * * All the Galois runtime actions (e.g., conflict detection) will be performed when * the method is executed. * * @return the data contained in the node */ public N getData(); /** * Retrieves the node data associated with the vertex. Equivalent to {@link #getData(byte, byte)} * passing <code>flags</code> to both parameters. * * @param flags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method. See {@link galois.objects.MethodFlag} * @return the data contained in the node */ public N getData(byte flags); /** * Retrieves the node data associated with the vertex. For convenience, this method * also calls {@link GObject#access(byte)} on the returned data. * * <p>Recall that the * {@link GNode} object maintains information about the vertex and its connectivity * in the graph. This is separate from the data itself. For example, * <code>getData(MethodFlag.NONE, MethodFlag.SAVE_UNDO)</code> * does not acquire an abstract lock on the {@link GNode} (perhaps because * it was returned by a call to {@link GNode#map(util.fn.LambdaVoid)}), but it * saves undo information on the returned data in case the iteration needs to * be rolled back. * </p> * * @param nodeFlags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method on the <i>node itself</i>. * See {@link galois.objects.MethodFlag} * @param dataFlags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method on the <i>data</i> contained in the node. * See {@link galois.objects.MethodFlag} * @return the data contained in the node */ public N getData(byte nodeFlags, byte dataFlags); /** * Sets the node data. * * All the Galois runtime actions (e.g., conflict detection) will be performed when * the method is executed. * * @param d the data to be stored * @return the old data associated with the node */ public N setData(N d); /** * Sets the node data. * * @param d the data to be stored * @param flags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method. See {@link galois.objects.MethodFlag} * @return the old data associated with the node */ public N setData(N d, byte flags); }
Java
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace SharpGraphLib { public partial class LegendControl : UserControl { List<LegendLabel> _Labels = new List<LegendLabel>(); bool _AllowHighlightingGraphs = true, _AllowDisablingGraphs = true; [Category("Behavior")] [DefaultValue(true)] public bool AllowDisablingGraphs { get { return _AllowDisablingGraphs; } set { _AllowDisablingGraphs = value;} } [Category("Behavior")] [DefaultValue(true)] public bool AllowHighlightingGraphs { get { return _AllowHighlightingGraphs; } set { _AllowHighlightingGraphs = value; } } bool _Autosize; internal bool Autosize { get { return _Autosize; } set { _Autosize = value; if (value) { Width = _AutoWidth; Height = _AutoHeight; } } } public LegendControl() { InitializeComponent(); } [Category("Appearance")] public string NoGraphsLabel { get { return label1.Text; } set { label1.Text = value; } } internal GraphViewer _GraphViewer; int _AutoWidth, _AutoHeight; /// <summary> /// Collection items should implement ILegendItem /// </summary> protected virtual System.Collections.IEnumerable Items { get { if (_GraphViewer == null) return null; return _GraphViewer.DisplayedGraphs; } } public void UpdateLegend() { foreach (LegendLabel lbl in _Labels) lbl.Dispose(); _Labels.Clear(); int i = 0; if (Items != null) { _AutoWidth = 0; foreach (ILegendItem gr in Items) { if (gr.HiddenFromLegend) continue; LegendLabel lbl = new LegendLabel { ForeColor = ForeColor }; lbl.Parent = this; lbl.SquareColor = gr.Color; lbl.Text = gr.Hint; lbl.Grayed = gr.Hidden; lbl.Left = 0; lbl.Top = i * lbl.Height + label1.Top; lbl.Width = Width; lbl.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; lbl.Tag = gr; lbl.Cursor = Cursors.Arrow; lbl.MouseClick += new MouseEventHandler(LegendPanel_MouseClick); lbl.MouseEnter += new EventHandler(LegendPanel_MouseEnter); lbl.MouseLeave += new EventHandler(LegendPanel_MouseLeave); lbl.MouseMove += new MouseEventHandler(lbl_MouseMove); lbl.MouseDown += new MouseEventHandler(lbl_MouseDown); _AutoWidth = Math.Max(_AutoWidth, lbl.Left + lbl.MeasureWidth() + 10); _AutoHeight = lbl.Bottom + 10; lbl.Visible = true; _Labels.Add(lbl); i++; } label1.Visible = false; } if (i == 0) { label1.Visible = true; _AutoWidth = label1.Right + 10; _AutoHeight = label1.Bottom + 10; } if (_Autosize) { Width = _AutoWidth; Height = _AutoHeight; } } protected virtual void lbl_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point newPoint = PointToClient((sender as Control).PointToScreen(e.Location)); OnMouseDown(new MouseEventArgs(e.Button, e.Clicks, newPoint.X, newPoint.Y, e.Delta)); } } protected virtual void lbl_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point newPoint = PointToClient((sender as Control).PointToScreen(e.Location)); OnMouseMove(new MouseEventArgs(e.Button, e.Clicks, newPoint.X, newPoint.Y, e.Delta)); } } public delegate void HandleLabelHilighted(ILegendItem item); public event HandleLabelHilighted OnLabelHilighted; LegendLabel _ActiveLabel; public ILegendItem ActiveItem { get { if (_ActiveLabel == null) return null; return _ActiveLabel.Tag as ILegendItem; } } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); _ActiveLabel = null; } void LegendPanel_MouseLeave(object sender, EventArgs e) { if (!_AllowHighlightingGraphs) return; LegendLabel lbl = sender as LegendLabel; lbl.BackColor = BackColor; if (OnLabelHilighted != null) OnLabelHilighted(null); } void LegendPanel_MouseEnter(object sender, EventArgs e) { _ActiveLabel = sender as LegendLabel; if (!_AllowHighlightingGraphs) return; LegendLabel lbl = sender as LegendLabel; lbl.BackColor = _HighlightedColor; if (OnLabelHilighted != null) OnLabelHilighted((ILegendItem)lbl.Tag); } public delegate void HandleLabelGrayed(ILegendItem graph, bool grayed); public event HandleLabelGrayed OnLabelGrayed; virtual protected void LegendPanel_MouseClick(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; if (!_AllowDisablingGraphs) return; LegendLabel label = sender as LegendLabel; label.Grayed = !label.Grayed; if (OnLabelGrayed != null) OnLabelGrayed((ILegendItem)label.Tag, label.Grayed); } private Color _HighlightedColor = Color.LemonChiffon; public System.Drawing.Color HighlightedColor { get { return _HighlightedColor; } set { _HighlightedColor = value; Invalidate(); } } } }
Java
#include "samplesat.h" #include "memalloc.h" #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <string.h> uint32_t num_sorts = 100; uint32_t num_consts = 1000; uint32_t buf_len = 11; #define ENABLE 0 typedef struct inclause_buffer_t { int32_t size; input_literal_t ** data; } inclause_buffer_t; static inclause_buffer_t inclause_buffer = {0, NULL}; int main(){ samp_table_t table; init_samp_table(&table); sort_table_t *sort_table = &(table.sort_table); const_table_t *const_table = &(table.const_table); pred_table_t *pred_table = &(table.pred_table); atom_table_t *atom_table = &(table.atom_table); clause_table_t *clause_table = &(table.clause_table); uint32_t i, j; char sort_num[6]; char const_num[6]; char pred_num[6]; char *buffer; for (i = 0; i < num_sorts; i++){ sprintf(sort_num, "%d", i); buffer = (char *) safe_malloc(sizeof(char)*buf_len); memcpy(buffer, "sort", buf_len); strcat(buffer, sort_num); add_sort(sort_table, buffer); } if (ENABLE){ printf("\nsort_table: size: %"PRId32", num_sorts: %"PRId32"", sort_table->size, sort_table->num_sorts); for (i = 0; i < num_sorts; i++){ buffer = sort_table->entries[i].name; printf("\nsort[%"PRIu32"]: %s; symbol_table: %"PRId32"", i, buffer, stbl_find(&(sort_table->sort_name_index), buffer)); add_sort(sort_table, buffer);//should do nothing printf("\nRe:sort[%"PRIu32"]: %s; symbol_table: %"PRId32"", i, buffer, stbl_find(&(sort_table->sort_name_index), buffer)); } } /* Now testing constants */ for (i = 0; i < num_sorts; i++){ for (j = 0; j < (num_consts/num_sorts); j++){ sprintf(const_num, "%d", i*(num_consts/num_sorts) + j); memcpy(buffer, "const", 6); strcat(buffer, const_num); add_const(const_table, buffer, sort_table, sort_table->entries[i].name); } } if (ENABLE){ for (i=0; i < num_sorts; i++){ printf("\nsort = %s", sort_table->entries[i].name); for (j = 0; j < sort_table->entries[i].cardinality; j++){ printf("\nconst = %s", const_table->entries[sort_table->entries[i].constants[j]].name); } } } /* Now testing signatures */ bool evidence = 0; char **sort_name_buffer = (char **) safe_malloc(num_sorts * sizeof(char *)); printf("\nAdding normal preds"); for (i = 0; i < num_sorts; i++){ sort_name_buffer[i] = sort_table->entries[i].name; memcpy(buffer, "pred", 5); sprintf(pred_num, "%d", i); strcat(buffer, pred_num); add_pred(pred_table, buffer, evidence, i, sort_table, sort_name_buffer); } evidence = !evidence; printf("\nAdding evidence preds"); for (j = 0; j < num_sorts; j++){ sort_name_buffer[j] = sort_table->entries[j].name; memcpy(buffer, "pred", 5); sprintf(pred_num, "%d", j+i); strcat(buffer, pred_num); add_pred(pred_table, buffer, evidence, j, sort_table, sort_name_buffer); } if (ENABLE){ for (i = 0; i < pred_table->evpred_tbl.num_preds; i++){ printf("\n evpred[%d] = ", i); buffer = pred_table->evpred_tbl.entries[i].name; printf("index(%d); ", pred_index(buffer, pred_table)); printf("%s(", buffer); for (j = 0; j < pred_table->evpred_tbl.entries[i].arity; j++){ printf(" %s, ", sort_table->entries[pred_table->evpred_tbl.entries[i].signature[j]].name); } printf(")"); } for (i = 0; i < pred_table->pred_tbl.num_preds; i++){ printf("\n pred[%d] = ", i); buffer = pred_table->pred_tbl.entries[i].name; printf("index(%d); ", pred_index(buffer, pred_table)); printf("%s(", buffer); for (j = 0; j < pred_table->pred_tbl.entries[i].arity; j++){ printf(" %s, ", sort_table->entries[pred_table->pred_tbl.entries[i].signature[j]].name); } printf(")"); } } /* Now adding evidence atoms */ input_atom_t * atom_buffer = (input_atom_t *) safe_malloc(101 * sizeof(char *)); int32_t index; for (i = 0; i < pred_table->evpred_tbl.num_preds; i++){ atom_buffer->pred = pred_table->evpred_tbl.entries[i].name; printf("\nBuilding atom[%d]: %s(", i, atom_buffer->pred); for(j = 0; j < pred_table->evpred_tbl.entries[i].arity; j++){ index = sort_table->entries[pred_table->evpred_tbl.entries[i].signature[j]].constants[0]; buffer = const_table->entries[index].name; printf("[%d]%s,", index, buffer); atom_buffer->args[j] = buffer; } printf(")"); add_atom(&table, atom_buffer); } if (ENABLE){ for (i = 0; i < atom_table->num_vars; i++){ printf("\natom[%d] = %d(", i, atom_table->atom[i]->pred); for (j = 0; j < pred_table->evpred_tbl.entries[-atom_table->atom[i]->pred].arity; j++){ printf("%d,", atom_table->atom[i]->args[j]); } printf(")"); printf("\nassignment[%d] = %d", i, atom_table->assignment[i]); } for (i = 0; i < pred_table->evpred_tbl.num_preds; i++){ printf("\n"); for (j = 0; j < pred_table->evpred_tbl.entries[i].num_atoms; j++){ printf("%d", pred_table->evpred_tbl.entries[i].atoms[j]); } } } /* Now adding atoms */ int32_t numvars = atom_table->num_vars; for (i = 0; i < pred_table->pred_tbl.num_preds; i++){ atom_buffer->pred = pred_table->pred_tbl.entries[i].name; printf("\nBuilding atom[%d]: %s(", i, atom_buffer->pred); for(j = 0; j < pred_table->pred_tbl.entries[i].arity; j++){ index = sort_table->entries[pred_table->pred_tbl.entries[i].signature[j]].constants[0]; buffer = const_table->entries[index].name; printf("[%d]%s,", index, buffer); atom_buffer->args[j] = buffer; } printf(")"); add_atom(&table, atom_buffer); } if (ENABLE){ for (i = numvars; i < atom_table->num_vars; i++){ printf("\natom[%d] = %d(", i, atom_table->atom[i]->pred); for (j = 0; j < pred_table->pred_tbl.entries[atom_table->atom[i]->pred].arity; j++){ printf("%d,", atom_table->atom[i]->args[j]); } printf(")"); printf("\nassignment[%d] = %d", i, atom_table->assignment[i]); } for (i = 0; i < pred_table->pred_tbl.num_preds; i++){ printf("\n"); for (j = 0; j < pred_table->pred_tbl.entries[i].num_atoms; j++){ printf("%d", pred_table->pred_tbl.entries[i].atoms[j]); } } } /* * Adding clauses */ double weight = 0; j = pred_table->pred_tbl.num_preds + 1; inclause_buffer.data = (input_literal_t **) safe_malloc(j * sizeof(input_literal_t *)); inclause_buffer.size = j; for (i = 0; i < j; i++){ inclause_buffer.data[i] = NULL; } bool negate = false; for (i = 0; i < pred_table->pred_tbl.num_preds-1; i++){ inclause_buffer.data[i] = (input_literal_t *) safe_malloc(sizeof(input_literal_t) + i*sizeof(char *)); /// inclause_buffer.data[i]->neg = !inclause_buffer.data[i]->neg; // ??? inclause_buffer.data[i]->neg = negate; negate = !negate; inclause_buffer.data[i]->atom.pred = pred_table->pred_tbl.entries[i+1].name; for (j = 0; j < i; j++){ index = sort_table->entries[pred_table->pred_tbl.entries[i+1].signature[j]].constants[0]; inclause_buffer.data[i]->atom.args[j] = const_table->entries[index].name; } weight += .25; add_clause(&table, inclause_buffer.data, weight); } print_clauses(clause_table); print_atoms(atom_table, pred_table, const_table); return 1; }
Java
//============================================================================ // I B E X // File : ibex_DoubleHeap.h // Author : Gilles Chabert, Jordan Ninin // Copyright : IMT Atlantique (France) // License : See the LICENSE file // Created : Sep 12, 2014 // Last Update : Dec 25, 2017 //============================================================================ #ifndef __IBEX_DOUBLE_HEAP_H__ #define __IBEX_DOUBLE_HEAP_H__ #include "ibex_SharedHeap.h" #include "ibex_Random.h" namespace ibex { /** * \brief Double-heap */ template<class T> class DoubleHeap { public: /** * \brief Create a double heap * * \param cost1 - cost function for the first heap * \param update_cost1_when_sorting - whether this cost is recalculated when sorting * \param cost2 - cost function for the second heap * \param update_cost2_when_sorting - whether this cost is recalculated when sorting * \param critpr - probability to chose the second heap as an integer in [0,100] (default value 50). * Value 0 or correspond to use a single criterion for node selection * > 0 = only the first heap * > 100 = only the second heap. */ DoubleHeap(CostFunc<T>& cost1, bool update_cost1_when_sorting, CostFunc<T>& cost2, bool update_cost2_when_sorting, int critpr=50); /** * \brief Copy constructor. */ explicit DoubleHeap(const DoubleHeap& dhcp, bool deep_copy=false); /** * \brief Flush the heap. * * All the remaining data will be *deleted*. */ void flush(); /** * \brief Clear the heap. * * All the remaining data will be *removed* without being *deleted*. */ void clear(); /** \brief Return the size of the buffer. */ unsigned int size() const; /** \brief Return true if the buffer is empty. */ bool empty() const; /** \brief Push new data on the heap. */ void push(T* data); /** \brief Pop data from the stack and return it.*/ T* pop(); /** \brief Pop data from the first heap and return it.*/ T* pop1(); /** \brief Pop data from the second heap and return it.*/ T* pop2(); /** \brief Return next data (but does not pop it).*/ T* top() const; /** \brief Return next data of the first heap (but does not pop it).*/ T* top1() const; /** \brief Return next data of the second heap (but does not pop it).*/ T* top2() const; /** * \brief Return the minimum (the criterion for the first heap) * * Complexity: o(1) */ double minimum() const; /** * \brief Return the first minimum (the criterion for the first heap) * * Complexity: o(1) */ double minimum1() const; /** * \brief Return the second minimum (the criterion for the second heap) * * Complexity: o(1) */ double minimum2() const; /** * \brief Contract the heap * * Removes (and deletes) from the two heaps all the data * with a cost (according to the cost function of the first heap) * that is greater than \a loup1. * * The costs of the first heap are assumed to be up-to-date. * * TODO: in principle we should implement the symmetric * case where the contraction is performed with respect * to the cost of the second heap. */ void contract(double loup1); /** * \brief Delete this */ virtual ~DoubleHeap(); template<class U> friend std::ostream& operator<<(std::ostream& os, const DoubleHeap<U>& heap); protected: /** Count the number of nodes pushed since * the object is created. */ unsigned int nb_nodes; /** the first heap */ SharedHeap<T> *heap1; /** the second heap */ SharedHeap<T> *heap2; /** Probability to choose the second * (see details in the constructor) */ const int critpr; /** Current selected heap. */ mutable int current_heap_id; /** * Used in the contract function by recursivity * * \param heap: the new heap1 under construction (will * eventually replace the current heap1). */ void contract_rec(double new_loup, HeapNode<T>* node, SharedHeap<T>& heap, bool percolate); private: /** * Erase all the subnodes of node (including itself) in the first heap * and manage the impact on the second heap. * If "percolate" is true, the second heap is left in a correct state. * Otherwise, the second heap has a binary tree structure but not sorted * anymore. Therefore, "sort" should be called on the second heap. * * So the heap structure is maintained for the second heap * but not the first one. The reason is that this function is called * either by "contract" or "flush". "contract" will build a new heap from scratch. */ void erase_subnodes(HeapNode<T>* node, bool percolate); std::ostream& print(std::ostream& os) const; }; /*================================== inline implementations ========================================*/ template<class T> DoubleHeap<T>::DoubleHeap(CostFunc<T>& cost1, bool update_cost1_when_sorting, CostFunc<T>& cost2, bool update_cost2_when_sorting, int critpr) : nb_nodes(0), heap1(new SharedHeap<T>(cost1,update_cost1_when_sorting,0)), heap2(new SharedHeap<T>(cost2,update_cost2_when_sorting,1)), critpr(critpr), current_heap_id(0) { } template<class T> DoubleHeap<T>::DoubleHeap(const DoubleHeap &dhcp, bool deep_copy) : nb_nodes(dhcp.nb_nodes), heap1(NULL), heap2(NULL), critpr(dhcp.critpr), current_heap_id(dhcp.current_heap_id) { heap1 = new SharedHeap<T>(*dhcp.heap1, 2, deep_copy); std::vector<HeapElt<T>*> p = heap1->elt(); heap2 = new SharedHeap<T>(dhcp.heap2->costf, dhcp.heap2->update_cost_when_sorting, dhcp.heap2->heap_id); while(!p.empty()) { heap2->push_elt(p.back()); p.pop_back(); } } template<class T> DoubleHeap<T>::~DoubleHeap() { clear(); // what for? if (heap1) delete heap1; if (heap2) delete heap2; } template<class T> void DoubleHeap<T>::flush() { if (nb_nodes>0) { heap1->clear(SharedHeap<T>::NODE); heap2->clear(SharedHeap<T>::NODE_ELT_DATA); nb_nodes=0; } } template<class T> void DoubleHeap<T>::clear() { if (nb_nodes>0) { heap1->clear(SharedHeap<T>::NODE); heap2->clear(SharedHeap<T>::NODE_ELT); nb_nodes=0; } } template<class T> unsigned int DoubleHeap<T>::size() const { assert(heap1->size()==heap2->size()); return nb_nodes; } template<class T> void DoubleHeap<T>::contract(double new_loup1) { if (nb_nodes==0) return; SharedHeap<T>* copy1 = new SharedHeap<T>(heap1->costf, heap1->update_cost_when_sorting, 0); contract_rec(new_loup1, heap1->root, *copy1, !heap2->update_cost_when_sorting); heap1->root = copy1->root; heap1->nb_nodes = copy1->size(); nb_nodes = copy1->size(); copy1->root = NULL; copy1->nb_nodes=0;// avoid to delete heap1 with copy1 delete copy1; if (heap2->update_cost_when_sorting) heap2->sort(); assert(nb_nodes==heap2->size()); assert(nb_nodes==heap1->size()); assert(heap1->heap_state()); assert(!heap2 || heap2->heap_state()); } template<class T> void DoubleHeap<T>::contract_rec(double new_loup1, HeapNode<T>* node, SharedHeap<T>& heap, bool percolate) { // the cost are assumed to be up-to-date for the 1st heap if (node->is_sup(new_loup1, 0)) { // we must remove from the other heap all the sub-nodes if (heap2) erase_subnodes(node, percolate); } else { heap.push_elt(node->elt); if (node->left) contract_rec(new_loup1, node->left, heap, percolate); if (node->right) contract_rec(new_loup1, node->right, heap, percolate); delete node; } } template<class T> void DoubleHeap<T>::erase_subnodes(HeapNode<T>* node, bool percolate) { if (node->left) erase_subnodes(node->left, percolate); if (node->right) erase_subnodes(node->right, percolate); if (!percolate) // there is no need to update the order now in the second heap // since all costs will have to be recalculated. // The heap2 will be sorted at the end (see contract) heap2->erase_node_no_percolate(node->elt->holder[1]); else heap2->erase_node(node->elt->holder[1]); if (node->elt->data) delete node->elt->data; delete node->elt; delete node; } template<class T> bool DoubleHeap<T>::empty() const { // if one buffer is empty, the other is also empty return (nb_nodes==0); } template<class T> void DoubleHeap<T>::push(T* data) { HeapElt<T>* elt; if (heap2) { elt = new HeapElt<T>(data, heap1->cost(*data), heap2->cost(*data)); } else { elt = new HeapElt<T>(data, heap1->cost(*data)); } // the data is put into the first heap heap1->push_elt(elt); if (heap2) heap2->push_elt(elt); nb_nodes++; } template<class T> T* DoubleHeap<T>::pop() { assert(size()>0); //std::cout << " \n\n Heap1=" << (*heap1); // Select the heap HeapElt<T>* elt; if (current_heap_id==0) { elt = heap1->pop_elt(); if (heap2) heap2->erase_node(elt->holder[1]); } else { elt = heap2->pop_elt(); heap1->erase_node(elt->holder[0]); } T* data = elt->data; elt->data=NULL; // avoid the data to be deleted with the element delete elt; nb_nodes--; assert(heap1->heap_state()); assert(!heap2 || heap2->heap_state()); // select the heap if (RNG::rand() % 100 >= static_cast<unsigned>(critpr)) { current_heap_id=0; } else { current_heap_id=1; } return data; } template<class T> T* DoubleHeap<T>::pop1() { // the first heap is used current_heap_id=0; return pop(); } template<class T> T* DoubleHeap<T>::pop2() { // the second heap is used current_heap_id=1; return pop(); } template<class T> T* DoubleHeap<T>::top() const { assert(size()>0); if (current_heap_id==0) { return heap1->top(); } else { // the second heap is used return heap2->top(); } } template<class T> T* DoubleHeap<T>::top1() const { // the first heap is used current_heap_id=0; return heap1->top(); } template<class T> T* DoubleHeap<T>::top2() const { // the second heap is used current_heap_id=1; return heap2->top(); } template<class T> inline double DoubleHeap<T>::minimum() const { return heap1->minimum(); } template<class T> inline double DoubleHeap<T>::minimum1() const { return heap1->minimum(); } template<class T> inline double DoubleHeap<T>::minimum2() const { return heap2->minimum(); } template<class T> std::ostream& DoubleHeap<T>::print(std::ostream& os) const{ if (this->empty()) { os << " EMPTY "; os<<std::endl; } else { os << "First Heap: "<<std::endl; heap1->print(os); os<<std::endl; os << "Second Heap: "<<std::endl; heap2->print(os); os<<std::endl; } return os; } template<class T> std::ostream& operator<<(std::ostream& os, const DoubleHeap<T>& heap) { return heap.print(os); } } // namespace ibex #endif // __IBEX_DOUBLE_HEAP_H__
Java
/** * Premium Markets is an automated stock market analysis system. * It implements a graphical environment for monitoring stock markets technical analysis * major indicators, for portfolio management and historical data charting. * In its advanced packaging -not provided under this license- it also includes : * Screening of financial web sites to pick up the best market shares, * Price trend prediction based on stock markets technical analysis and indices rotation, * Back testing, Automated buy sell email notifications on trend signals calculated over * markets and user defined portfolios. * With in mind beating the buy and hold strategy. * Type 'Premium Markets FORECAST' in your favourite search engine for a free workable demo. * * Copyright (C) 2008-2014 Guillaume Thoreton * * This file is part of Premium Markets. * * Premium Markets is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU 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 <http://www.gnu.org/licenses/>. */ package com.finance.pms.events.pounderationrules; import java.util.HashMap; import com.finance.pms.admin.install.logging.MyLogger; import com.finance.pms.datasources.shares.Stock; import com.finance.pms.events.SymbolEvents; import com.finance.pms.events.Validity; public class LatestNoYoYoValidatedPonderationRule extends LatestEventsPonderationRule { private static final long serialVersionUID = 573802685420097964L; private static MyLogger LOGGER = MyLogger.getLogger(LatestNoYoYoValidatedPonderationRule.class); private HashMap<Stock, Validity> tuningValidityList; public LatestNoYoYoValidatedPonderationRule(Integer sellThreshold, Integer buyThreshold, HashMap<Stock, Validity> tuningValidityList) { super(sellThreshold, buyThreshold); this.tuningValidityList = tuningValidityList; } @Override public int compare(SymbolEvents o1, SymbolEvents o2) { SymbolEvents se1 = o1; SymbolEvents se2 = o2; PonderationRule p1 = new LatestNoYoYoValidatedPonderationRule(sellThreshold, buyThreshold, tuningValidityList); PonderationRule p2 = new LatestNoYoYoValidatedPonderationRule(sellThreshold, buyThreshold, tuningValidityList); return compareCal(se1, se2, p1, p2); } @Override public Float finalWeight(SymbolEvents symbolEvents) { Validity validity = tuningValidityList.get(symbolEvents.getStock()); boolean isValid = false; if (validity != null) { isValid = validity.equals(Validity.SUCCESS); } else { LOGGER.warn("No validity information found for " + symbolEvents.getStock() + " while parsing events " + symbolEvents + ". Neural trend was not calculated for that stock."); } if (isValid) { return super.finalWeight(symbolEvents); } else { return 0.0f; } } @Override public Signal initSignal(SymbolEvents symbolEvents) { return new LatestNoYoYoValidatedSignal(symbolEvents.getEventDefList()); } @Override protected void postCondition(Signal signal) { LatestNoYoYoValidatedSignal LVSignal = (LatestNoYoYoValidatedSignal) signal; //Updating cumulative event signal with Bull Bear neural events. switch (LVSignal.getNbTrendChange()) { case 0 : //No event detected break; case 1 : //One Type of Event, no yoyo : weight = sum(cumulative events) + bullish - bearish signal.setSignalWeight(signal.getSignalWeight() + LVSignal.getNbBullish() - LVSignal.getNbBearish()); break; default : //Yoyo, Bull/Bear, we ignore the signal LOGGER.warn("Yo yo trend detected."); break; } } }
Java
/** * * This file is part of Disco. * * Disco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Disco 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 Disco. If not, see <http://www.gnu.org/licenses/>. */ package eu.diversify.disco.cloudml; import eu.diversify.disco.population.diversity.TrueDiversity; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Options { private static final String JSON_FILE_NAME = "[^\\.]*\\.json$"; private static final String DOUBLE_LITERAL = "((\\+|-)?([0-9]+)(\\.[0-9]+)?)|((\\+|-)?\\.?[0-9]+)"; public static final String ENABLE_GUI = "-gui"; public static Options fromCommandLineArguments(String... arguments) { Options extracted = new Options(); for (String argument : arguments) { if (isJsonFile(argument)) { extracted.addDeploymentModel(argument); } else if (isDouble(argument)) { extracted.setReference(Double.parseDouble(argument)); } else if (isEnableGui(argument)) { extracted.setGuiEnabled(true); } else { throw new IllegalArgumentException("Unknown argument: " + argument); } } return extracted; } private static boolean isJsonFile(String argument) { return argument.matches(JSON_FILE_NAME); } private static boolean isDouble(String argument) { return argument.matches(DOUBLE_LITERAL); } private static boolean isEnableGui(String argument) { return argument.matches(ENABLE_GUI); } private boolean guiEnabled; private final List<String> deploymentModels; private double reference; public Options() { this.guiEnabled = false; this.deploymentModels = new ArrayList<String>(); this.reference = 0.75; } public boolean isGuiEnabled() { return guiEnabled; } public void setGuiEnabled(boolean guiEnabled) { this.guiEnabled = guiEnabled; } public double getReference() { return reference; } public void setReference(double setPoint) { this.reference = setPoint; } public List<String> getDeploymentModels() { return Collections.unmodifiableList(deploymentModels); } public void addDeploymentModel(String pathToModel) { this.deploymentModels.add(pathToModel); } public void launchDiversityController() { final CloudMLController controller = new CloudMLController(new TrueDiversity().normalise()); if (guiEnabled) { startGui(controller); } else { startCommandLine(controller); } } private void startGui(final CloudMLController controller) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { final Gui gui = new Gui(controller); gui.setReference(reference); gui.setFileToLoad(deploymentModels.get(0)); gui.setVisible(true); } }); } private void startCommandLine(final CloudMLController controller) { final CommandLine commandLine = new CommandLine(controller); for (String deployment : getDeploymentModels()) { commandLine.controlDiversity(deployment, reference); } } }
Java
using iTextSharp.text; namespace PdfRpt.VectorCharts { /// <summary> /// BarChartItem /// </summary> public class BarChartItem { /// <summary> /// BarChartItem /// </summary> public BarChartItem() { } /// <summary> /// BarChartItem /// </summary> /// <param name="value">Value of the chart's item.</param> /// <param name="label">Label of the item.</param> /// <param name="color">Color of the item.</param> public BarChartItem(double value, string label, BaseColor color) { Value = value; Label = label; Color = color; } /// <summary> /// BarChartItem /// </summary> /// <param name="value">Value of the chart's item.</param> /// <param name="label">Label of the item.</param> /// <param name="color">Color of the item.</param> public BarChartItem(double value, string label, System.Drawing.Color color) { Value = value; Label = label; Color = new BaseColor(color.ToArgb()); } /// <summary> /// Value of the chart's item. /// </summary> public double Value { set; get; } /// <summary> /// Label of the item. /// </summary> public string Label { set; get; } /// <summary> /// Color of the item. /// </summary> public BaseColor Color { set; get; } } }
Java
/** * */ package com.sirma.itt.emf.authentication.sso.saml.authenticator; import java.nio.charset.StandardCharsets; import java.util.Map; import javax.crypto.SecretKey; import javax.enterprise.inject.Instance; import javax.inject.Inject; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import com.sirma.itt.emf.authentication.sso.saml.SAMLMessageProcessor; import com.sirma.itt.seip.configuration.SystemConfiguration; import com.sirma.itt.seip.idp.config.IDPConfiguration; import com.sirma.itt.seip.plugin.Extension; import com.sirma.itt.seip.security.User; import com.sirma.itt.seip.security.authentication.AuthenticationContext; import com.sirma.itt.seip.security.authentication.Authenticator; import com.sirma.itt.seip.security.configuration.SecurityConfiguration; import com.sirma.itt.seip.security.context.SecurityContext; import com.sirma.itt.seip.security.util.SecurityUtil; import com.sirma.itt.seip.util.EqualsHelper; /** * Th SystemUserAuthenticator is responsible to login system users only using a generated token. * * @author bbanchev */ @Extension(target = Authenticator.NAME, order = 20) public class SystemUserAuthenticator extends BaseSamlAuthenticator { @Inject private Instance<SecurityConfiguration> securityConfiguration; @Inject private IDPConfiguration idpConfiguration; @Inject private SAMLMessageProcessor samlMessageProcessor; @Inject private SystemConfiguration systemConfiguration; @Override public User authenticate(AuthenticationContext authenticationContext) { return null; } @Override public Object authenticate(User toAuthenticate) { return authenticateById(toAuthenticate, toAuthenticate.getIdentityId()); } private Object authenticateById(User toAuthenticate, final String username) { if (StringUtils.isBlank(username)) { return null; } String userSimpleName = SecurityUtil.getUserWithoutTenant(username); if (isSystemUser(userSimpleName) || isSystemAdmin(userSimpleName)) { return authenticateWithTokenAndGetTicket(toAuthenticate, createToken(username, securityConfiguration.get().getCryptoKey().get())); } return null; } @SuppressWarnings("static-method") protected boolean isSystemAdmin(String userSimpleName) { return EqualsHelper.nullSafeEquals(SecurityContext.getSystemAdminName(), userSimpleName, true); } protected boolean isSystemUser(String userSimpleName) { return EqualsHelper.nullSafeEquals(userSimpleName, SecurityUtil.getUserWithoutTenant(SecurityContext.SYSTEM_USER_NAME), true); } @Override protected void completeAuthentication(User authenticated, SAMLTokenInfo info, Map<String, String> processedToken) { authenticated.getProperties().putAll(processedToken); } /** * Creates a token for given user. * * @param user * the user to create for * @param secretKey * is the encrypt key for saml token * @return the saml token */ protected byte[] createToken(String user, SecretKey secretKey) { return Base64.encodeBase64(SecurityUtil.encrypt( createResponse(systemConfiguration.getSystemAccessUrl().getOrFail().toString(), samlMessageProcessor.getIssuerId().get(), idpConfiguration.getIdpServerURL().get(), user), secretKey)); } /** * Creates the response for authentication in DMS. The time should be synchronized * * @param assertionUrl * the alfresco url * @param audianceUrl * the audiance url * @param samlURL * the saml url * @param user * the user to authenticate * @return the resulted saml2 message */ @SuppressWarnings("static-method") protected byte[] createResponse(String assertionUrl, String audianceUrl, String samlURL, String user) { DateTime now = new DateTime(DateTimeZone.UTC); DateTime barrier = now.plusMinutes(10); StringBuilder saml = new StringBuilder(2048); saml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") .append("<saml2p:Response ID=\"inppcpljfhhckioclinjenlcneknojmngnmgklab\" IssueInstant=\"").append(now) .append("\" Version=\"2.0\" xmlns:saml2p=\"urn:oasis:names:tc:SAML:2.0:protocol\">") .append("<saml2p:Status>") .append("<saml2p:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>") .append("</saml2p:Status>") .append("<saml2:Assertion ID=\"ehmifefpmmlichdcpeiogbgcmcbafafckfgnjfnk\" IssueInstant=\"").append(now) .append("\" Version=\"2.0\" xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\">") .append("<saml2:Issuer Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\">").append(samlURL) .append("</saml2:Issuer>").append("<saml2:Subject>").append("<saml2:NameID>").append(user) .append("</saml2:NameID>") .append("<saml2:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">") .append("<saml2:SubjectConfirmationData InResponseTo=\"0\" NotOnOrAfter=\"").append(barrier) .append("\" Recipient=\"").append(assertionUrl).append("\"/>").append("</saml2:SubjectConfirmation>") .append("</saml2:Subject>").append("<saml2:Conditions NotBefore=\"").append(now) .append("\" NotOnOrAfter=\"").append(barrier).append("\">").append("<saml2:AudienceRestriction>") .append("<saml2:Audience>").append(audianceUrl).append("</saml2:Audience>") .append("</saml2:AudienceRestriction>").append("</saml2:Conditions>") .append("<saml2:AuthnStatement AuthnInstant=\"").append(now).append("\">") .append("<saml2:AuthnContext>") .append("<saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml2:AuthnContextClassRef>") .append("</saml2:AuthnContext>").append("</saml2:AuthnStatement>").append("</saml2:Assertion>") .append("</saml2p:Response>"); return saml.toString().getBytes(StandardCharsets.UTF_8); } }
Java
#include <cstdio> #include <iostream> #include <vector> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; #define DEBUG #undef DEBUG //uncomment this line to pull out print statements #ifdef DEBUG #define TAB '\t' #define debug(a, end) cout << #a << ": " << a << end #else #define debug(a, end) #endif typedef pair<int, int> point; typedef long long int64; //for clarity typedef vector<int> vi; //? typedef vector<point> vp; //? template<class T> void chmin(T &t, T f) { if (t > f) t = f; } //change min template<class T> void chmax(T &t, T f) { if (t < f) t = f; } //change max #define UN(v) SORT(v),v.erase(unique(v.begin(),v.end()),v.end()) #define SORT(c) sort((c).begin(),(c).end()) #define FOR(i,a,b) for (int i=(a); i < (b); i++) #define REP(i,n) FOR(i,0,n) #define CL(a,b) memset(a,b,sizeof(a)) #define CL2d(a,b,x,y) memset(a, b, sizeof(a[0][0])*x*y) /*global variables*/ bool first_time = true; const double PI = acos(-1.0); int n; /*global variables*/ void dump() { //dump data } bool getInput() { //get input if (scanf("%d\n", &n) == EOF) return false; if (!first_time) printf("\n"); else first_time = false; return true; } bool in_circle(const point& x, double radius) { double y = (x.first*x.first + x.second*x.second); if (y < (radius*radius)) { debug(y, TAB); debug(radius, endl); } return y <= (radius*radius); } void process() { //process input //int t = (int)ceil(((2*n-1)*(2*n-1))/4*PI)/4; double r = (double)(2*n-1)/2; int in = 0, out = 0; point x; REP(i, n) { REP(j, n) { x.first = i; x.second = j; //top left if (in_circle(x, r)) { debug("contained segment", endl); out++; x.first = i+1; x.second = j+1; //bottom right if (in_circle(x, r)) { debug("fully in", endl); in++; out--; } } } } printf("In the case n = %d, %d cells contain segments of the circle.\n", n, out*4); printf("There are %d cells completely contained in the circle.\n", in*4); } int main() { while (getInput()) { process(); /*output*/ /*output*/ } return 0; }
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>BlueViaAndroidSDK: XmlDirectoryPersonalInfoParser Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body onload='searchBox.OnSelectItem(0);'> <!-- Generated by Doxygen 1.7.3 --> <script type="text/javascript"><!-- var searchBox = new SearchBox("searchBox", "search",false,'Search'); --></script> <div id="top"> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">BlueViaAndroidSDK&#160;<span id="projectnumber">1.6</span></div> </td> </tr> </tbody> </table> </div> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li id="searchli"> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> initNavTree('classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html',''); </script> <div id="doc-content"> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> </div> <div class="headertitle"> <h1>XmlDirectoryPersonalInfoParser Class Reference</h1> </div> </div> <div class="contents"> <!-- doxytag: class="com::bluevia::android::directory::parser::XmlDirectoryPersonalInfoParser" --><!-- doxytag: inherits="com::bluevia::android::directory::parser::DirectoryEntityParser" --><div class="dynheader"> Inheritance diagram for XmlDirectoryPersonalInfoParser:</div> <div class="dyncontent"> <div class="center"> <img src="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.png" usemap="#XmlDirectoryPersonalInfoParser_map" alt=""/> <map id="XmlDirectoryPersonalInfoParser_map" name="XmlDirectoryPersonalInfoParser_map"> <area href="interfacecom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1DirectoryEntityParser.html" alt="DirectoryEntityParser" shape="rect" coords="0,0,195,24"/> </map> </div></div> <p><a href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser-members.html">List of all members.</a></p> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1data_1_1PersonalInfo.html">PersonalInfo</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html#ac20d3cfdf717ba8e8c3b1060d58fa6bd">parse</a> (XmlPullParser parser) throws ParseException </td></tr> </table> <hr/><a name="_details"></a><h2>Detailed Description</h2> <div class="textblock"><p>Xml parser for <a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html">XmlDirectoryPersonalInfoParser</a> entities.</p> <dl class="author"><dt><b>Author:</b></dt><dd>Telefonica I+D </dd></dl> </div><hr/><h2>Member Function Documentation</h2> <a class="anchor" id="ac20d3cfdf717ba8e8c3b1060d58fa6bd"></a><!-- doxytag: member="com::bluevia::android::directory::parser::XmlDirectoryPersonalInfoParser::parse" ref="ac20d3cfdf717ba8e8c3b1060d58fa6bd" args="(XmlPullParser parser)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1data_1_1PersonalInfo.html">PersonalInfo</a> parse </td> <td>(</td> <td class="paramtype">XmlPullParser&#160;</td> <td class="paramname"><em>parser</em></td><td>)</td> <td> throws <a class="el" href="classcom_1_1bluevia_1_1android_1_1commons_1_1parser_1_1ParseException.html">ParseException</a> </td> </tr> </table> </div> <div class="memdoc"> <p>Parse the next entry on the parser </p> <dl><dt><b>Parameters:</b></dt><dd> <table class="params"> <tr><td class="paramname">parser</td><td>is the parser with the entity information </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>the <a class="el" href="interfacecom_1_1bluevia_1_1android_1_1commons_1_1Entity.html">Entity</a> object </dd></dl> <dl><dt><b>Exceptions:</b></dt><dd> <table class="exception"> <tr><td class="paramname">ParseException</td><td>when an error occurs converting the stream into an object </td></tr> <tr><td class="paramname">IOException</td><td>when an error reading the stream occurs </td></tr> </table> </dd> </dl> <p>Implements <a class="el" href="interfacecom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1DirectoryEntityParser.html#af20d62a0d03e9aa80d7520d6ea3b0280">DirectoryEntityParser</a>.</p> </div> </div> </div> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><b>com</b> </li> <li class="navelem"><b>bluevia</b> </li> <li class="navelem"><b>android</b> </li> <li class="navelem"><b>directory</b> </li> <li class="navelem"><b>parser</b> </li> <li class="navelem"><a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html">XmlDirectoryPersonalInfoParser</a> </li> <li class="footer">Generated on Fri May 11 2012 13:19:19 for BlueViaAndroidSDK by&#160; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </li> </ul> </div> <!--- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Enumerations</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </body> </html>
Java
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws 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 QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SQSPURGEQUEUERESPONSE_P_H #define SQSPURGEQUEUERESPONSE_P_H #include "sqsresponse_p.h" namespace QtAws { namespace SqsOld { class SqsPurgeQueueResponse; class SqsPurgeQueueResponsePrivate : public SqsResponsePrivate { public: QString queueUrl; ///< Created queue URL. SqsPurgeQueueResponsePrivate(SqsPurgeQueueResponse * const q); void parsePurgeQueueResponse(QXmlStreamReader &xml); private: Q_DECLARE_PUBLIC(SqsPurgeQueueResponse) Q_DISABLE_COPY(SqsPurgeQueueResponsePrivate) }; } // namespace SqsOld } // namespace QtAws #endif
Java
class WeavingType < ActiveRecord::Base acts_as_content_block :belongs_to_attachment => true has_many :weavings belongs_to :user validates_presence_of :name validates_uniqueness_of :name end
Java
/** * DynamicReports - Free Java reporting library for creating reports dynamically * * Copyright (C) 2010 - 2012 Ricardo Mariaca * http://dynamicreports.sourceforge.net * * This file is part of DynamicReports. * * DynamicReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.dynamicreports.examples.complex.applicationform; /** * @author Ricardo Mariaca (dynamicreports@gmail.com) */ public enum MaritalStatus { SINGLE, MARRIED, DIVORCED }
Java
<?php if (file_exists('../libcompactmvc.php')) include_once ('../libcompactmvc.php'); LIBCOMPACTMVC_ENTRY; /** * Mutex * * @author Botho Hohbaum <bhohbaum@googlemail.com> * @package LibCompactMVC * @copyright Copyright (c) Botho Hohbaum * @license BSD License (see LICENSE file in root directory) * @link https://github.com/bhohbaum/LibCompactMVC */ class Mutex { private $key; private $token; private $delay; private $maxwait; public function __construct($key) { $this->key = $key; $this->token = md5(microtime() . rand(0, 99999999)); $this->delay = 2; $this->register(); } public function __destruct() { $this->unregister(); } public function lock($maxwait = 60) { echo ("Lock\n"); $start = time(); $this->maxwait = $maxwait; while (time() < $start + $maxwait) { if (count($this->get_requests()) == 0) { $this->set_request(); // usleep($this->delay * 5000); if (count($this->get_requests()) == 1) { if (count($this->get_acks()) + 1 == count($this->get_registrations())) { return; } } } if (count($this->get_requests()) == 1) { if (!$this->is_ack_set() && !$this->is_request_set()) { $this->set_ack(); } } if (count($this->get_requests()) > 1) { echo ("Increasing delay: " . $this->delay . "\n"); $this->delay += 1; } $this->unlock(); usleep(rand(0, $this->delay * 500)); } throw new MutexException("max wait time elapsed", 500); } public function unlock() { echo ("UnLock\n"); foreach ($this->get_acks() as $ack) { echo ("Deleting " . $ack . "\n"); RedisAdapter::get_instance()->delete($ack, false); } foreach ($this->get_requests() as $request) { echo ("Deleting " . $request . "\n"); RedisAdapter::get_instance()->delete($request, false); } } private function register() { echo ("Registering " . REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token, 1, false); RedisAdapter::get_instance()->expire(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $elem->token, $this->maxwait); } private function unregister() { echo ("Unregistering " . REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token, false); } private function get_registrations() { return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_*", false); } private function set_request() { echo ("Setting request " . REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false); } private function del_request() { echo ("Deleting request " . REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false); } private function get_requests() { return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_*", false); } private function is_request_set() { return (RedisAdapter::get_instance()->get(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false) != null); } private function set_ack() { echo ("Set ACK " . REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false); } private function del_ack() { echo ("Del ACK " . REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false); } private function get_acks() { return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_*", false); } private function is_ack_set() { return (RedisAdapter::get_instance()->get(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false) != null); } }
Java
if (WIN32) if (MSVC71) set (COMPILER_SUFFIX "vc71") set (COMPILER_SUFFIX_VERSION "71") endif(MSVC71) if (MSVC80) set (COMPILER_SUFFIX "vc80") set (COMPILER_SUFFIX_VERSION "80") endif(MSVC80) if (MSVC90) set (COMPILER_SUFFIX "vc90") set (COMPILER_SUFFIX_VERSION "90") endif(MSVC90) if (MSVC10) set (COMPILER_SUFFIX "vc100") set (COMPILER_SUFFIX_VERSION "100") endif(MSVC10) if (MSVC11) set (COMPILER_SUFFIX "vc110") set (COMPILER_SUFFIX_VERSION "110") endif(MSVC11) if (MSVC12) set (COMPILER_SUFFIX "vc120") set (COMPILER_SUFFIX_VERSION "120") endif(MSVC12) if (MSVC14) set (COMPILER_SUFFIX "vc141") set (COMPILER_SUFFIX_VERSION "141") endif(MSVC14) if (MSVC15) set (COMPILER_SUFFIX "vc141") set (COMPILER_SUFFIX_VERSION "141") endif(MSVC15) endif (WIN32) if (UNIX) if (CMAKE_COMPILER_IS_GNUCXX) #find out the version of gcc being used. exec_program(${CMAKE_CXX_COMPILER} ARGS --version OUTPUT_VARIABLE _COMPILER_VERSION ) string(REGEX REPLACE ".* ([0-9])\\.([0-9])\\.[0-9].*" "\\1\\2" _COMPILER_VERSION ${_COMPILER_VERSION}) set (COMPILER_SUFFIX "gcc${_COMPILER_VERSION}") #set (COMPILER_SUFFIX "") endif (CMAKE_COMPILER_IS_GNUCXX) endif(UNIX) if (COMPILER_SUFFIX STREQUAL "") message(FATAL_ERROR "schism_compiler.cmake: unable to identify supported compiler") else (COMPILER_SUFFIX STREQUAL "") set(COMPILER_SUFFIX ${COMPILER_SUFFIX} CACHE STRING "The boost style compiler suffix") endif (COMPILER_SUFFIX STREQUAL "")
Java
{-| Module : Main-nowx Description : Модуль с точкой входа для консольной версии приложения License : LGPLv3 -} module Main where import Kernel import PlayerConsole import DrawingConsole import Controller import AIPlayer -- | Точка входа для консольной версии программы main :: IO () main = do winner <- run cfg player1 player2 [drawing] case winner of Winner color -> putStrLn $ (show color) ++ " player wins!" DrawBy color -> putStrLn $ "It's a trap for " ++ (show color) ++ " player!" return () where cfg = russianConfig game = createGame cfg player1 = createAIPlayer 1 2 player2 = createPlayerConsole drawing = createDrawingConsole
Java
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Copyright (c) 2015-2020 The plumed team (see the PEOPLE file at the root of the distribution for a list of names) See http://www.plumed.org for more information. This file is part of plumed, version 2. plumed is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. plumed 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 plumed. If not, see <http://www.gnu.org/licenses/>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #include "core/ActionAtomistic.h" #include "core/ActionPilot.h" #include "core/ActionRegister.h" #include "tools/File.h" #include "core/PlumedMain.h" #include "core/Atoms.h" namespace PLMD { namespace generic { //+PLUMEDOC PRINTANALYSIS DUMPMASSCHARGE /* Dump masses and charges on a selected file. This command dumps a file containing charges and masses. It does so only once in the simulation (at first step). File can be recycled in the \ref driver tool. Notice that masses and charges are only written once at the beginning of the simulation. In case no atom list is provided, charges and masses for all atoms are written. \par Examples You can add the DUMPMASSCHARGE action at the end of the plumed.dat file that you use during an MD simulations: \plumedfile c1: COM ATOMS=1-10 c2: COM ATOMS=11-20 DUMPATOMS ATOMS=c1,c2 FILE=coms.xyz STRIDE=100 DUMPMASSCHARGE FILE=mcfile \endplumedfile In this way, you will be able to use the same masses while processing a trajectory from the \ref driver . To do so, you need to add the --mc flag on the driver command line, e.g. \verbatim plumed driver --mc mcfile --plumed plumed.dat --ixyz traj.xyz \endverbatim With the following input you can dump only the charges for a specific group. \plumedfile solute_ions: GROUP ATOMS=1-121,200-2012 DUMPATOMS FILE=traj.gro ATOMS=solute_ions STRIDE=100 DUMPMASSCHARGE FILE=mcfile ATOMS=solute_ions \endplumedfile Notice however that if you want to process the charges with the driver (e.g. reading traj.gro) you have to fix atom numbers first, e.g. with the script \verbatim awk 'BEGIN{c=0}{ if(match($0,"#")) print ; else {print c,$2,$3; c++} }' < mc > newmc }' \endverbatim then \verbatim plumed driver --mc newmc --plumed plumed.dat --ixyz traj.gro \endverbatim */ //+ENDPLUMEDOC class DumpMassCharge: public ActionAtomistic, public ActionPilot { std::string file; bool first; bool second; bool print_masses; bool print_charges; public: explicit DumpMassCharge(const ActionOptions&); ~DumpMassCharge(); static void registerKeywords( Keywords& keys ); void prepare() override; void calculate() override {} void apply() override {} void update() override; }; PLUMED_REGISTER_ACTION(DumpMassCharge,"DUMPMASSCHARGE") void DumpMassCharge::registerKeywords( Keywords& keys ) { Action::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); ActionAtomistic::registerKeywords( keys ); keys.add("compulsory","STRIDE","1","the frequency with which the atoms should be output"); keys.add("atoms", "ATOMS", "the atom indices whose charges and masses you would like to print out"); keys.add("compulsory", "FILE", "file on which to output charges and masses."); keys.addFlag("ONLY_MASSES",false,"Only output masses to file"); keys.addFlag("ONLY_CHARGES",false,"Only output charges to file"); } DumpMassCharge::DumpMassCharge(const ActionOptions&ao): Action(ao), ActionAtomistic(ao), ActionPilot(ao), first(true), second(true), print_masses(true), print_charges(true) { std::vector<AtomNumber> atoms; parse("FILE",file); if(file.length()==0) error("name of output file was not specified"); log.printf(" output written to file %s\n",file.c_str()); parseAtomList("ATOMS",atoms); if(atoms.size()==0) { for(int i=0; i<plumed.getAtoms().getNatoms(); i++) { atoms.push_back(AtomNumber::index(i)); } } bool only_masses = false; parseFlag("ONLY_MASSES",only_masses); if(only_masses) { print_charges = false; log.printf(" only masses will be written to file\n"); } bool only_charges = false; parseFlag("ONLY_CHARGES",only_charges); if(only_charges) { print_masses = false; log.printf(" only charges will be written to file\n"); } checkRead(); log.printf(" printing the following atoms:" ); for(unsigned i=0; i<atoms.size(); ++i) log.printf(" %d",atoms[i].serial() ); log.printf("\n"); requestAtoms(atoms); if(only_masses && only_charges) { plumed_merror("using both ONLY_MASSES and ONLY_CHARGES doesn't make sense"); } } void DumpMassCharge::prepare() { if(!first && second) { requestAtoms(std::vector<AtomNumber>()); second=false; } } void DumpMassCharge::update() { if(!first) return; first=false; OFile of; of.link(*this); of.open(file); for(unsigned i=0; i<getNumberOfAtoms(); i++) { int ii=getAbsoluteIndex(i).index(); of.printField("index",ii); if(print_masses) {of.printField("mass",getMass(i));} if(print_charges) {of.printField("charge",getCharge(i));} of.printField(); } } DumpMassCharge::~DumpMassCharge() { } } }
Java
" Settings for tests. " from settings.project import * # Databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'TEST_CHARSET': 'utf8', }} # Caches CACHES['default']['BACKEND'] = 'django.core.cache.backends.locmem.LocMemCache' CACHES['default']['KEY_PREFIX'] = '_'.join((PROJECT_NAME, 'TST')) # pymode:lint_ignore=W404
Java
// // Copyright 2012 Josh Blum // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU 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 <http://www.gnu.org/licenses/>. #ifndef INCLUDED_LIBTSBE_ELEMENT_IMPL_HPP #define INCLUDED_LIBTSBE_ELEMENT_IMPL_HPP #include <tsbe/thread_pool.hpp> #include <tsbe_impl/common_impl.hpp> #include <vector> #include <queue> #include <iostream> namespace tsbe { //! ElementImpl is both a topology and a block to allow interconnection struct ElementImpl { ElementImpl(void) { //NOP } ~ElementImpl(void) { this->actor.reset(); } bool block; bool is_block(void) { return block; } boost::shared_ptr<Actor> actor; boost::shared_ptr<Theron::Framework> framework; ThreadPool thread_pool; }; } //namespace tsbe #endif /*INCLUDED_LIBTSBE_ELEMENT_IMPL_HPP*/
Java
package org.molgenis.lifelines.catalog; import nl.umcg.hl7.service.studydefinition.POQMMT000002UVObservation; import org.molgenis.omx.catalogmanager.OmxCatalogFolder; import org.molgenis.omx.observ.Protocol; public class PoqmObservationCatalogItem extends OmxCatalogFolder { private final POQMMT000002UVObservation observation; public PoqmObservationCatalogItem(POQMMT000002UVObservation observation, Protocol protocol) { super(protocol); if (observation == null) throw new IllegalArgumentException("observation is null"); this.observation = observation; } @Override public String getName() { return observation.getCode().getDisplayName(); } @Override public String getDescription() { return observation.getCode().getOriginalText().getContent().toString(); } @Override public String getCode() { return observation.getCode().getCode(); } @Override public String getCodeSystem() { return observation.getCode().getCodeSystem(); } }
Java
/* * SonarQube Lua Plugin * Copyright (C) 2016 * mailto:fati.ahmadi AT gmail DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.lua.checks; import org.junit.Test; import org.sonar.lua.LuaAstScanner; import org.sonar.squidbridge.api.SourceFile; import org.sonar.squidbridge.checks.CheckMessagesVerifier; import org.sonar.squidbridge.api.SourceFunction; import java.io.File; public class TableComplexityCheckTest { @Test public void test() { TableComplexityCheck check = new TableComplexityCheck(); check.setMaximumTableComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/tableComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("Table has a complexity of 1 which is greater than 0 authorized.") .noMore(); } }
Java
/* * partition.h -- a disjoint set of pairwise equivalent items * * Copyright (c) 2007-2010, Dmitry Prokoptsev <dprokoptsev@gmail.com>, * Alexander Gololobov <agololobov@gmail.com> * * This file is part of Pire, the Perl Incompatible * Regular Expressions library. * * Pire is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pire 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 Public License for more details. * You should have received a copy of the GNU Lesser Public License * along with Pire. If not, see <http://www.gnu.org/licenses>. */ #ifndef PIRE_PARTITION_H #define PIRE_PARTITION_H #include "stub/stl.h" #include "stub/singleton.h" namespace Pire { /* * A class which forms a disjoint set of pairwise equivalent items, * depending on given equivalence relation. */ template<class T, class Eq> class Partition { private: typedef ymap< T, ypair< size_t, yvector<T> > > Set; public: Partition(const Eq& eq) : m_eq(eq) , m_maxidx(0) { } /// Appends a new item into partition, creating new equivalience class if neccessary. void Append(const T& t) { DoAppend(m_set, t); } typedef typename Set::const_iterator ConstIterator; ConstIterator Begin() const { return m_set.begin(); } ConstIterator End() const { return m_set.end(); } size_t Size() const { return m_set.size(); } bool Empty() const { return m_set.empty(); } /// Returns an item equal to @p t. It is guaranteed that: /// - representative(a) equals representative(b) iff a is equivalent to b; /// - representative(a) is equivalent to a. const T& Representative(const T& t) const { typename ymap<T, T>::const_iterator it = m_inv.find(t); if (it != m_inv.end()) return it->second; else return DefaultValue<T>(); } bool Contains(const T& t) const { return m_inv.find(t) != m_inv.end(); } /// Returns an index of set containing @p t. It is guaranteed that: /// - index(a) equals index(b) iff a is equivalent to b; /// - 0 <= index(a) < size(). size_t Index(const T& t) const { typename ymap<T, T>::const_iterator it = m_inv.find(t); if (it == m_inv.end()) throw Error("Partition::index(): attempted to obtain an index of nonexistent item"); typename Set::const_iterator it2 = m_set.find(it->second); YASSERT(it2 != m_set.end()); return it2->second.first; } /// Returns the whole equivalence class of @p t (i.e. item @p i /// is returned iff representative(i) == representative(t)). const yvector<T>& Klass(const T& t) const { typename ymap<T, T>::const_iterator it = m_inv.find(t); if (it == m_inv.end()) throw Error("Partition::index(): attempted to obtain an index of nonexistent item"); ConstIterator it2 = m_set.find(it->second); YASSERT(it2 != m_set.end()); return it2->second.second; } bool operator == (const Partition& rhs) const { return m_set == rhs.m_set; } bool operator != (const Partition& rhs) const { return !(*this == rhs); } /// Splits the current sets into smaller ones, using given equivalence relation. /// Requires given relation imply previous one (set either in ctor or /// in preceeding calls to split()), but performs faster. /// Replaces previous relation with given one. void Split(const Eq& eq) { m_eq = eq; for (typename Set::iterator sit = m_set.begin(), sie = m_set.end(); sit != sie; ++sit) if (sit->second.second.size() > 1) { yvector<T>& v = sit->second.second; typename yvector<T>::iterator bound = std::partition(v.begin(), v.end(), std::bind2nd(m_eq, v[0])); if (bound == v.end()) continue; Set delta; for (typename yvector<T>::iterator it = bound, ie = v.end(); it != ie; ++it) DoAppend(delta, *it); v.erase(bound, v.end()); m_set.insert(delta.begin(), delta.end()); } } private: Eq m_eq; Set m_set; ymap<T, T> m_inv; size_t m_maxidx; void DoAppend(Set& set, const T& t) { typename Set::iterator it = set.begin(); typename Set::iterator end = set.end(); for (; it != end; ++it) if (m_eq(it->first, t)) { it->second.second.push_back(t); m_inv[t] = it->first; break; } if (it == end) { // Begin new set yvector<T> v(1, t); set.insert(ymake_pair(t, ymake_pair(m_maxidx++, v))); m_inv[t] = t; } } }; // Mainly for debugging template<class T, class Eq> yostream& operator << (yostream& stream, const Partition<T, Eq>& partition) { stream << "Partition {\n"; for (typename Partition<T, Eq>::ConstIterator it = partition.Begin(), ie = partition.End(); it != ie; ++it) { stream << " Class " << it->second.first << " \"" << it->first << "\" { "; bool first = false; for (typename yvector<T>::const_iterator iit = it->second.second.begin(), iie = it->second.second.end(); iit != iie; ++iit) { if (first) stream << ", "; else first = true; stream << *iit; } stream << " }\n"; } stream << "}"; return stream; } } #endif
Java
SUBROUTINE SGETF2( M, N, A, LDA, IPIV, INFO ) * * -- LAPACK routine (version 3.0) -- * Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., * Courant Institute, Argonne National Lab, and Rice University * June 30, 1992 * * .. Scalar Arguments .. INTEGER INFO, LDA, M, N * .. * .. Array Arguments .. INTEGER IPIV( * ) REAL A( LDA, * ) * .. * * Purpose * ======= * * SGETF2 computes an LU factorization of a general m-by-n matrix A * using partial pivoting with row interchanges. * * The factorization has the form * A = P * L * U * where P is a permutation matrix, L is lower triangular with unit * diagonal elements (lower trapezoidal if m > n), and U is upper * triangular (upper trapezoidal if m < n). * * This is the right-looking Level 2 BLAS version of the algorithm. * * Arguments * ========= * * M (input) INTEGER * The number of rows of the matrix A. M >= 0. * * N (input) INTEGER * The number of columns of the matrix A. N >= 0. * * A (input/output) REAL array, dimension (LDA,N) * On entry, the m by n matrix to be factored. * On exit, the factors L and U from the factorization * A = P*L*U; the unit diagonal elements of L are not stored. * * LDA (input) INTEGER * The leading dimension of the array A. LDA >= max(1,M). * * IPIV (output) INTEGER array, dimension (min(M,N)) * The pivot indices; for 1 <= i <= min(M,N), row i of the * matrix was interchanged with row IPIV(i). * * INFO (output) INTEGER * = 0: successful exit * < 0: if INFO = -k, the k-th argument had an illegal value * > 0: if INFO = k, U(k,k) is exactly zero. The factorization * has been completed, but the factor U is exactly * singular, and division by zero will occur if it is used * to solve a system of equations. * * ===================================================================== * * .. Parameters .. REAL ONE, ZERO PARAMETER ( ONE = 1.0E+0, ZERO = 0.0E+0 ) * .. * .. Local Scalars .. INTEGER J, JP * .. * .. External Functions .. INTEGER ISAMAX EXTERNAL ISAMAX * .. * .. External Subroutines .. EXTERNAL SGER, SSCAL, SSWAP, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX, MIN * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 IF( M.LT.0 ) THEN INFO = -1 ELSE IF( N.LT.0 ) THEN INFO = -2 ELSE IF( LDA.LT.MAX( 1, M ) ) THEN INFO = -4 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'SGETF2', -INFO ) RETURN END IF * * Quick return if possible * IF( M.EQ.0 .OR. N.EQ.0 ) $ RETURN * DO 10 J = 1, MIN( M, N ) * * Find pivot and test for singularity. * JP = J - 1 + ISAMAX( M-J+1, A( J, J ), 1 ) IPIV( J ) = JP IF( A( JP, J ).NE.ZERO ) THEN * * Apply the interchange to columns 1:N. * IF( JP.NE.J ) $ CALL SSWAP( N, A( J, 1 ), LDA, A( JP, 1 ), LDA ) * * Compute elements J+1:M of J-th column. * IF( J.LT.M ) $ CALL SSCAL( M-J, ONE / A( J, J ), A( J+1, J ), 1 ) * ELSE IF( INFO.EQ.0 ) THEN * INFO = J END IF * IF( J.LT.MIN( M, N ) ) THEN * * Update trailing submatrix. * CALL SGER( M-J, N-J, -ONE, A( J+1, J ), 1, A( J, J+1 ), LDA, $ A( J+1, J+1 ), LDA ) END IF 10 CONTINUE RETURN * * End of SGETF2 * END
Java
#!/usr/bin/python # -*- coding: utf-8 -*- "Visual Property Editor (using wx PropertyGrid) of gui2py's components" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2013- Mariano Reingart" __license__ = "LGPL 3.0" # some parts where inspired or borrowed from wxFormBuilders & wxPython examples import sys, time, math, os, os.path import wx _ = wx.GetTranslation import wx.propgrid as wxpg from gui.component import InitSpec, StyleSpec, Spec, EventSpec, DimensionSpec from gui.font import Font DEBUG = False class PropertyEditorPanel(wx.Panel): def __init__( self, parent, log ): wx.Panel.__init__(self, parent, wx.ID_ANY) self.log = log self.callback = None self.panel = panel = wx.Panel(self, wx.ID_ANY) topsizer = wx.BoxSizer(wx.VERTICAL) # Difference between using PropertyGridManager vs PropertyGrid is that # the manager supports multiple pages and a description box. self.pg = pg = wxpg.PropertyGrid(panel, style=wxpg.PG_SPLITTER_AUTO_CENTER | wxpg.PG_AUTO_SORT | wxpg.PG_TOOLBAR) # Show help as tooltips pg.SetExtraStyle(wxpg.PG_EX_HELP_AS_TOOLTIPS) pg.Bind( wxpg.EVT_PG_CHANGED, self.OnPropGridChange ) pg.Bind( wxpg.EVT_PG_PAGE_CHANGED, self.OnPropGridPageChange ) pg.Bind( wxpg.EVT_PG_SELECTED, self.OnPropGridSelect ) pg.Bind( wxpg.EVT_PG_RIGHT_CLICK, self.OnPropGridRightClick ) ##pg.AddPage( "Page 1 - Testing All" ) # store the property grid for future reference self.pg = pg # load empty object (just draws categories) self.load_object(None) # sizing stuff: topsizer.Add(pg, 1, wx.EXPAND) panel.SetSizer(topsizer) topsizer.SetSizeHints(panel) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(panel, 1, wx.EXPAND) self.SetSizer(sizer) self.SetAutoLayout(True) def load_object(self, obj, callback=None): pg = self.pg # get the property grid reference self.callback = callback # store the update method # delete all properties pg.Clear() # clean references and aux structures appended = set() self.obj = obj self.groups = {} # loop on specs and append each property (categorized): for i, cat, class_ in ((1, 'Init Specs', InitSpec), (2, 'Dimension Specs', DimensionSpec), (3, 'Style Specs', StyleSpec), (5, 'Events', EventSpec), (4, 'Basic Specs', Spec), ): pg.Append(wxpg.PropertyCategory("%s - %s" % (i, cat))) if obj is None: continue specs = sorted(obj._meta.specs.items(), key=lambda it: it[0]) for name, spec in specs: if DEBUG: print "setting prop", spec, class_, spec.type if isinstance(spec, class_): prop = {'string': wxpg.StringProperty, 'integer': wxpg.IntProperty, 'float': wxpg.FloatProperty, 'boolean': wxpg.BoolProperty, 'text': wxpg.LongStringProperty, 'code': wxpg.LongStringProperty, 'enum': wxpg.EnumProperty, 'edit_enum': wxpg.EditEnumProperty, 'expr': wxpg.StringProperty, 'array': wxpg.ArrayStringProperty, 'font': wxpg.FontProperty, 'image_file': wxpg.ImageFileProperty, 'colour': wxpg.ColourProperty}.get(spec.type) if prop and name not in appended: value = getattr(obj, name) if DEBUG: print "name", name, value if spec.type == "code" and value is None: value = "" if spec.type == "boolean" and value is None: value = False if spec.type == "integer" and value is None: value = -1 if spec.type in ("string", "text") and value is None: value = "" if spec.type == "expr": value = repr(value) if spec.type == "font": if value is None: value = wx.NullFont else: value = value.get_wx_font() if callable(value): # event binded at runtime cannot be modified: value = str(value) readonly = True else: readonly = False if spec.type == "enum": prop = prop(name, name, spec.mapping.keys(), spec.mapping.values(), value=spec.mapping.get(value, 0)) elif spec.type == "edit_enum": prop = prop(name, name, spec.mapping.keys(), range(len(spec.mapping.values())), value=spec.mapping[value]) else: try: prop = prop(name, value=value) except Exception, e: print "CANNOT LOAD PROPERTY", name, value, e prop.SetPyClientData(spec) appended.add(name) if spec.group is None: pg.Append(prop) if readonly: pg.SetPropertyReadOnly(prop) else: # create a group hierachy (wxpg uses dot notation) group = "" prop_parent = None for grp in spec.group.split("."): prev_group = group # ancestor group += ("." if group else "") + grp # path if group in self.groups: prop_parent = self.groups[group] else: prop_group = wxpg.StringProperty(grp, value="<composed>") if not prop_parent: pg.Append(prop_group) else: pg.AppendIn(prev_group, prop_group) prop_parent = prop_group self.groups[group] = prop_parent pg.SetPropertyReadOnly(group) pg.AppendIn(spec.group, prop) pg.Collapse(spec.group) name = spec.group + "." + name if spec.type == "boolean": pg.SetPropertyAttribute(name, "UseCheckbox", True) doc = spec.__doc__ if doc: pg.SetPropertyHelpString(name, doc) def edit(self, name=""): "Programatically select a (default) property to start editing it" # for more info see DoSelectAndEdit in propgrid.cpp for name in (name, "label", "value", "text", "title", "filename", "name"): prop = self.pg.GetPropertyByName(name) if prop is not None: break self.Parent.SetFocus() self.Parent.Raise() self.pg.SetFocus() # give time to the ui to show the prop grid and set focus: wx.CallLater(250, self.select, prop.GetName()) def select(self, name, flags=0): "Select a property (and start the editor)" # do not call this directly from another window, use edit() instead # // wxPropertyGrid::DoSelectProperty flags (selFlags) -see propgrid.h- wxPG_SEL_FOCUS=0x0001 # Focuses to created editor wxPG_SEL_FORCE=0x0002 # Forces deletion and recreation of editor flags |= wxPG_SEL_FOCUS # | wxPG_SEL_FORCE prop = self.pg.GetPropertyByName(name) self.pg.SelectProperty(prop, flags) if DEBUG: print "selected!", prop def OnPropGridChange(self, event): p = event.GetProperty() if DEBUG: print "change!", p if p: name = p.GetName() spec = p.GetPyClientData() if spec and 'enum' in spec.type: value = p.GetValueAsString() else: value = p.GetValue() #self.log.write(u'%s changed to "%s"\n' % (p,p.GetValueAsString())) # if it a property child (parent.child), extract its name if "." in name: name = name[name.rindex(".") + 1:] if spec and not name in self.groups: if name == 'font': # TODO: detect property type # create a gui font from the wx.Font font = Font() font.set_wx_font(value) value = font # expressions must be evaluated to store the python object if spec.type == "expr": value = eval(value) # re-create the wx_object with the new property value # (this is required at least to apply new styles and init specs) if DEBUG: print "changed", self.obj.name kwargs = {str(name): value} wx.CallAfter(self.obj.rebuild, **kwargs) if name == 'name': wx.CallAfter(self.callback, **dict(name=self.obj.name)) def OnPropGridSelect(self, event): p = event.GetProperty() if p: self.log.write(u'%s selected\n' % (event.GetProperty().GetName())) else: self.log.write(u'Nothing selected\n') def OnDeleteProperty(self, event): p = self.pg.GetSelectedProperty() if p: self.pg.DeleteProperty(p) else: wx.MessageBox("First select a property to delete") def OnReserved(self, event): pass def OnPropGridRightClick(self, event): p = event.GetProperty() if p: self.log.write(u'%s right clicked\n' % (event.GetProperty().GetName())) else: self.log.write(u'Nothing right clicked\n') #self.obj.get_parent().Refresh() def OnPropGridPageChange(self, event): index = self.pg.GetSelectedPage() self.log.write('Page Changed to \'%s\'\n' % (self.pg.GetPageName(index))) if __name__ == '__main__': import sys,os app = wx.App() f = wx.Frame(None) from gui.controls import Button, Label, TextBox, CheckBox, ListBox, ComboBox frame = wx.Frame(None) #o = Button(frame, name="btnTest", label="click me!", default=True) #o = Label(frame, name="lblTest", alignment="right", size=(-1, 500), text="hello!") o = TextBox(frame, name="txtTest", border=False, text="hello world!") #o = CheckBox(frame, name="chkTest", border='none', label="Check me!") #o = ListBox(frame, name="lstTest", border='none', # items={'datum1': 'a', 'datum2':'b', 'datum3':'c'}, # multiselect="--multiselect" in sys.argv) #o = ComboBox(frame, name="cboTest", # items={'datum1': 'a', 'datum2':'b', 'datum3':'c'}, # readonly='--readonly' in sys.argv, # ) frame.Show() log = sys.stdout w = PropertyEditorPanel(f, log) w.load_object(o) f.Show() app.MainLoop()
Java
#!/usr/bin/python3 import sys from pathlib import Path list_scope_path = Path("./list_scope_tokens.txt") keyword_bit = 13 list_scope_bit = 14 def main(): if len(sys.argv) < 2: print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr) return 1 list_scopes = set() with list_scope_path.open('r') as f: for line in f: line = line.strip() if line.startswith('#') or len(line) == 0: continue list_scopes.add(line) max_kw_len = max( len(kw) for kw in list_scopes ) if sys.argv[1] == 'tokens': t_id = (1 << (keyword_bit - 1)) | (1 << (list_scope_bit-1)) for t in sorted(list_scopes): print(' {:<{width}} = 0x{:4X};'.format(t.upper(), t_id, width=max_kw_len)) t_id += 1 elif sys.argv[1] == 'emitters': for t in sorted(list_scopes): print(' {:<{width}} => T_{}(Lexeme);'.format('"' + t + '"', t.upper(), width = max_kw_len + 2)) else: print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr) return 1 return 0 if __name__ == '__main__': sys.exit(main())
Java
package com.faralot.core.ui.fragments; import android.app.Activity; import android.app.AlertDialog.Builder; import android.app.Fragment; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.provider.MediaStore.Images.Media; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import com.faralot.core.App; import com.faralot.core.R; import com.faralot.core.R.drawable; import com.faralot.core.R.id; import com.faralot.core.R.layout; import com.faralot.core.R.string; import com.faralot.core.lib.LocalizationSystem; import com.faralot.core.lib.LocalizationSystem.Listener; import com.faralot.core.rest.model.Location; import com.faralot.core.rest.model.location.Coord; import com.faralot.core.ui.holder.LocalizationHolder; import com.faralot.core.utils.Dimension; import com.faralot.core.utils.Localization; import com.faralot.core.utils.Util; import com.orhanobut.dialogplus.DialogPlus; import com.orhanobut.dialogplus.OnItemClickListener; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.RequestBody; import org.osmdroid.bonuspack.overlays.InfoWindow; import org.osmdroid.bonuspack.overlays.MapEventsOverlay; import org.osmdroid.bonuspack.overlays.MapEventsReceiver; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.ItemizedIconOverlay; import org.osmdroid.views.overlay.OverlayItem; import java.io.File; import java.util.ArrayList; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; public class LocationAddSelectFragment extends Fragment { protected MapView mapView; protected TextView latitude; protected ProgressBar latitudeProgress; protected TextView longitude; protected ProgressBar longitudeProgress; protected ImageButton submit; private boolean forceZoom; public LocationAddSelectFragment() { } @Override public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(layout.fragment_location_add_select, container, false); initElements(view); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(getString(string.find_coordinates)); } onChoose(); return view; } private void initElements(View view) { mapView = (MapView) view.findViewById(id.map); latitude = (TextView) view.findViewById(id.result_lat); latitudeProgress = (ProgressBar) view.findViewById(id.progress_latitude); longitude = (TextView) view.findViewById(id.result_lon); longitudeProgress = (ProgressBar) view.findViewById(id.progress_longitude); Button back = (Button) view.findViewById(id.back); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearResultLayout(); onChoose(); onChoose(); } }); submit = (ImageButton) view.findViewById(id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onSubmit(); } }); } private void generateContent(float lat, float lon) { GeoPoint actPosition = new GeoPoint((double) lat, (double) lon); Util.setMapViewSettings(mapView, actPosition, forceZoom); ArrayList<OverlayItem> locations = new ArrayList<>(1); OverlayItem actPositionItem = new OverlayItem(getString(string.here), getString(string.my_position), actPosition); actPositionItem.setMarker(Util.resizeDrawable(getResources() .getDrawable(drawable.ic_marker_dark), getResources(), new Dimension(45, 45))); locations.add(actPositionItem); // Bonuspack MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(getActivity(), new MapEventsReceiver() { @Override public boolean singleTapConfirmedHelper(GeoPoint geoPoint) { InfoWindow.closeAllInfoWindowsOn(mapView); return true; } @Override public boolean longPressHelper(GeoPoint geoPoint) { InfoWindow.closeAllInfoWindowsOn(mapView); setResultLayout((float) geoPoint.getLatitude(), (float) geoPoint .getLongitude()); return true; } }); mapView.getOverlays().add(0, mapEventsOverlay); mapView.getOverlays().add(new ItemizedIconOverlay<>(getActivity(), locations, null)); } protected final void onChoose() { clearResultLayout(); forceZoom = true; ArrayList<Localization> localizations = new ArrayList<>(4); localizations.add(new Localization(drawable.ic_gps_dark, getString(string.gps_coordinates), Localization.GPS)); localizations.add(new Localization(drawable.ic_camera_dark, getString(string.coord_photo_exif), Localization.PIC_COORD)); localizations.add(new Localization(drawable.ic_manual_dark, getString(string.add_manual), Localization.MANUAL)); if (App.palsActive) { localizations.add(new Localization(drawable.ic_pals_dark, getString(string.pals_provider), Localization.PALS)); } DialogPlus dialog = DialogPlus.newDialog(getActivity()) .setAdapter(new LocalizationHolder(getActivity(), localizations)) .setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(DialogPlus dialog, Object item, View view, int position) { Listener listener = new Listener() { @Override public void onComplete(Coord coord, boolean valid) { if (valid) { setResultLayout(coord.getLatitude(), coord.getLongitude()); } } }; dialog.dismiss(); if (position == 0) { App.localization.getCoords(LocalizationSystem.GPS, listener); } else if (position == 1) { searchExif(); } else if (position == 2) { searchManual(); } else if (position == 3) { App.localization.getCoords(LocalizationSystem.PALS, listener); } } }) .setContentWidth(LayoutParams.WRAP_CONTENT) .setContentHeight(LayoutParams.WRAP_CONTENT) .create(); dialog.show(); } void searchManual() { Builder alertDialog = new Builder(getActivity()); final View layout = getActivity().getLayoutInflater() .inflate(R.layout.dialog_location_add_manual, null); alertDialog.setView(layout); alertDialog.setPositiveButton(getString(string.confirm), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText latitude = (EditText) layout.findViewById(id.latitude); EditText longitude = (EditText) layout.findViewById(id.longitude); setResultLayout(Float.parseFloat(latitude.getText() .toString()), Float.parseFloat(longitude.getText().toString())); } }); alertDialog.show(); } void searchExif() { Intent intent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, 0); } void setResultLayout(float lat, float lon) { if (lat != 0 && lon != 0) { submit.setVisibility(View.VISIBLE); } latitudeProgress.setVisibility(View.GONE); latitude.setText(String.valueOf(lat)); longitudeProgress.setVisibility(View.GONE); longitude.setText(String.valueOf(lon)); generateContent(lat, lon); forceZoom = false; } private void clearResultLayout() { submit.setVisibility(View.GONE); latitudeProgress.setVisibility(View.VISIBLE); latitudeProgress.setIndeterminate(true); latitude.setText(null); longitudeProgress.setVisibility(View.VISIBLE); longitudeProgress.setIndeterminate(true); longitude.setText(null); } protected final void onSubmit() { float lat = Float.parseFloat(latitude.getText().toString()); float lon = Float.parseFloat(longitude.getText().toString()); if (lat != 0 && lon != 0) { Fragment fragment = new LocationAddFragment(); Bundle bundle = new Bundle(); bundle.putFloat(Location.GEOLOCATION_COORD_LATITUDE, lat); bundle.putFloat(Location.GEOLOCATION_COORD_LONGITUDE, lon); fragment.setArguments(bundle); Util.changeFragment(null, fragment, id.frame_container, getActivity(), null); } else { Util.getMessageDialog(getString(string.no_valid_coords), getActivity()); } } /** * Bild wird ausgesucht und uebergeben */ @Override public final void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 0 && resultCode == Activity.RESULT_OK) { String path = Util.getPathFromCamera(data, getActivity()); if (path != null) { RequestBody typedFile = RequestBody.create(MediaType.parse("image/*"), new File(path)); App.rest.location.getLocationByExif(typedFile).enqueue(new Callback<Coord>() { @Override public void onResponse(Response<Coord> response, Retrofit retrofit) { if (response.isSuccess()) { setResultLayout(response.body().getLatitude(), response .body() .getLongitude()); } else { setResultLayout(0, 0); } } @Override public void onFailure(Throwable t) { Util.getMessageDialog(t.getMessage(), getActivity()); } }); } } } }
Java
module RailsLog class MailerSubscriber < ActiveSupport::LogSubscriber def record(event) payload = event.payload log_mailer = Logged::LogMailer.new(message_object_id: payload[:message_object_id], mailer: payload[:mailer]) log_mailer.action_name = payload[:action_name] log_mailer.params = payload[:params] log_mailer.save info 'mailer log saved!' end def deliver(event) payload = event.payload log_mailer = Logged::LogMailer.find_or_initialize_by(message_object_id: payload[:message_object_id], mailer: payload[:mailer]) log_mailer.subject = payload[:subject] log_mailer.sent_status = payload[:sent_status] log_mailer.sent_string = payload[:sent_string] log_mailer.mail_to = payload[:mail_to] log_mailer.cc_to = payload[:cc_to] log_mailer.save info 'mailer log updated!' end end end RailsLog::MailerSubscriber.attach_to :action_mailer
Java
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2016 Pelican Mapping * http://osgearth.org * * osgEarth 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 <http://www.gnu.org/licenses/> */ #include <osgEarthFeatures/FeatureDisplayLayout> #include <limits> using namespace osgEarth; using namespace osgEarth::Features; using namespace osgEarth::Symbology; //------------------------------------------------------------------------ FeatureLevel::FeatureLevel( const Config& conf ) : _minRange( 0.0f ), _maxRange( FLT_MAX ) { fromConfig( conf ); } FeatureLevel::FeatureLevel( float minRange, float maxRange ) { _minRange = minRange; _maxRange = maxRange; } FeatureLevel::FeatureLevel( float minRange, float maxRange, const std::string& styleName ) { _minRange = minRange; _maxRange = maxRange; _styleName = styleName; } void FeatureLevel::fromConfig( const Config& conf ) { conf.getIfSet( "min_range", _minRange ); conf.getIfSet( "max_range", _maxRange ); conf.getIfSet( "style", _styleName ); conf.getIfSet( "class", _styleName ); // alias } Config FeatureLevel::getConfig() const { Config conf( "level" ); conf.addIfSet( "min_range", _minRange ); conf.addIfSet( "max_range", _maxRange ); conf.addIfSet( "style", _styleName ); return conf; } //------------------------------------------------------------------------ FeatureDisplayLayout::FeatureDisplayLayout( const Config& conf ) : _tileSizeFactor( 15.0f ), _minRange ( 0.0f ), _maxRange ( 0.0f ), _cropFeatures ( false ), _priorityOffset( 0.0f ), _priorityScale ( 1.0f ), _minExpiryTime ( 0.0f ) { fromConfig( conf ); } void FeatureDisplayLayout::fromConfig( const Config& conf ) { conf.getIfSet( "tile_size", _tileSize ); conf.getIfSet( "tile_size_factor", _tileSizeFactor ); conf.getIfSet( "crop_features", _cropFeatures ); conf.getIfSet( "priority_offset", _priorityOffset ); conf.getIfSet( "priority_scale", _priorityScale ); conf.getIfSet( "min_expiry_time", _minExpiryTime ); conf.getIfSet( "min_range", _minRange ); conf.getIfSet( "max_range", _maxRange ); ConfigSet children = conf.children( "level" ); for( ConfigSet::const_iterator i = children.begin(); i != children.end(); ++i ) addLevel( FeatureLevel( *i ) ); } Config FeatureDisplayLayout::getConfig() const { Config conf( "layout" ); conf.addIfSet( "tile_size", _tileSize ); conf.addIfSet( "tile_size_factor", _tileSizeFactor ); conf.addIfSet( "crop_features", _cropFeatures ); conf.addIfSet( "priority_offset", _priorityOffset ); conf.addIfSet( "priority_scale", _priorityScale ); conf.addIfSet( "min_expiry_time", _minExpiryTime ); conf.addIfSet( "min_range", _minRange ); conf.addIfSet( "max_range", _maxRange ); for( Levels::const_iterator i = _levels.begin(); i != _levels.end(); ++i ) conf.add( i->second.getConfig() ); return conf; } void FeatureDisplayLayout::addLevel( const FeatureLevel& level ) { _levels.insert( std::make_pair( -level.maxRange().get(), level ) ); } unsigned FeatureDisplayLayout::getNumLevels() const { return _levels.size(); } const FeatureLevel* FeatureDisplayLayout::getLevel( unsigned n ) const { unsigned i = 0; for( Levels::const_iterator k = _levels.begin(); k != _levels.end(); ++k ) { if ( n == i++ ) return &(k->second); } return 0L; } unsigned FeatureDisplayLayout::chooseLOD( const FeatureLevel& level, double fullExtentRadius ) const { double radius = fullExtentRadius; unsigned lod = 1; for( ; lod < 20; ++lod ) { radius *= 0.5; float lodMaxRange = radius * _tileSizeFactor.value(); if ( level.maxRange() >= lodMaxRange ) break; } return lod-1; }
Java
package de.riedquat.java.io; import de.riedquat.java.util.Arrays; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import static de.riedquat.java.io.Util.copy; import static de.riedquat.java.util.Arrays.EMPTY_BYTE_ARRAY; import static org.junit.Assert.assertArrayEquals; public class UtilTest { @Test public void emptyStream_copiesNothing() throws IOException { assertCopies(EMPTY_BYTE_ARRAY); } @Test public void copiesData() throws IOException { assertCopies(Arrays.createRandomByteArray(10001)); } private void assertCopies(final byte[] testData) throws IOException { final ByteArrayInputStream in = new ByteArrayInputStream(testData); final ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(out, in); assertArrayEquals(testData, out.toByteArray()); } }
Java
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2014 Pelican Mapping * http://osgearth.org * * osgEarth 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 <http://www.gnu.org/licenses/> */ #include <string> #include <osg/Notify> #include <osg/Timer> #include <osg/ShapeDrawable> #include <osg/PositionAttitudeTransform> #include <osgGA/StateSetManipulator> #include <osgGA/GUIEventHandler> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgEarth/GeoMath> #include <osgEarth/GeoTransform> #include <osgEarth/MapNode> #include <osgEarth/TerrainEngineNode> #include <osgEarth/Viewpoint> #include <osgEarthUtil/EarthManipulator> #include <osgEarthUtil/AutoClipPlaneHandler> #include <osgEarthUtil/Controls> #include <osgEarthUtil/ExampleResources> #include <osgEarthAnnotation/AnnotationUtils> #include <osgEarthAnnotation/LabelNode> #include <osgEarthSymbology/Style> using namespace osgEarth::Util; using namespace osgEarth::Util::Controls; using namespace osgEarth::Annotation; #define D2R (osg::PI/180.0) #define R2D (180.0/osg::PI) namespace { /** * Builds our help menu UI. */ Control* createHelp( osgViewer::View* view ) { const char* text[] = { "left mouse :", "pan", "middle mouse :", "rotate", "right mouse :", "continuous zoom", "double-click :", "zoom to point", "scroll wheel :", "zoom in/out", "arrows :", "pan", "1-6 :", "fly to preset viewpoints", "shift-right-mouse :", "locked panning", "u :", "toggle azimuth lock", "c :", "toggle perspective/ortho", "t :", "toggle tethering", "a :", "toggle viewpoint arcing", "z :", "toggle throwing", "k :", "toggle collision" }; Grid* g = new Grid(); for( unsigned i=0; i<sizeof(text)/sizeof(text[0]); ++i ) { unsigned c = i % 2; unsigned r = i / 2; g->setControl( c, r, new LabelControl(text[i]) ); } VBox* v = new VBox(); v->addControl( g ); return v; } /** * Some preset viewpoints to show off the setViewpoint function. */ static Viewpoint VPs[] = { Viewpoint( "Africa", osg::Vec3d( 0.0, 0.0, 0.0 ), 0.0, -90.0, 10e6 ), Viewpoint( "California", osg::Vec3d( -121.0, 34.0, 0.0 ), 0.0, -90.0, 6e6 ), Viewpoint( "Europe", osg::Vec3d( 0.0, 45.0, 0.0 ), 0.0, -90.0, 4e6 ), Viewpoint( "Washington DC", osg::Vec3d( -77.0, 38.0, 0.0 ), 0.0, -90.0, 1e6 ), Viewpoint( "Australia", osg::Vec3d( 135.0, -20.0, 0.0 ), 0.0, -90.0, 2e6 ), Viewpoint( "Boston", osg::Vec3d( -71.096936, 42.332771, 0 ), 0.0, -90, 1e5 ) }; /** * Handler that demonstrates the "viewpoint" functionality in * osgEarthUtil::EarthManipulator. Press a number key to fly to a viewpoint. */ struct FlyToViewpointHandler : public osgGA::GUIEventHandler { FlyToViewpointHandler( EarthManipulator* manip ) : _manip(manip) { } bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { if ( ea.getEventType() == ea.KEYDOWN && ea.getKey() >= '1' && ea.getKey() <= '6' ) { _manip->setViewpoint( VPs[ea.getKey()-'1'], 4.0 ); aa.requestRedraw(); } return false; } osg::observer_ptr<EarthManipulator> _manip; }; /** * Handler to toggle "azimuth locking", which locks the camera's relative Azimuth * while panning. For example, it can maintain "north-up" as you pan around. The * caveat is that when azimuth is locked you cannot cross the poles. */ struct LockAzimuthHandler : public osgGA::GUIEventHandler { LockAzimuthHandler(char key, EarthManipulator* manip) : _key(key), _manip(manip) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key) { bool lockAzimuth = _manip->getSettings()->getLockAzimuthWhilePanning(); _manip->getSettings()->setLockAzimuthWhilePanning(!lockAzimuth); aa.requestRedraw(); return true; } return false; } void getUsage(osg::ApplicationUsage& usage) const { using namespace std; usage.addKeyboardMouseBinding(string(1, _key), string("Toggle azimuth locking")); } char _key; osg::ref_ptr<EarthManipulator> _manip; }; /** * Handler to toggle "viewpoint transtion arcing", which causes the camera to "arc" * as it travels from one viewpoint to another. */ struct ToggleArcViewpointTransitionsHandler : public osgGA::GUIEventHandler { ToggleArcViewpointTransitionsHandler(char key, EarthManipulator* manip) : _key(key), _manip(manip) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key) { bool arc = _manip->getSettings()->getArcViewpointTransitions(); _manip->getSettings()->setArcViewpointTransitions(!arc); aa.requestRedraw(); return true; } return false; } void getUsage(osg::ApplicationUsage& usage) const { using namespace std; usage.addKeyboardMouseBinding(string(1, _key), string("Arc viewpoint transitions")); } char _key; osg::ref_ptr<EarthManipulator> _manip; }; /** * Toggles the projection matrix between perspective and orthographic. */ struct ToggleProjectionHandler : public osgGA::GUIEventHandler { ToggleProjectionHandler(char key, EarthManipulator* manip) : _key(key), _manip(manip) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key) { if ( _manip->getSettings()->getCameraProjection() == EarthManipulator::PROJ_PERSPECTIVE ) _manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_ORTHOGRAPHIC ); else _manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_PERSPECTIVE ); aa.requestRedraw(); return true; } return false; } void getUsage(osg::ApplicationUsage& usage) const { using namespace std; usage.addKeyboardMouseBinding(string(1, _key), string("Toggle projection type")); } char _key; osg::ref_ptr<EarthManipulator> _manip; }; /** * Toggles the throwing feature. */ struct ToggleThrowingHandler : public osgGA::GUIEventHandler { ToggleThrowingHandler(char key, EarthManipulator* manip) : _key(key), _manip(manip) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key) { bool throwing = _manip->getSettings()->getThrowingEnabled(); _manip->getSettings()->setThrowingEnabled( !throwing ); aa.requestRedraw(); return true; } return false; } void getUsage(osg::ApplicationUsage& usage) const { using namespace std; usage.addKeyboardMouseBinding(string(1, _key), string("Toggle throwing")); } char _key; osg::ref_ptr<EarthManipulator> _manip; }; /** * Toggles the collision feature. */ struct ToggleCollisionHandler : public osgGA::GUIEventHandler { ToggleCollisionHandler(char key, EarthManipulator* manip) : _key(key), _manip(manip) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key) { bool collision = _manip->getSettings()->getDisableCollisionAvoidance(); _manip->getSettings()->setDisableCollisionAvoidance( !collision ); aa.requestRedraw(); return true; } return false; } void getUsage(osg::ApplicationUsage& usage) const { using namespace std; usage.addKeyboardMouseBinding(string(1, _key), string("Toggle collision avoidance")); } char _key; osg::ref_ptr<EarthManipulator> _manip; }; /** * A simple simulator that moves an object around the Earth. We use this to * demonstrate/test tethering. */ struct Simulator : public osgGA::GUIEventHandler { Simulator( osg::Group* root, EarthManipulator* manip, MapNode* mapnode, osg::Node* model) : _manip(manip), _mapnode(mapnode), _model(model), _lat0(55.0), _lon0(45.0), _lat1(-55.0), _lon1(-45.0) { if ( !model ) { _model = AnnotationUtils::createSphere( 250.0, osg::Vec4(1,.7,.4,1) ); } _xform = new GeoTransform(); _xform->setTerrain(mapnode->getTerrain()); _pat = new osg::PositionAttitudeTransform(); _pat->addChild( _model ); _xform->addChild( _pat ); _cam = new osg::Camera(); _cam->setRenderOrder( osg::Camera::NESTED_RENDER, 1 ); _cam->addChild( _xform ); Style style; style.getOrCreate<TextSymbol>()->size() = 32.0f; style.getOrCreate<TextSymbol>()->declutter() = false; _label = new LabelNode(_mapnode, GeoPoint(), "Hello World", style); _label->setDynamic( true ); _cam->addChild( _label ); root->addChild( _cam.get() ); } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if ( ea.getEventType() == ea.FRAME ) { double t = fmod( osg::Timer::instance()->time_s(), 600.0 ) / 600.0; double lat, lon; GeoMath::interpolate( D2R*_lat0, D2R*_lon0, D2R*_lat1, D2R*_lon1, t, lat, lon ); GeoPoint p( SpatialReference::create("wgs84"), R2D*lon, R2D*lat, 2500.0 ); double bearing = GeoMath::bearing(D2R*_lat1, D2R*_lon1, lat, lon); _xform->setPosition( p ); _pat->setAttitude(osg::Quat(bearing, osg::Vec3d(0,0,1))); _label->setPosition( p ); } else if ( ea.getEventType() == ea.KEYDOWN && ea.getKey() == 't' ) { _manip->getSettings()->setTetherMode(osgEarth::Util::EarthManipulator::TETHER_CENTER_AND_HEADING); _manip->setTetherNode( _manip->getTetherNode() ? 0L : _xform.get(), 2.0 ); Viewpoint vp = _manip->getViewpoint(); vp.setRange(5000); _manip->setViewpoint(vp); return true; } return false; } MapNode* _mapnode; EarthManipulator* _manip; osg::ref_ptr<osg::Camera> _cam; osg::ref_ptr<GeoTransform> _xform; osg::ref_ptr<osg::PositionAttitudeTransform> _pat; double _lat0, _lon0, _lat1, _lon1; LabelNode* _label; osg::Node* _model; }; } int main(int argc, char** argv) { osg::ArgumentParser arguments(&argc,argv); if (arguments.read("--help") || argc==1) { OE_WARN << "Usage: " << argv[0] << " [earthFile] [--model modelToLoad]" << std::endl; return 0; } osgViewer::Viewer viewer(arguments); // install the programmable manipulator. EarthManipulator* manip = new EarthManipulator(); viewer.setCameraManipulator( manip ); // UI: Control* help = createHelp(&viewer); osg::Node* earthNode = MapNodeHelper().load( arguments, &viewer, help ); if (!earthNode) { OE_WARN << "Unable to load earth model." << std::endl; return -1; } osg::Group* root = new osg::Group(); root->addChild( earthNode ); osgEarth::MapNode* mapNode = osgEarth::MapNode::findMapNode( earthNode ); if ( mapNode ) { if ( mapNode ) manip->setNode( mapNode->getTerrainEngine() ); if ( mapNode->getMap()->isGeocentric() ) { manip->setHomeViewpoint( Viewpoint( osg::Vec3d( -90, 0, 0 ), 0.0, -90.0, 5e7 ) ); } } // user model? osg::Node* model = 0L; std::string modelFile; if (arguments.read("--model", modelFile)) model = osgDB::readNodeFile(modelFile); // Simulator for tethering: viewer.addEventHandler( new Simulator(root, manip, mapNode, model) ); manip->getSettings()->getBreakTetherActions().push_back( EarthManipulator::ACTION_PAN ); manip->getSettings()->getBreakTetherActions().push_back( EarthManipulator::ACTION_GOTO ); // Set the minimum distance to something larger than the default manip->getSettings()->setMinMaxDistance(5.0, manip->getSettings()->getMaxDistance()); viewer.setSceneData( root ); manip->getSettings()->bindMouse( EarthManipulator::ACTION_EARTH_DRAG, osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON, osgGA::GUIEventAdapter::MODKEY_SHIFT ); manip->getSettings()->setArcViewpointTransitions( true ); viewer.addEventHandler(new FlyToViewpointHandler( manip )); viewer.addEventHandler(new LockAzimuthHandler('u', manip)); viewer.addEventHandler(new ToggleProjectionHandler('c', manip)); viewer.addEventHandler(new ToggleArcViewpointTransitionsHandler('a', manip)); viewer.addEventHandler(new ToggleThrowingHandler('z', manip)); viewer.addEventHandler(new ToggleCollisionHandler('k', manip)); viewer.getCamera()->setNearFarRatio(0.00002); viewer.getCamera()->setSmallFeatureCullingPixelSize(-1.0f); while(!viewer.done()) { viewer.frame(); // simulate slow frame rate //OpenThreads::Thread::microSleep(1000*1000); } return 0; }
Java
package com.darkona.adventurebackpack.inventory; import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; import com.darkona.adventurebackpack.init.ModBlocks; import com.darkona.adventurebackpack.item.ItemAdventureBackpack; import com.darkona.adventurebackpack.util.Utils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; /** * Created by Darkona on 12/10/2014. */ public class SlotBackpack extends SlotAdventureBackpack { public SlotBackpack(IInventoryAdventureBackpack inventory, int id, int x, int y) { super(inventory, id, x, y); } @Override public boolean isItemValid(ItemStack stack) { return (!(stack.getItem() instanceof ItemAdventureBackpack) && !(stack.getItem() == Item.getItemFromBlock(ModBlocks.blockBackpack))); } @Override public void onPickupFromSlot(EntityPlayer p_82870_1_, ItemStack p_82870_2_) { super.onPickupFromSlot(p_82870_1_, p_82870_2_); } }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitExAPI.Markets.Kraken.Requests { /// <summary> /// https://api.kraken.com/0/private/TradeBalance /// </summary> public class RequestTradeBalance { } } /*Input: aclass = asset class (optional): currency (default) asset = base asset used to determine balance (default = ZUSD) Result: array of trade balance info eb = equivalent balance (combined balance of all currencies) tb = trade balance (combined balance of all equity currencies) m = margin amount of open positions n = unrealized net profit/loss of open positions c = cost basis of open positions v = current floating valuation of open positions e = equity = trade balance + unrealized net profit/loss mf = free margin = equity - initial margin (maximum margin available to open new positions) ml = margin level = (equity / initial margin) * 100 */
Java
// // BitWiseTrie.hpp // Scissum // // Created by Marten van de Sanden on 12/1/15. // Copyright © 2015 MVDS. All rights reserved. // #ifndef BitWiseTrie_hpp #define BitWiseTrie_hpp #include <vector> //#include <iostream> #include <cstring> #define __SCISSUM_BITWISE_TRIE_USE_ZERO_TABLE 1 namespace scissum { /// TODO: Add cache locality and allocation efficiency by pre allocating an array of nodes!!!!! template <class _Key, class _Value> class BitWiseTrie { public: struct Node { size_t childs[2]; _Value value; Node() { childs[0] = 0; childs[1] = 0; } }; BitWiseTrie() { d_nodes.resize(sizeof(_Key)*8+1); for (size_t i = 0; i < sizeof(_Key)*8+1; ++i) { d_zeroTable[i] = i; } } Node const *node(size_t index) const { return &d_nodes[index]; } Node const *roots(size_t lz) const { return &d_nodes[d_zeroTable[lz]]; } Node *insert(_Key key) { int z = (key != 0?__builtin_clz(key):(sizeof(_Key) * 8)); size_t root = d_zeroTable[z]; int c = (sizeof(_Key) * 8) - z; while (c-- > 0) { //std::cout << "A " << c << " = " << !!(key & (1 << c)) << ".\n"; size_t n = d_nodes[root].childs[!!(key & (1 << c))]; if (n == 0) { break; } root = n; } while (c > 0) { //std::cout << "B " << c << " = " << !!(key & (1 << c)) << ".\n"; size_t n = d_nodes.size(); d_nodes.push_back(Node()); d_nodes[root].childs[!!(key & (1 << c--))] = n; root = n; } if (c == 0) { //std::cout << "C = " << !!(key & 1) << ".\n"; size_t n = d_nodes.size(); d_nodes.push_back(Node()); d_nodes[root].childs[!!(key & 1)] = n; return &d_nodes[n]; } return &d_nodes[root]; } private: std::vector<Node> d_nodes; size_t d_zeroTable[sizeof(_Key)*8+1]; }; } #endif /* BitWiseTrie_hpp */
Java
/** *×÷Õß:Âé²Ë *ÈÕÆÚ:2013Äê6ÔÂ20ÈÕ *¹¦ÄÜ:×Ô¶¨ÒåÑÕɫѡÔñ¶ÔÏó,´ÓQColorDialogÀàÖÐÌáÈ¡ÖØÐ·â×°.½ö±£Áôͨ¹ýÊó±êpickÌáÈ¡ÑÕÉ«µÄ¿Ø¼þ *˵Ã÷:¿ªÔ´,Ãâ·Ñ,ʹÓÃʱÇë±£³Ö¿ªÔ´¾«Éñ. *ÁªÏµ:12319597@qq.com *²©¿Í:www.newdebug.com **/ #include "colorshowlabel.h" #include <QApplication> #include <QPainter> #include <QMimeData> #include <QDrag> #include <QMouseEvent> YviColorShowLabel::YviColorShowLabel(QWidget *parent) : QFrame(parent) { this->setFrameStyle(QFrame::Panel|QFrame::Sunken); this->setAcceptDrops(true); m_mousePressed = false; } void YviColorShowLabel::paintEvent(QPaintEvent *e) { QPainter p(this); drawFrame(&p); p.fillRect(contentsRect()&e->rect(), m_color); } void YviColorShowLabel::mousePressEvent(QMouseEvent *e) { m_mousePressed = true; m_pressPos = e->pos(); } void YviColorShowLabel::mouseMoveEvent(QMouseEvent *e) { if (!m_mousePressed) return; if ((m_pressPos - e->pos()).manhattanLength() > QApplication::startDragDistance()) { QMimeData *mime = new QMimeData; mime->setColorData(m_color); QPixmap pix(30, 20); pix.fill(m_color); QPainter p(&pix); p.drawRect(0, 0, pix.width() - 1, pix.height() - 1); p.end(); QDrag *drg = new QDrag(this); drg->setMimeData(mime); drg->setPixmap(pix); m_mousePressed = false; drg->start(); } } void YviColorShowLabel::mouseReleaseEvent(QMouseEvent *) { if (!m_mousePressed) return; m_mousePressed = false; }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Harnet.Net { public class Request { #region Properties /// <summary> /// Request method (GET, POST, ...). /// </summary> public string Method { get; set; } /// <summary> /// Absolute URL of the request (fragments are not included). /// </summary> public string Url { get; set; } /// <summary> /// Request HTTP Version. /// </summary> public string HttpVersion { get; set; } /// <summary> /// List of header objects. /// </summary> public Dictionary<string, List<string>> Headers { get; set; } /// <summary> /// List of query parameter objects. /// </summary> public Dictionary<string, List<string>> QueryStrings { get; set; } /// <summary> /// List of cookie objects. /// </summary> public Dictionary<string, List<string>> Cookies { get; set; } /// <summary> /// Total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body. Set to -1 if the info is not available. /// </summary> public int HeaderSize { get; set; } /// <summary> /// Size of the request body (POST data payload) in bytes. Set to -1 if the info is not available. /// </summary> public int BodySize { get; set; } /// <summary> /// Posted data info. /// </summary> public PostData PostData { get; set; } /// <summary> /// A comment provided by the user or the application. /// </summary> public string Comment { get; set; } #endregion #region Methods public List<string> GetHeaderValueByHeaderName(string name) { List<string> value = null; if (Headers.ContainsKey(name)) { value = Headers[name]; } return value; } /// <summary> /// Attempts to retrieve the filename from the request. /// </summary> /// <returns>Returns the filename. If no filename is found, returns null.</returns> public string GetFileName() { string fileName = null; // If we have query strings we remove them first because sometimes they get funky if (this.QueryStrings.Count >= 1) { fileName = StripQueryStringsFromUrl(); } else fileName = Url; // Isolate what's after the trailing slash and before any query string int index = fileName.LastIndexOf("/"); // If difference between index and length is < 1, it means we have no file name // e.g.: http://www.fsf.org/ int diff = fileName.Length - index; if (index > 0 && diff > 1) fileName = fileName.Substring(index +1, diff - 1); else fileName = null; return fileName; } /// <summary> /// Strips the Url of all query strings and returns it (e.g. www.fsf.org/index.html?foo=bar returns www.fsg.org/index.html). /// </summary> /// <returns></returns> public string StripQueryStringsFromUrl() { int indexOf = Url.IndexOf("?"); if (indexOf >= 1) return Url.Substring(0, indexOf); else return Url; } /// <summary> /// Returns whether or not this request contains cookies. /// </summary> /// <returns></returns> public bool HasCookies() { return (this.Cookies.Count > 0) ? true : false; } /// <summary> /// Returns whether or not this request contains headers. /// </summary> /// <returns></returns> public bool HasHeaders() { return (this.Headers.Count > 0) ? true : false; } /// <summary> /// Returns whether or not this request contains query strings. /// </summary> /// <returns></returns> public bool HasQueryStrings() { return (this.QueryStrings.Count > 0) ? true : false; } #endregion } }
Java
package org.alfresco.repo.cmis.ws; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="repositoryId" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="extension" type="{http://docs.oasis-open.org/ns/cmis/messaging/200908/}cmisExtensionType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "repositoryId", "extension" }) @XmlRootElement(name = "getRepositoryInfo") public class GetRepositoryInfo { @XmlElement(required = true) protected String repositoryId; @XmlElementRef(name = "extension", namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", type = JAXBElement.class) protected JAXBElement<CmisExtensionType> extension; /** * Gets the value of the repositoryId property. * * @return * possible object is * {@link String } * */ public String getRepositoryId() { return repositoryId; } /** * Sets the value of the repositoryId property. * * @param value * allowed object is * {@link String } * */ public void setRepositoryId(String value) { this.repositoryId = value; } /** * Gets the value of the extension property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link CmisExtensionType }{@code >} * */ public JAXBElement<CmisExtensionType> getExtension() { return extension; } /** * Sets the value of the extension property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link CmisExtensionType }{@code >} * */ public void setExtension(JAXBElement<CmisExtensionType> value) { this.extension = ((JAXBElement<CmisExtensionType> ) value); } }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace LeagueOfChampios { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
Java
// Copyright (C) 2013 Columbia University in the City of New York and others. // // Please see the AUTHORS file in the main source directory for a full list // of contributors. // // This file is part of TerraFERMA. // // TerraFERMA is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // TerraFERMA 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 TerraFERMA. If not, see <http://www.gnu.org/licenses/>. #include "SemiLagrangianExpression.h" #include "BoostTypes.h" #include "Bucket.h" #include "Logger.h" #include <dolfin.h> using namespace buckettools; //*******************************************************************|************************************************************// // specific constructor (scalar) //*******************************************************************|************************************************************// SemiLagrangianExpression::SemiLagrangianExpression(const Bucket *bucket, const double_ptr time, const std::pair< std::string, std::pair< std::string, std::string > > &function, const std::pair< std::string, std::pair< std::string, std::string > > &velocity, const std::pair< std::string, std::pair< std::string, std::string > > &outside) : dolfin::Expression(), bucket_(bucket), time_(time), funcname_(function), velname_(velocity), outname_(outside), initialized_(false) { tf_not_parallelized("SemiLagrangianExpression"); } //*******************************************************************|************************************************************// // specific constructor (vector) //*******************************************************************|************************************************************// SemiLagrangianExpression::SemiLagrangianExpression(const std::size_t &dim, const Bucket *bucket, const double_ptr time, const std::pair< std::string, std::pair< std::string, std::string > > &function, const std::pair< std::string, std::pair< std::string, std::string > > &velocity, const std::pair< std::string, std::pair< std::string, std::string > > &outside) : dolfin::Expression(dim), bucket_(bucket), time_(time), funcname_(function), velname_(velocity), outname_(outside), initialized_(false) { tf_not_parallelized("SemiLagrangianExpression"); } //*******************************************************************|************************************************************// // specific constructor (tensor) //*******************************************************************|************************************************************// SemiLagrangianExpression::SemiLagrangianExpression(const std::vector<std::size_t> &value_shape, const Bucket *bucket, const double_ptr time, const std::pair< std::string, std::pair< std::string, std::string > > &function, const std::pair< std::string, std::pair< std::string, std::string > > &velocity, const std::pair< std::string, std::pair< std::string, std::string > > &outside) : dolfin::Expression(value_shape), bucket_(bucket), time_(time), funcname_(function), velname_(velocity), outname_(outside), initialized_(false) { tf_not_parallelized("SemiLagrangianExpression"); } //*******************************************************************|************************************************************// // default destructor //*******************************************************************|************************************************************// SemiLagrangianExpression::~SemiLagrangianExpression() { delete ufccellstar_; ufccellstar_ = NULL; delete[] xstar_; xstar_ = NULL; delete v_; v_ = NULL; delete oldv_; oldv_ = NULL; delete vstar_; vstar_ = NULL; delete cellcache_; cellcache_ = NULL; } //*******************************************************************|************************************************************// // initialize the expression //*******************************************************************|************************************************************// void SemiLagrangianExpression::init() { if (!initialized_) { initialized_ = true; if(funcname_.second.first=="field") { func_ = (*(*(*bucket()).fetch_system(funcname_.first)). fetch_field(funcname_.second.second)). genericfunction_ptr(time()); } else { func_ = (*(*(*bucket()).fetch_system(funcname_.first)). fetch_coeff(funcname_.second.second)). genericfunction_ptr(time()); } if(velname_.second.first=="field") { vel_ = (*(*(*bucket()).fetch_system(velname_.first)). fetch_field(velname_.second.second)). genericfunction_ptr((*bucket()).current_time_ptr()); oldvel_ = (*(*(*bucket()).fetch_system(velname_.first)). fetch_field(velname_.second.second)). genericfunction_ptr((*bucket()).old_time_ptr()); } else { vel_ = (*(*(*bucket()).fetch_system(velname_.first)). fetch_coeff(velname_.second.second)). genericfunction_ptr((*bucket()).current_time_ptr()); oldvel_ = (*(*(*bucket()).fetch_system(velname_.first)). fetch_coeff(velname_.second.second)). genericfunction_ptr((*bucket()).old_time_ptr()); } if(outname_.second.first=="field") { out_ = (*(*(*bucket()).fetch_system(outname_.first)). fetch_field(outname_.second.second)). genericfunction_ptr(time()); } else { out_ = (*(*(*bucket()).fetch_system(outname_.first)). fetch_coeff(outname_.second.second)). genericfunction_ptr(time()); } assert(value_rank()==(*func_).value_rank()); assert(value_rank()==(*out_).value_rank()); for (uint i = 0; i < value_rank(); i++) { assert(value_dimension(i)==(*func_).value_dimension(i)); assert(value_dimension(i)==(*out_).value_dimension(i)); } mesh_ = (*(*bucket()).fetch_system(funcname_.first)).mesh();// use the mesh from the function system dim_ = (*mesh_).geometry().dim(); assert((*vel_).value_rank()<2); if((*vel_).value_rank()==0) { assert(dim_==1); } else { assert((*vel_).value_dimension(0)==dim_); } ufccellstar_ = new ufc::cell; xstar_ = new double[dim_]; v_ = new dolfin::Array<double>(dim_); oldv_ = new dolfin::Array<double>(dim_); vstar_ = new dolfin::Array<double>(dim_); cellcache_ = new dolfin::MeshFunction< point_map >(mesh_, dim_); } } //*******************************************************************|************************************************************// // overload dolfin expression eval //*******************************************************************|************************************************************// void SemiLagrangianExpression::eval(dolfin::Array<double>& values, const dolfin::Array<double>& x, const ufc::cell &cell) const { const bool outside = findpoint_(x, cell); dolfin::Array<double> xstar(dim_, xstar_); if (outside) { (*out_).eval(values, xstar, *ufccellstar_); } else { (*func_).eval(values, xstar, *ufccellstar_); } } //*******************************************************************|************************************************************// // find the launch point //*******************************************************************|************************************************************// const bool SemiLagrangianExpression::findpoint_(const dolfin::Array<double>& x, const ufc::cell &cell) const { bool outside = false; point_map &points = (*cellcache_)[cell.index]; dolfin::Point lp(x.size(), x.data()); point_iterator p_it = points.find(lp); findvstar_(x, cell); for (uint k = 0; k < 2; k++) { for (uint i = 0; i < dim_; i++) { xstar_[i] = x[i] - ((*bucket()).timestep()/2.0)*(*vstar_)[i]; } outside = checkpoint_(0, p_it, points, lp); if (outside) { return true; } dolfin::Array<double> xstar(dim_, xstar_); findvstar_(xstar, *ufccellstar_); } for (uint i = 0; i < dim_; i++) { xstar_[i] = x[i] - ((*bucket()).timestep())*(*vstar_)[i]; } outside = checkpoint_(1, p_it, points, lp); if (outside) { return true; } return false; } //*******************************************************************|************************************************************// // find the time weighted velocity at the requested point, x //*******************************************************************|************************************************************// void SemiLagrangianExpression::findvstar_(const dolfin::Array<double>& x, const ufc::cell &cell) const { (*vel_).eval(*v_, x, cell); (*oldvel_).eval(*oldv_, x, cell); for (uint i = 0; i < dim_; i++) { (*vstar_)[i] = 0.5*( (*v_)[i] + (*oldv_)[i] ); } } //*******************************************************************|************************************************************// // check if the current xstar_ is in the cache and/or is valid //*******************************************************************|************************************************************// const bool SemiLagrangianExpression::checkpoint_(const int &index, point_iterator &p_it, point_map &points, const dolfin::Point &lp) const { std::vector<unsigned int> cell_indices; int cell_index; const dolfin::Point p(dim_, xstar_); if (p_it != points.end()) { cell_index = (*p_it).second[index]; bool update = false; if (cell_index < 0) { update = true; } else { dolfin::Cell dolfincell(*mesh_, cell_index); if (!dolfincell.collides(p)) { update = true; } } if (update) { cell_indices = (*(*mesh_).bounding_box_tree()).compute_entity_collisions(p); if (cell_indices.size()==0) { cell_index = -1; } else { cell_index = cell_indices[0]; } (*p_it).second[index] = cell_index; } } else { cell_indices = (*(*mesh_).bounding_box_tree()).compute_entity_collisions(p); if (cell_indices.size()==0) { cell_index = -1; } else { cell_index = cell_indices[0]; } std::vector<int> cells(2, -1); cells[index] = cell_index; points[lp] = cells; } if (cell_index<0) { return true; } dolfin::Cell dolfincell(*mesh_, cell_index); dolfincell.get_cell_data(*ufccellstar_); return false; }
Java
#include "util/checksum.hpp" namespace trillek { namespace util { namespace algorithm { static uint32_t crc32_table[256]; static bool crc32_table_computed = false; static void GenCRC32Table() { uint32_t c; uint32_t i; int k; for(i = 0; i < 256; i++) { c = i; for(k = 0; k < 8; k++) { if(c & 1) c = 0xedb88320ul ^ (c >> 1); else c = c >> 1; } crc32_table[i] = c; } crc32_table_computed = true; } void Crc32::Update(char d) { if(!crc32_table_computed) GenCRC32Table(); ldata = crc32_table[(ldata ^ ((unsigned char)d)) & 0xff] ^ (ldata >> 8); } void Crc32::Update(const std::string &d) { uint32_t c = ldata; std::string::size_type n, l = d.length(); if(!crc32_table_computed) GenCRC32Table(); for(n = 0; n < l; n++) { c = crc32_table[(c ^ ((unsigned char)d[n])) & 0xff] ^ (c >> 8); } ldata = c; } void Crc32::Update(const void *dv, size_t l) { uint32_t c = ldata; std::string::size_type n; char * d = (char*)dv; if(!crc32_table_computed) GenCRC32Table(); for(n = 0; n < l; n++) { c = crc32_table[(c ^ ((unsigned char)d[n])) & 0xff] ^ (c >> 8); } ldata = c; } static const uint32_t ADLER_LIMIT = 5552; static const uint32_t ADLER_BASE = 65521u; void Adler32::Update(const std::string &d) { Update(d.data(), d.length()); } void Adler32::Update(const void *dv, size_t l) { uint32_t c1 = ldata & 0xffff; uint32_t c2 = (ldata >> 16) & 0xffff; unsigned char * d = (unsigned char*)dv; std::string::size_type n = 0; while(l >= ADLER_LIMIT) { l -= ADLER_LIMIT; uint32_t limit = ADLER_LIMIT / 16; while(limit--) { c1 += d[n ]; c2 += c1; c1 += d[n+ 1]; c2 += c1; c1 += d[n+ 2]; c2 += c1; c1 += d[n+ 3]; c2 += c1; c1 += d[n+ 4]; c2 += c1; c1 += d[n+ 5]; c2 += c1; c1 += d[n+ 6]; c2 += c1; c1 += d[n+ 7]; c2 += c1; c1 += d[n+ 8]; c2 += c1; c1 += d[n+ 9]; c2 += c1; c1 += d[n+10]; c2 += c1; c1 += d[n+11]; c2 += c1; c1 += d[n+12]; c2 += c1; c1 += d[n+13]; c2 += c1; c1 += d[n+14]; c2 += c1; c1 += d[n+15]; c2 += c1; n += 16; } c1 %= ADLER_BASE; c2 %= ADLER_BASE; } for(; l; n++, l--) { c1 += d[n]; while(c1 >= ADLER_BASE) { c1 -= ADLER_BASE; } c2 += c1; while(c2 >= ADLER_BASE) { c2 -= ADLER_BASE; } } ldata = (c2 << 16) + c1; } } // algorithm } // util } // trillek
Java
Imports Windows.Graphics.Imaging Imports Windows.Storage Imports Windows.Storage.Pickers Imports Windows.Storage.Streams Imports Windows.UI Module Captura Public Async Sub Generar(lv As ListView, tienda As String) Dim picker As New FileSavePicker() picker.FileTypeChoices.Add("PNG File", New List(Of String)() From { ".png" }) picker.SuggestedFileName = tienda.ToLower + DateTime.Today.Day.ToString + DateTime.Now.Hour.ToString + DateTime.Now.Minute.ToString + DateTime.Now.Millisecond.ToString Dim ficheroImagen As StorageFile = Await picker.PickSaveFileAsync() If ficheroImagen Is Nothing Then Return End If lv.Background = New SolidColorBrush(Colors.Gainsboro) Dim stream As IRandomAccessStream = Await ficheroImagen.OpenAsync(FileAccessMode.ReadWrite) Dim render As New RenderTargetBitmap Await render.RenderAsync(lv) Dim buffer As IBuffer = Await render.GetPixelsAsync Dim pixels As Byte() = buffer.ToArray Dim logicalDpi As Single = DisplayInformation.GetForCurrentView().LogicalDpi Dim encoder As BitmapEncoder = Await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream) encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, render.PixelWidth, render.PixelHeight, logicalDpi, logicalDpi, pixels) Await encoder.FlushAsync() lv.Background = New SolidColorBrush(Colors.Transparent) End Sub End Module
Java
/* * Copyright (C) 2011-2020 goblinhack@gmail.com * * See the LICENSE file for license. */ #include "my_main.h" #include "my_thing_tile.h" #include "my_time_util.h" #include "my_wid.h" void wid_animate (widp w) {_ if (!w->animate) { return; } tpp tp = wid_get_thing_template(w); if (!tp) { return; } if (!tp_is_animated(tp)) { return; } thing_tilep tile; tile = w->current_tile; if (tile) { /* * If within the animate time of this frame, keep with it. */ if (w->timestamp_change_to_next_frame > time_get_time_ms()) { return; } /* * Stop the animation here? */ if (thing_tile_is_end_of_anim(tile)) { return; } } auto tiles = tp_get_tiles(tp); /* * Get the next tile. */ if (tile) { tile = thing_tile_next(tiles, tile); } /* * Find a tile that matches the things current mode. */ uint32_t size = tiles.size(); uint32_t tries = 0; while (tries < size) { tries++; /* * Cater for wraps. */ if (!tile) { tile = thing_tile_first(tiles); } { if (thing_tile_is_dead(tile)) { tile = thing_tile_next(tiles, tile); continue; } if (thing_tile_is_open(tile)) { tile = thing_tile_next(tiles, tile); continue; } } break; } if (!tile) { return; } /* * Use this tile! */ w->current_tile = tile; wid_set_tilename(w, thing_tile_name(tile)); /* * When does this tile expire ? */ uint32_t delay = thing_tile_delay_ms(tile); if (delay) { delay = myrand() % delay; } w->timestamp_change_to_next_frame = time_get_time_ms() + delay; }
Java
/******************************************************************************* * Copyright (c) 2014 Open Door Logistics (www.opendoorlogistics.com) * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at http://www.gnu.org/licenses/lgpl.txt ******************************************************************************/ package com.opendoorlogistics.core.scripts.execution.dependencyinjection; import java.awt.Dimension; import javax.swing.JPanel; import com.opendoorlogistics.api.HasApi; import com.opendoorlogistics.api.components.ComponentControlLauncherApi.ControlLauncherCallback; import com.opendoorlogistics.api.components.ComponentExecutionApi.ClosedStatusObservable; import com.opendoorlogistics.api.components.ComponentExecutionApi.ModalDialogResult; import com.opendoorlogistics.api.components.ODLComponent; import com.opendoorlogistics.api.components.ProcessingApi; import com.opendoorlogistics.api.distances.DistancesConfiguration; import com.opendoorlogistics.api.distances.ODLCostMatrix; import com.opendoorlogistics.api.geometry.LatLong; import com.opendoorlogistics.api.geometry.ODLGeom; import com.opendoorlogistics.api.tables.ODLDatastore; import com.opendoorlogistics.api.tables.ODLTable; import com.opendoorlogistics.api.tables.ODLTableReadOnly; import com.opendoorlogistics.core.tables.decorators.datastores.dependencies.DataDependencies; public interface DependencyInjector extends ProcessingApi, HasApi { String getBatchKey(); ModalDialogResult showModalPanel(JPanel panel,String title, ModalDialogResult ...buttons); ModalDialogResult showModalPanel(JPanel panel,String title,Dimension minSize, ModalDialogResult ...buttons); <T extends JPanel & ClosedStatusObservable> void showModalPanel(T panel, String title); ODLCostMatrix calculateDistances(DistancesConfiguration request, ODLTableReadOnly... tables); ODLGeom calculateRouteGeom(DistancesConfiguration request, LatLong from, LatLong to); void addInstructionDependencies(String instructionId, DataDependencies dependencies); void submitControlLauncher(String instructionId,ODLComponent component,ODLDatastore<? extends ODLTable> parametersTableCopy, String reportTopLabel,ControlLauncherCallback cb); }
Java
/****************************************************************************** * Copyright (c) 2014-2015 Leandro T. C. Melo (ltcmelo@gmail.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA *****************************************************************************/ #include "ui_uaisosettings.h" #include "uaisosettings.h" #include "uaisoeditor.h" #include <coreplugin/icore.h> #include <QPointer> /* Uaiso - https://github.com/ltcmelo/uaiso * * Notice: This implementation has the only purpose of showcasing a few * components of the Uaiso project. It's not intended to be efficient, * nor to be taken as reference on how to write Qt Creator editors. It's * not even complete. The primary concern is to demonstrate Uaiso's API. */ using namespace UaisoQtc; using namespace TextEditor; using namespace uaiso; struct UaisoSettingsPage::UaisoSettingsPagePrivate { explicit UaisoSettingsPagePrivate() : m_displayName(tr("Uaiso Source Analyser")) , m_settingsPrefix(QLatin1String("Uaiso")) , m_prevIndex(-1) , m_page(0) {} const Core::Id m_id; const QString m_displayName; const QString m_settingsPrefix; int m_prevIndex; UaisoSettings m_settings; QPointer<QWidget> m_widget; Ui::UaisoSettingsPage *m_page; }; UaisoSettingsPage::UaisoSettingsPage(QObject *parent) : Core::IOptionsPage(parent) , m_d(new UaisoSettingsPagePrivate) { setId(Constants::SETTINGS_ID); setDisplayName(m_d->m_displayName); setCategory(Constants::SETTINGS_CATEGORY); setDisplayCategory(QCoreApplication::translate("Uaiso", Constants::SETTINGS_TR_CATEGORY)); //setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_ICON)); } UaisoSettingsPage::~UaisoSettingsPage() { delete m_d; } QWidget *UaisoSettingsPage::widget() { if (!m_d->m_widget) { m_d->m_widget = new QWidget; m_d->m_page = new Ui::UaisoSettingsPage; m_d->m_page->setupUi(m_d->m_widget); m_d->m_page->langCombo->setCurrentIndex(0); for (auto lang : supportedLangs()) { m_d->m_page->langCombo->addItem(QString::fromStdString(langName(lang)), QVariant::fromValue(static_cast<int>(lang))); } m_d->m_settings.load(Core::ICore::settings()); m_d->m_prevIndex = -1; // Reset previous index. connect(m_d->m_page->langCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(displayOptionsForLang(int))); settingsToUI(); } return m_d->m_widget; } void UaisoSettingsPage::apply() { if (!m_d->m_page) return; settingsFromUI(); m_d->m_settings.store(Core::ICore::settings()); } void UaisoSettingsPage::finish() { delete m_d->m_widget; if (!m_d->m_page) return; delete m_d->m_page; m_d->m_page = 0; } void UaisoSettingsPage::displayOptionsForLang(int index) { if (m_d->m_prevIndex != -1) updateOptionsOfLang(m_d->m_prevIndex); UaisoSettings::LangOptions &options = m_d->m_settings.m_options[index]; m_d->m_page->enabledCheck->setChecked(options.m_enabled); m_d->m_page->interpreterEdit->setText(options.m_interpreter); m_d->m_page->sysPathEdit->setText(options.m_systemPaths); m_d->m_page->extraPathEdit->setText(options.m_extraPaths); m_d->m_prevIndex = index; } void UaisoSettingsPage::updateOptionsOfLang(int index) { UaisoSettings::LangOptions &options = m_d->m_settings.m_options[index]; options.m_enabled = m_d->m_page->enabledCheck->isChecked(); options.m_interpreter = m_d->m_page->interpreterEdit->text(); options.m_systemPaths = m_d->m_page->sysPathEdit->text(); options.m_extraPaths = m_d->m_page->extraPathEdit->text(); } void UaisoSettingsPage::settingsFromUI() { updateOptionsOfLang(m_d->m_page->langCombo->currentIndex()); } void UaisoSettingsPage::settingsToUI() { displayOptionsForLang(m_d->m_page->langCombo->currentIndex()); } namespace { const QLatin1String kUaiso("UaisoSettings"); const QLatin1String kEnabled("Enabled"); const QLatin1String kInterpreter("Interpreter"); const QLatin1String kSystemPaths("SystemPaths"); const QLatin1String kExtraPaths("ExtraPaths"); } // anonymous void UaisoSettings::store(QSettings *settings, const LangOptions &options, const QString& group) const { settings->beginGroup(group); settings->setValue(kEnabled, options.m_enabled); settings->setValue(kInterpreter, options.m_interpreter); settings->setValue(kSystemPaths, options.m_systemPaths); settings->setValue(kExtraPaths, options.m_extraPaths); settings->endGroup(); } void UaisoSettings::store(QSettings *settings) const { for (auto const& option : m_options) { store(settings, option.second, kUaiso + QString::fromStdString(langName(LangName(option.first)))); } } void UaisoSettings::load(QSettings *settings, LangOptions &options, const QString& group) { settings->beginGroup(group); options.m_enabled = settings->value(kEnabled).toBool(); options.m_interpreter = settings->value(kInterpreter).toString(); options.m_systemPaths = settings->value(kSystemPaths).toString(); options.m_extraPaths = settings->value(kExtraPaths).toString(); settings->endGroup(); } void UaisoSettings::load(QSettings *settings) { for (auto lang : supportedLangs()) { auto& option = m_options[static_cast<int>(lang)]; load(settings, option, kUaiso + QString::fromStdString(langName(lang))); } }
Java
/**************************************************************************** ** ** Copyright (C) 2014-2018 Dinu SV. ** (contact: mail@dinusv.com) ** This file is part of Live CV Application. ** ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPLv3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl.html. ** ****************************************************************************/ #include "qmllibrarydependency.h" #include <QStringList> namespace lv{ QmlLibraryDependency::QmlLibraryDependency(const QString &uri, int versionMajor, int versionMinor) : m_uri(uri) , m_versionMajor(versionMajor) , m_versionMinor(versionMinor) { } QmlLibraryDependency::~QmlLibraryDependency(){ } QmlLibraryDependency QmlLibraryDependency::parse(const QString &import){ int position = import.lastIndexOf(' '); if ( position == -1 ) return QmlLibraryDependency("", -1, -1); int major, minor; bool isVersion = parseVersion(import.mid(position + 1).trimmed(), &major, &minor); if ( !isVersion ) return QmlLibraryDependency("", -1, -1); return QmlLibraryDependency(import.mid(0, position).trimmed(), major, minor); } int QmlLibraryDependency::parseInt(const QStringRef &str, bool *ok){ int pos = 0; int number = 0; while (pos < str.length() && str.at(pos).isDigit()) { if (pos != 0) number *= 10; number += str.at(pos).unicode() - '0'; ++pos; } if (pos != str.length()) *ok = false; else *ok = true; return number; } bool QmlLibraryDependency::parseVersion(const QString &str, int *major, int *minor){ const int dotIndex = str.indexOf(QLatin1Char('.')); if (dotIndex != -1 && str.indexOf(QLatin1Char('.'), dotIndex + 1) == -1) { bool ok = false; *major = parseInt(QStringRef(&str, 0, dotIndex), &ok); if (ok) *minor = parseInt(QStringRef(&str, dotIndex + 1, str.length() - dotIndex - 1), &ok); return ok; } return false; } QString QmlLibraryDependency::path() const{ QStringList splitPath = m_uri.split('.'); QString res = splitPath.join(QLatin1Char('/')); if (res.isEmpty() && !splitPath.isEmpty()) return QLatin1String("/"); return res; } }// namespace
Java
package org.energy_home.dal.functions.data; import java.util.Map; import org.osgi.service.dal.FunctionData; public class DoorLockData extends FunctionData { public final static String STATUS_OPEN = "OPEN"; public final static String STATUS_CLOSED = "CLOSED"; private String status; public DoorLockData(long timestamp, Map metadata) { super(timestamp, metadata); } public DoorLockData(long timestamp, Map metadata, String status) { super(timestamp, metadata); this.status = status; } public String getStatus() { return this.status; } public int compareTo(Object o) { return 0; } }
Java
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "fasta.h" #include "util.h" fastap fa_alloc(int maxlen) { fastap fa; fa = (fastap) malloc(sizeof(struct fasta)); fa->id = (char *) malloc(maxlen+1); fa->data = (char *) malloc(maxlen+1); fa->maxlen = maxlen; return fa; } int fa_next(fastap seq,FILE *fd) { fgets(seq->id,seq->maxlen+1,fd); if (feof(fd)) { return 0; } seq->id[0] = ' '; /* white out the ">" */ stripWhiteSpace(seq->id); /* remove blank, newline */ fgets(seq->data,seq->maxlen+1,fd); stripWhiteSpace(seq->data); /* remove newline */ return 1; } void fa_fasta(fastap seq,FILE *fd) { fprintf(fd,">%s\n%s\n",seq->id,seq->data); } void fa_fasta_trunc(fastap seq,FILE *fd,int len) { seq->data[len] = 0; fprintf(fd,">%s\n%s\n",seq->id,seq->data); } void fa_free(fastap seq) { if (seq != NULL) { free(seq->id); free(seq->data); free(seq); } } void fa_mask(fastap seq,unsigned start,unsigned length,char mask) { unsigned i; unsigned seqlen; seqlen = strlen(seq->data); if (start >= seqlen) { return; /* can't start past the end of the sequence */ } if (length == 0 || /* default: from 'start' to end of sequence */ start + length > seqlen) { /* writing past end of sequence */ length = seqlen - start; } for (i=start;i<start+length;i++) { seq->data[i] = mask; } }
Java
.NOTPARALLEL : SOURCES_PATH ?= $(BASEDIR)/sources BASE_CACHE ?= $(BASEDIR)/built SDK_PATH ?= $(BASEDIR)/SDKs NO_QT ?= NO_WALLET ?= NO_UPNP ?= FALLBACK_DOWNLOAD_PATH ?= https://crimsoncore.org/depends-sources BUILD = $(shell ./config.guess) HOST ?= $(BUILD) PATCHES_PATH = $(BASEDIR)/patches BASEDIR = $(CURDIR) HASH_LENGTH:=11 DOWNLOAD_CONNECT_TIMEOUT:=10 DOWNLOAD_RETRIES:=3 HOST_ID_SALT ?= salt BUILD_ID_SALT ?= salt host:=$(BUILD) ifneq ($(HOST),) host:=$(HOST) host_toolchain:=$(HOST)- endif ifneq ($(DEBUG),) release_type=debug else release_type=release endif base_build_dir=$(BASEDIR)/work/build base_staging_dir=$(BASEDIR)/work/staging base_download_dir=$(BASEDIR)/work/download canonical_host:=$(shell ./config.sub $(HOST)) build:=$(shell ./config.sub $(BUILD)) build_arch =$(firstword $(subst -, ,$(build))) build_vendor=$(word 2,$(subst -, ,$(build))) full_build_os:=$(subst $(build_arch)-$(build_vendor)-,,$(build)) build_os:=$(findstring linux,$(full_build_os)) build_os+=$(findstring darwin,$(full_build_os)) build_os:=$(strip $(build_os)) ifeq ($(build_os),) build_os=$(full_build_os) endif host_arch=$(firstword $(subst -, ,$(canonical_host))) host_vendor=$(word 2,$(subst -, ,$(canonical_host))) full_host_os:=$(subst $(host_arch)-$(host_vendor)-,,$(canonical_host)) host_os:=$(findstring linux,$(full_host_os)) host_os+=$(findstring darwin,$(full_host_os)) host_os+=$(findstring mingw32,$(full_host_os)) host_os:=$(strip $(host_os)) ifeq ($(host_os),) host_os=$(full_host_os) endif $(host_arch)_$(host_os)_prefix=$(BASEDIR)/$(host) $(host_arch)_$(host_os)_host=$(host) host_prefix=$($(host_arch)_$(host_os)_prefix) build_prefix=$(host_prefix)/native build_host=$(build) AT_$(V):= AT_:=@ AT:=$(AT_$(V)) all: install include hosts/$(host_os).mk include hosts/default.mk include builders/$(build_os).mk include builders/default.mk include packages/packages.mk build_id_string:=$(BUILD_ID_SALT) build_id_string+=$(shell $(build_CC) --version 2>/dev/null) build_id_string+=$(shell $(build_AR) --version 2>/dev/null) build_id_string+=$(shell $(build_CXX) --version 2>/dev/null) build_id_string+=$(shell $(build_RANLIB) --version 2>/dev/null) build_id_string+=$(shell $(build_STRIP) --version 2>/dev/null) $(host_arch)_$(host_os)_id_string:=$(HOST_ID_SALT) $(host_arch)_$(host_os)_id_string+=$(shell $(host_CC) --version 2>/dev/null) $(host_arch)_$(host_os)_id_string+=$(shell $(host_AR) --version 2>/dev/null) $(host_arch)_$(host_os)_id_string+=$(shell $(host_CXX) --version 2>/dev/null) $(host_arch)_$(host_os)_id_string+=$(shell $(host_RANLIB) --version 2>/dev/null) $(host_arch)_$(host_os)_id_string+=$(shell $(host_STRIP) --version 2>/dev/null) qt_packages_$(NO_QT) = $(qt_packages) $(qt_$(host_os)_packages) $(qt_$(host_arch)_$(host_os)_packages) wallet_packages_$(NO_WALLET) = $(wallet_packages) upnp_packages_$(NO_UPNP) = $(upnp_packages) packages += $($(host_arch)_$(host_os)_packages) $($(host_os)_packages) $(qt_packages_) $(wallet_packages_) $(upnp_packages_) native_packages += $($(host_arch)_$(host_os)_native_packages) $($(host_os)_native_packages) ifneq ($(qt_packages_),) native_packages += $(qt_native_packages) endif all_packages = $(packages) $(native_packages) meta_depends = Makefile funcs.mk builders/default.mk hosts/default.mk hosts/$(host_os).mk builders/$(build_os).mk $(host_arch)_$(host_os)_native_toolchain?=$($(host_os)_native_toolchain) include funcs.mk toolchain_path=$($($(host_arch)_$(host_os)_native_toolchain)_prefixbin) final_build_id_long+=$(shell $(build_SHA256SUM) config.site.in) final_build_id+=$(shell echo -n "$(final_build_id_long)" | $(build_SHA256SUM) | cut -c-$(HASH_LENGTH)) $(host_prefix)/.stamp_$(final_build_id): $(native_packages) $(packages) $(AT)rm -rf $(@D) $(AT)mkdir -p $(@D) $(AT)echo copying packages: $^ $(AT)echo to: $(@D) $(AT)cd $(@D); $(foreach package,$^, tar xf $($(package)_cached); ) $(AT)touch $@ $(host_prefix)/share/config.site : config.site.in $(host_prefix)/.stamp_$(final_build_id) $(AT)@mkdir -p $(@D) $(AT)sed -e 's|@HOST@|$(host)|' \ -e 's|@CC@|$(toolchain_path)$(host_CC)|' \ -e 's|@CXX@|$(toolchain_path)$(host_CXX)|' \ -e 's|@AR@|$(toolchain_path)$(host_AR)|' \ -e 's|@RANLIB@|$(toolchain_path)$(host_RANLIB)|' \ -e 's|@NM@|$(toolchain_path)$(host_NM)|' \ -e 's|@STRIP@|$(toolchain_path)$(host_STRIP)|' \ -e 's|@build_os@|$(build_os)|' \ -e 's|@host_os@|$(host_os)|' \ -e 's|@CFLAGS@|$(strip $(host_CFLAGS) $(host_$(release_type)_CFLAGS))|' \ -e 's|@CXXFLAGS@|$(strip $(host_CXXFLAGS) $(host_$(release_type)_CXXFLAGS))|' \ -e 's|@CPPFLAGS@|$(strip $(host_CPPFLAGS) $(host_$(release_type)_CPPFLAGS))|' \ -e 's|@LDFLAGS@|$(strip $(host_LDFLAGS) $(host_$(release_type)_LDFLAGS))|' \ -e 's|@no_qt@|$(NO_QT)|' \ -e 's|@no_wallet@|$(NO_WALLET)|' \ -e 's|@no_upnp@|$(NO_UPNP)|' \ -e 's|@debug@|$(DEBUG)|' \ $< > $@ $(AT)touch $@ define check_or_remove_cached mkdir -p $(BASE_CACHE)/$(host)/$(package) && cd $(BASE_CACHE)/$(host)/$(package); \ $(build_SHA256SUM) -c $($(package)_cached_checksum) >/dev/null 2>/dev/null || \ ( rm -f $($(package)_cached_checksum); \ if test -f "$($(package)_cached)"; then echo "Checksum mismatch for $(package). Forcing rebuild.."; rm -f $($(package)_cached_checksum) $($(package)_cached); fi ) endef define check_or_remove_sources mkdir -p $($(package)_source_dir); cd $($(package)_source_dir); \ test -f $($(package)_fetched) && ( $(build_SHA256SUM) -c $($(package)_fetched) >/dev/null 2>/dev/null || \ ( echo "Checksum missing or mismatched for $(package) source. Forcing re-download."; \ rm -f $($(package)_all_sources) $($(1)_fetched))) || true endef check-packages: @$(foreach package,$(all_packages),$(call check_or_remove_cached,$(package));) check-sources: @$(foreach package,$(all_packages),$(call check_or_remove_sources,$(package));) $(host_prefix)/share/config.site: check-packages check-packages: check-sources install: check-packages $(host_prefix)/share/config.site download-one: check-sources $(all_sources) download-osx: @$(MAKE) -s HOST=x86_64-apple-darwin11 download-one download-linux: @$(MAKE) -s HOST=x86_64-unknown-linux-gnu download-one download-win: @$(MAKE) -s HOST=x86_64-w64-mingw32 download-one download: download-osx download-linux download-win .PHONY: install cached download-one download-osx download-linux download-win download check-packages check-sources
Java